]> granicus.if.org Git - postgresql/blob - src/pl/plpgsql/src/pl_exec.c
Make the order of the header file includes consistent in non-backend modules.
[postgresql] / src / pl / plpgsql / src / pl_exec.c
1 /*-------------------------------------------------------------------------
2  *
3  * pl_exec.c            - Executor for the PL/pgSQL
4  *                        procedural language
5  *
6  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/pl/plpgsql/src/pl_exec.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include <ctype.h>
19
20 #include "access/detoast.h"
21 #include "access/htup_details.h"
22 #include "access/transam.h"
23 #include "access/tupconvert.h"
24 #include "catalog/pg_proc.h"
25 #include "catalog/pg_type.h"
26 #include "commands/defrem.h"
27 #include "executor/execExpr.h"
28 #include "executor/spi.h"
29 #include "executor/spi_priv.h"
30 #include "funcapi.h"
31 #include "miscadmin.h"
32 #include "nodes/nodeFuncs.h"
33 #include "optimizer/optimizer.h"
34 #include "parser/parse_coerce.h"
35 #include "parser/parse_type.h"
36 #include "parser/scansup.h"
37 #include "plpgsql.h"
38 #include "storage/proc.h"
39 #include "tcop/tcopprot.h"
40 #include "tcop/utility.h"
41 #include "utils/array.h"
42 #include "utils/builtins.h"
43 #include "utils/datum.h"
44 #include "utils/fmgroids.h"
45 #include "utils/lsyscache.h"
46 #include "utils/memutils.h"
47 #include "utils/rel.h"
48 #include "utils/snapmgr.h"
49 #include "utils/syscache.h"
50 #include "utils/typcache.h"
51
52 typedef struct
53 {
54         int                     nargs;                  /* number of arguments */
55         Oid                *types;                      /* types of arguments */
56         Datum      *values;                     /* evaluated argument values */
57         char       *nulls;                      /* null markers (' '/'n' style) */
58 } PreparedParamsData;
59
60 /*
61  * All plpgsql function executions within a single transaction share the same
62  * executor EState for evaluating "simple" expressions.  Each function call
63  * creates its own "eval_econtext" ExprContext within this estate for
64  * per-evaluation workspace.  eval_econtext is freed at normal function exit,
65  * and the EState is freed at transaction end (in case of error, we assume
66  * that the abort mechanisms clean it all up).  Furthermore, any exception
67  * block within a function has to have its own eval_econtext separate from
68  * the containing function's, so that we can clean up ExprContext callbacks
69  * properly at subtransaction exit.  We maintain a stack that tracks the
70  * individual econtexts so that we can clean up correctly at subxact exit.
71  *
72  * This arrangement is a bit tedious to maintain, but it's worth the trouble
73  * so that we don't have to re-prepare simple expressions on each trip through
74  * a function.  (We assume the case to optimize is many repetitions of a
75  * function within a transaction.)
76  *
77  * However, there's no value in trying to amortize simple expression setup
78  * across multiple executions of a DO block (inline code block), since there
79  * can never be any.  If we use the shared EState for a DO block, the expr
80  * state trees are effectively leaked till end of transaction, and that can
81  * add up if the user keeps on submitting DO blocks.  Therefore, each DO block
82  * has its own simple-expression EState, which is cleaned up at exit from
83  * plpgsql_inline_handler().  DO blocks still use the simple_econtext_stack,
84  * though, so that subxact abort cleanup does the right thing.
85  */
86 typedef struct SimpleEcontextStackEntry
87 {
88         ExprContext *stack_econtext;    /* a stacked econtext */
89         SubTransactionId xact_subxid;   /* ID for current subxact */
90         struct SimpleEcontextStackEntry *next;  /* next stack entry up */
91 } SimpleEcontextStackEntry;
92
93 static EState *shared_simple_eval_estate = NULL;
94 static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
95
96 /*
97  * Memory management within a plpgsql function generally works with three
98  * contexts:
99  *
100  * 1. Function-call-lifespan data, such as variable values, is kept in the
101  * "main" context, a/k/a the "SPI Proc" context established by SPI_connect().
102  * This is usually the CurrentMemoryContext while running code in this module
103  * (which is not good, because careless coding can easily cause
104  * function-lifespan memory leaks, but we live with it for now).
105  *
106  * 2. Some statement-execution routines need statement-lifespan workspace.
107  * A suitable context is created on-demand by get_stmt_mcontext(), and must
108  * be reset at the end of the requesting routine.  Error recovery will clean
109  * it up automatically.  Nested statements requiring statement-lifespan
110  * workspace will result in a stack of such contexts, see push_stmt_mcontext().
111  *
112  * 3. We use the eval_econtext's per-tuple memory context for expression
113  * evaluation, and as a general-purpose workspace for short-lived allocations.
114  * Such allocations usually aren't explicitly freed, but are left to be
115  * cleaned up by a context reset, typically done by exec_eval_cleanup().
116  *
117  * These macros are for use in making short-lived allocations:
118  */
119 #define get_eval_mcontext(estate) \
120         ((estate)->eval_econtext->ecxt_per_tuple_memory)
121 #define eval_mcontext_alloc(estate, sz) \
122         MemoryContextAlloc(get_eval_mcontext(estate), sz)
123 #define eval_mcontext_alloc0(estate, sz) \
124         MemoryContextAllocZero(get_eval_mcontext(estate), sz)
125
126 /*
127  * We use a session-wide hash table for caching cast information.
128  *
129  * Once built, the compiled expression trees (cast_expr fields) survive for
130  * the life of the session.  At some point it might be worth invalidating
131  * those after pg_cast changes, but for the moment we don't bother.
132  *
133  * The evaluation state trees (cast_exprstate) are managed in the same way as
134  * simple expressions (i.e., we assume cast expressions are always simple).
135  *
136  * As with simple expressions, DO blocks don't use the shared hash table but
137  * must have their own.  This isn't ideal, but we don't want to deal with
138  * multiple simple_eval_estates within a DO block.
139  */
140 typedef struct                                  /* lookup key for cast info */
141 {
142         /* NB: we assume this struct contains no padding bytes */
143         Oid                     srctype;                /* source type for cast */
144         Oid                     dsttype;                /* destination type for cast */
145         int32           srctypmod;              /* source typmod for cast */
146         int32           dsttypmod;              /* destination typmod for cast */
147 } plpgsql_CastHashKey;
148
149 typedef struct                                  /* cast_hash table entry */
150 {
151         plpgsql_CastHashKey key;        /* hash key --- MUST BE FIRST */
152         Expr       *cast_expr;          /* cast expression, or NULL if no-op cast */
153         CachedExpression *cast_cexpr;   /* cached expression backing the above */
154         /* ExprState is valid only when cast_lxid matches current LXID */
155         ExprState  *cast_exprstate; /* expression's eval tree */
156         bool            cast_in_use;    /* true while we're executing eval tree */
157         LocalTransactionId cast_lxid;
158 } plpgsql_CastHashEntry;
159
160 static MemoryContext shared_cast_context = NULL;
161 static HTAB *shared_cast_hash = NULL;
162
163 /*
164  * LOOP_RC_PROCESSING encapsulates common logic for looping statements to
165  * handle return/exit/continue result codes from the loop body statement(s).
166  * It's meant to be used like this:
167  *
168  *              int rc = PLPGSQL_RC_OK;
169  *              for (...)
170  *              {
171  *                      ...
172  *                      rc = exec_stmts(estate, stmt->body);
173  *                      LOOP_RC_PROCESSING(stmt->label, break);
174  *                      ...
175  *              }
176  *              return rc;
177  *
178  * If execution of the loop should terminate, LOOP_RC_PROCESSING will execute
179  * "exit_action" (typically a "break" or "goto"), after updating "rc" to the
180  * value the current statement should return.  If execution should continue,
181  * LOOP_RC_PROCESSING will do nothing except reset "rc" to PLPGSQL_RC_OK.
182  *
183  * estate and rc are implicit arguments to the macro.
184  * estate->exitlabel is examined and possibly updated.
185  */
186 #define LOOP_RC_PROCESSING(looplabel, exit_action) \
187         if (rc == PLPGSQL_RC_RETURN) \
188         { \
189                 /* RETURN, so propagate RC_RETURN out */ \
190                 exit_action; \
191         } \
192         else if (rc == PLPGSQL_RC_EXIT) \
193         { \
194                 if (estate->exitlabel == NULL) \
195                 { \
196                         /* unlabelled EXIT terminates this loop */ \
197                         rc = PLPGSQL_RC_OK; \
198                         exit_action; \
199                 } \
200                 else if ((looplabel) != NULL && \
201                                  strcmp(looplabel, estate->exitlabel) == 0) \
202                 { \
203                         /* labelled EXIT matching this loop, so terminate loop */ \
204                         estate->exitlabel = NULL; \
205                         rc = PLPGSQL_RC_OK; \
206                         exit_action; \
207                 } \
208                 else \
209                 { \
210                         /* non-matching labelled EXIT, propagate RC_EXIT out */ \
211                         exit_action; \
212                 } \
213         } \
214         else if (rc == PLPGSQL_RC_CONTINUE) \
215         { \
216                 if (estate->exitlabel == NULL) \
217                 { \
218                         /* unlabelled CONTINUE matches this loop, so continue in loop */ \
219                         rc = PLPGSQL_RC_OK; \
220                 } \
221                 else if ((looplabel) != NULL && \
222                                  strcmp(looplabel, estate->exitlabel) == 0) \
223                 { \
224                         /* labelled CONTINUE matching this loop, so continue in loop */ \
225                         estate->exitlabel = NULL; \
226                         rc = PLPGSQL_RC_OK; \
227                 } \
228                 else \
229                 { \
230                         /* non-matching labelled CONTINUE, propagate RC_CONTINUE out */ \
231                         exit_action; \
232                 } \
233         } \
234         else \
235                 Assert(rc == PLPGSQL_RC_OK)
236
237 /************************************************************
238  * Local function forward declarations
239  ************************************************************/
240 static void coerce_function_result_tuple(PLpgSQL_execstate *estate,
241                                                                                  TupleDesc tupdesc);
242 static void plpgsql_exec_error_callback(void *arg);
243 static void copy_plpgsql_datums(PLpgSQL_execstate *estate,
244                                                                 PLpgSQL_function *func);
245 static void plpgsql_fulfill_promise(PLpgSQL_execstate *estate,
246                                                                         PLpgSQL_var *var);
247 static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate);
248 static void push_stmt_mcontext(PLpgSQL_execstate *estate);
249 static void pop_stmt_mcontext(PLpgSQL_execstate *estate);
250
251 static int      exec_stmt_block(PLpgSQL_execstate *estate,
252                                                         PLpgSQL_stmt_block *block);
253 static int      exec_stmts(PLpgSQL_execstate *estate,
254                                            List *stmts);
255 static int      exec_stmt(PLpgSQL_execstate *estate,
256                                           PLpgSQL_stmt *stmt);
257 static int      exec_stmt_assign(PLpgSQL_execstate *estate,
258                                                          PLpgSQL_stmt_assign *stmt);
259 static int      exec_stmt_perform(PLpgSQL_execstate *estate,
260                                                           PLpgSQL_stmt_perform *stmt);
261 static int      exec_stmt_call(PLpgSQL_execstate *estate,
262                                                    PLpgSQL_stmt_call *stmt);
263 static int      exec_stmt_getdiag(PLpgSQL_execstate *estate,
264                                                           PLpgSQL_stmt_getdiag *stmt);
265 static int      exec_stmt_if(PLpgSQL_execstate *estate,
266                                                  PLpgSQL_stmt_if *stmt);
267 static int      exec_stmt_case(PLpgSQL_execstate *estate,
268                                                    PLpgSQL_stmt_case *stmt);
269 static int      exec_stmt_loop(PLpgSQL_execstate *estate,
270                                                    PLpgSQL_stmt_loop *stmt);
271 static int      exec_stmt_while(PLpgSQL_execstate *estate,
272                                                         PLpgSQL_stmt_while *stmt);
273 static int      exec_stmt_fori(PLpgSQL_execstate *estate,
274                                                    PLpgSQL_stmt_fori *stmt);
275 static int      exec_stmt_fors(PLpgSQL_execstate *estate,
276                                                    PLpgSQL_stmt_fors *stmt);
277 static int      exec_stmt_forc(PLpgSQL_execstate *estate,
278                                                    PLpgSQL_stmt_forc *stmt);
279 static int      exec_stmt_foreach_a(PLpgSQL_execstate *estate,
280                                                                 PLpgSQL_stmt_foreach_a *stmt);
281 static int      exec_stmt_open(PLpgSQL_execstate *estate,
282                                                    PLpgSQL_stmt_open *stmt);
283 static int      exec_stmt_fetch(PLpgSQL_execstate *estate,
284                                                         PLpgSQL_stmt_fetch *stmt);
285 static int      exec_stmt_close(PLpgSQL_execstate *estate,
286                                                         PLpgSQL_stmt_close *stmt);
287 static int      exec_stmt_exit(PLpgSQL_execstate *estate,
288                                                    PLpgSQL_stmt_exit *stmt);
289 static int      exec_stmt_return(PLpgSQL_execstate *estate,
290                                                          PLpgSQL_stmt_return *stmt);
291 static int      exec_stmt_return_next(PLpgSQL_execstate *estate,
292                                                                   PLpgSQL_stmt_return_next *stmt);
293 static int      exec_stmt_return_query(PLpgSQL_execstate *estate,
294                                                                    PLpgSQL_stmt_return_query *stmt);
295 static int      exec_stmt_raise(PLpgSQL_execstate *estate,
296                                                         PLpgSQL_stmt_raise *stmt);
297 static int      exec_stmt_assert(PLpgSQL_execstate *estate,
298                                                          PLpgSQL_stmt_assert *stmt);
299 static int      exec_stmt_execsql(PLpgSQL_execstate *estate,
300                                                           PLpgSQL_stmt_execsql *stmt);
301 static int      exec_stmt_dynexecute(PLpgSQL_execstate *estate,
302                                                                  PLpgSQL_stmt_dynexecute *stmt);
303 static int      exec_stmt_dynfors(PLpgSQL_execstate *estate,
304                                                           PLpgSQL_stmt_dynfors *stmt);
305 static int      exec_stmt_commit(PLpgSQL_execstate *estate,
306                                                          PLpgSQL_stmt_commit *stmt);
307 static int      exec_stmt_rollback(PLpgSQL_execstate *estate,
308                                                            PLpgSQL_stmt_rollback *stmt);
309 static int      exec_stmt_set(PLpgSQL_execstate *estate,
310                                                   PLpgSQL_stmt_set *stmt);
311
312 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
313                                                                  PLpgSQL_function *func,
314                                                                  ReturnSetInfo *rsi,
315                                                                  EState *simple_eval_estate);
316 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
317
318 static void exec_prepare_plan(PLpgSQL_execstate *estate,
319                                                           PLpgSQL_expr *expr, int cursorOptions,
320                                                           bool keepplan);
321 static void exec_simple_check_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr);
322 static void exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan);
323 static void exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno);
324 static bool contains_target_param(Node *node, int *target_dno);
325 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
326                                                                   PLpgSQL_expr *expr,
327                                                                   Datum *result,
328                                                                   bool *isNull,
329                                                                   Oid *rettype,
330                                                                   int32 *rettypmod);
331
332 static void exec_assign_expr(PLpgSQL_execstate *estate,
333                                                          PLpgSQL_datum *target,
334                                                          PLpgSQL_expr *expr);
335 static void exec_assign_c_string(PLpgSQL_execstate *estate,
336                                                                  PLpgSQL_datum *target,
337                                                                  const char *str);
338 static void exec_assign_value(PLpgSQL_execstate *estate,
339                                                           PLpgSQL_datum *target,
340                                                           Datum value, bool isNull,
341                                                           Oid valtype, int32 valtypmod);
342 static void exec_eval_datum(PLpgSQL_execstate *estate,
343                                                         PLpgSQL_datum *datum,
344                                                         Oid *typeid,
345                                                         int32 *typetypmod,
346                                                         Datum *value,
347                                                         bool *isnull);
348 static int      exec_eval_integer(PLpgSQL_execstate *estate,
349                                                           PLpgSQL_expr *expr,
350                                                           bool *isNull);
351 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
352                                                           PLpgSQL_expr *expr,
353                                                           bool *isNull);
354 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
355                                                         PLpgSQL_expr *expr,
356                                                         bool *isNull,
357                                                         Oid *rettype,
358                                                         int32 *rettypmod);
359 static int      exec_run_select(PLpgSQL_execstate *estate,
360                                                         PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
361 static int      exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
362                                                    Portal portal, bool prefetch_ok);
363 static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
364                                                                           PLpgSQL_expr *expr);
365 static ParamExternData *plpgsql_param_fetch(ParamListInfo params,
366                                                                                         int paramid, bool speculative,
367                                                                                         ParamExternData *workspace);
368 static void plpgsql_param_compile(ParamListInfo params, Param *param,
369                                                                   ExprState *state,
370                                                                   Datum *resv, bool *resnull);
371 static void plpgsql_param_eval_var(ExprState *state, ExprEvalStep *op,
372                                                                    ExprContext *econtext);
373 static void plpgsql_param_eval_var_ro(ExprState *state, ExprEvalStep *op,
374                                                                           ExprContext *econtext);
375 static void plpgsql_param_eval_recfield(ExprState *state, ExprEvalStep *op,
376                                                                                 ExprContext *econtext);
377 static void plpgsql_param_eval_generic(ExprState *state, ExprEvalStep *op,
378                                                                            ExprContext *econtext);
379 static void plpgsql_param_eval_generic_ro(ExprState *state, ExprEvalStep *op,
380                                                                                   ExprContext *econtext);
381 static void exec_move_row(PLpgSQL_execstate *estate,
382                                                   PLpgSQL_variable *target,
383                                                   HeapTuple tup, TupleDesc tupdesc);
384 static void revalidate_rectypeid(PLpgSQL_rec *rec);
385 static ExpandedRecordHeader *make_expanded_record_for_rec(PLpgSQL_execstate *estate,
386                                                                                                                   PLpgSQL_rec *rec,
387                                                                                                                   TupleDesc srctupdesc,
388                                                                                                                   ExpandedRecordHeader *srcerh);
389 static void exec_move_row_from_fields(PLpgSQL_execstate *estate,
390                                                                           PLpgSQL_variable *target,
391                                                                           ExpandedRecordHeader *newerh,
392                                                                           Datum *values, bool *nulls,
393                                                                           TupleDesc tupdesc);
394 static bool compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc);
395 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
396                                                                          PLpgSQL_row *row,
397                                                                          TupleDesc tupdesc);
398 static TupleDesc deconstruct_composite_datum(Datum value,
399                                                                                          HeapTupleData *tmptup);
400 static void exec_move_row_from_datum(PLpgSQL_execstate *estate,
401                                                                          PLpgSQL_variable *target,
402                                                                          Datum value);
403 static void instantiate_empty_record_variable(PLpgSQL_execstate *estate,
404                                                                                           PLpgSQL_rec *rec);
405 static char *convert_value_to_string(PLpgSQL_execstate *estate,
406                                                                          Datum value, Oid valtype);
407 static Datum exec_cast_value(PLpgSQL_execstate *estate,
408                                                          Datum value, bool *isnull,
409                                                          Oid valtype, int32 valtypmod,
410                                                          Oid reqtype, int32 reqtypmod);
411 static plpgsql_CastHashEntry *get_cast_hashentry(PLpgSQL_execstate *estate,
412                                                                                                  Oid srctype, int32 srctypmod,
413                                                                                                  Oid dsttype, int32 dsttypmod);
414 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
415 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
416 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
417 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
418 static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
419                                                           Datum newvalue, bool isnull, bool freeable);
420 static void assign_text_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
421                                                         const char *str);
422 static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec,
423                                                           ExpandedRecordHeader *erh);
424 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
425                                                                                                   List *params);
426 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
427                                                                                 PLpgSQL_expr *dynquery, List *params,
428                                                                                 const char *portalname, int cursorOptions);
429 static char *format_expr_params(PLpgSQL_execstate *estate,
430                                                                 const PLpgSQL_expr *expr);
431 static char *format_preparedparamsdata(PLpgSQL_execstate *estate,
432                                                                            const PreparedParamsData *ppd);
433
434
435 /* ----------
436  * plpgsql_exec_function        Called by the call handler for
437  *                              function execution.
438  *
439  * This is also used to execute inline code blocks (DO blocks).  The only
440  * difference that this code is aware of is that for a DO block, we want
441  * to use a private simple_eval_estate, which is created and passed in by
442  * the caller.  For regular functions, pass NULL, which implies using
443  * shared_simple_eval_estate.  (When using a private simple_eval_estate,
444  * we must also use a private cast hashtable, but that's taken care of
445  * within plpgsql_estate_setup.)
446  * ----------
447  */
448 Datum
449 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
450                                           EState *simple_eval_estate, bool atomic)
451 {
452         PLpgSQL_execstate estate;
453         ErrorContextCallback plerrcontext;
454         int                     i;
455         int                     rc;
456
457         /*
458          * Setup the execution state
459          */
460         plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo,
461                                                  simple_eval_estate);
462         estate.atomic = atomic;
463
464         /*
465          * Setup error traceback support for ereport()
466          */
467         plerrcontext.callback = plpgsql_exec_error_callback;
468         plerrcontext.arg = &estate;
469         plerrcontext.previous = error_context_stack;
470         error_context_stack = &plerrcontext;
471
472         /*
473          * Make local execution copies of all the datums
474          */
475         estate.err_text = gettext_noop("during initialization of execution state");
476         copy_plpgsql_datums(&estate, func);
477
478         /*
479          * Store the actual call argument values into the appropriate variables
480          */
481         estate.err_text = gettext_noop("while storing call arguments into local variables");
482         for (i = 0; i < func->fn_nargs; i++)
483         {
484                 int                     n = func->fn_argvarnos[i];
485
486                 switch (estate.datums[n]->dtype)
487                 {
488                         case PLPGSQL_DTYPE_VAR:
489                                 {
490                                         PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
491
492                                         assign_simple_var(&estate, var,
493                                                                           fcinfo->args[i].value,
494                                                                           fcinfo->args[i].isnull,
495                                                                           false);
496
497                                         /*
498                                          * Force any array-valued parameter to be stored in
499                                          * expanded form in our local variable, in hopes of
500                                          * improving efficiency of uses of the variable.  (This is
501                                          * a hack, really: why only arrays? Need more thought
502                                          * about which cases are likely to win.  See also
503                                          * typisarray-specific heuristic in exec_assign_value.)
504                                          *
505                                          * Special cases: If passed a R/W expanded pointer, assume
506                                          * we can commandeer the object rather than having to copy
507                                          * it.  If passed a R/O expanded pointer, just keep it as
508                                          * the value of the variable for the moment.  (We'll force
509                                          * it to R/W if the variable gets modified, but that may
510                                          * very well never happen.)
511                                          */
512                                         if (!var->isnull && var->datatype->typisarray)
513                                         {
514                                                 if (VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(var->value)))
515                                                 {
516                                                         /* take ownership of R/W object */
517                                                         assign_simple_var(&estate, var,
518                                                                                           TransferExpandedObject(var->value,
519                                                                                                                                          estate.datum_context),
520                                                                                           false,
521                                                                                           true);
522                                                 }
523                                                 else if (VARATT_IS_EXTERNAL_EXPANDED_RO(DatumGetPointer(var->value)))
524                                                 {
525                                                         /* R/O pointer, keep it as-is until assigned to */
526                                                 }
527                                                 else
528                                                 {
529                                                         /* flat array, so force to expanded form */
530                                                         assign_simple_var(&estate, var,
531                                                                                           expand_array(var->value,
532                                                                                                                    estate.datum_context,
533                                                                                                                    NULL),
534                                                                                           false,
535                                                                                           true);
536                                                 }
537                                         }
538                                 }
539                                 break;
540
541                         case PLPGSQL_DTYPE_REC:
542                                 {
543                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) estate.datums[n];
544
545                                         if (!fcinfo->args[i].isnull)
546                                         {
547                                                 /* Assign row value from composite datum */
548                                                 exec_move_row_from_datum(&estate,
549                                                                                                  (PLpgSQL_variable *) rec,
550                                                                                                  fcinfo->args[i].value);
551                                         }
552                                         else
553                                         {
554                                                 /* If arg is null, set variable to null */
555                                                 exec_move_row(&estate, (PLpgSQL_variable *) rec,
556                                                                           NULL, NULL);
557                                         }
558                                         /* clean up after exec_move_row() */
559                                         exec_eval_cleanup(&estate);
560                                 }
561                                 break;
562
563                         default:
564                                 /* Anything else should not be an argument variable */
565                                 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
566                 }
567         }
568
569         estate.err_text = gettext_noop("during function entry");
570
571         /*
572          * Set the magic variable FOUND to false
573          */
574         exec_set_found(&estate, false);
575
576         /*
577          * Let the instrumentation plugin peek at this function
578          */
579         if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
580                 ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
581
582         /*
583          * Now call the toplevel block of statements
584          */
585         estate.err_text = NULL;
586         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
587         rc = exec_stmt(&estate, (PLpgSQL_stmt *) func->action);
588         if (rc != PLPGSQL_RC_RETURN)
589         {
590                 estate.err_stmt = NULL;
591                 estate.err_text = NULL;
592                 ereport(ERROR,
593                                 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
594                                  errmsg("control reached end of function without RETURN")));
595         }
596
597         /*
598          * We got a return value - process it
599          */
600         estate.err_stmt = NULL;
601         estate.err_text = gettext_noop("while casting return value to function's return type");
602
603         fcinfo->isnull = estate.retisnull;
604
605         if (estate.retisset)
606         {
607                 ReturnSetInfo *rsi = estate.rsi;
608
609                 /* Check caller can handle a set result */
610                 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
611                         (rsi->allowedModes & SFRM_Materialize) == 0)
612                         ereport(ERROR,
613                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
614                                          errmsg("set-valued function called in context that cannot accept a set")));
615                 rsi->returnMode = SFRM_Materialize;
616
617                 /* If we produced any tuples, send back the result */
618                 if (estate.tuple_store)
619                 {
620                         MemoryContext oldcxt;
621
622                         rsi->setResult = estate.tuple_store;
623                         oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
624                         rsi->setDesc = CreateTupleDescCopy(estate.tuple_store_desc);
625                         MemoryContextSwitchTo(oldcxt);
626                 }
627                 estate.retval = (Datum) 0;
628                 fcinfo->isnull = true;
629         }
630         else if (!estate.retisnull)
631         {
632                 /*
633                  * Cast result value to function's declared result type, and copy it
634                  * out to the upper executor memory context.  We must treat tuple
635                  * results specially in order to deal with cases like rowtypes
636                  * involving dropped columns.
637                  */
638                 if (estate.retistuple)
639                 {
640                         /* Don't need coercion if rowtype is known to match */
641                         if (func->fn_rettype == estate.rettype &&
642                                 func->fn_rettype != RECORDOID)
643                         {
644                                 /*
645                                  * Copy the tuple result into upper executor memory context.
646                                  * However, if we have a R/W expanded datum, we can just
647                                  * transfer its ownership out to the upper context.
648                                  */
649                                 estate.retval = SPI_datumTransfer(estate.retval,
650                                                                                                   false,
651                                                                                                   -1);
652                         }
653                         else
654                         {
655                                 /*
656                                  * Need to look up the expected result type.  XXX would be
657                                  * better to cache the tupdesc instead of repeating
658                                  * get_call_result_type(), but the only easy place to save it
659                                  * is in the PLpgSQL_function struct, and that's too
660                                  * long-lived: composite types could change during the
661                                  * existence of a PLpgSQL_function.
662                                  */
663                                 Oid                     resultTypeId;
664                                 TupleDesc       tupdesc;
665
666                                 switch (get_call_result_type(fcinfo, &resultTypeId, &tupdesc))
667                                 {
668                                         case TYPEFUNC_COMPOSITE:
669                                                 /* got the expected result rowtype, now coerce it */
670                                                 coerce_function_result_tuple(&estate, tupdesc);
671                                                 break;
672                                         case TYPEFUNC_COMPOSITE_DOMAIN:
673                                                 /* got the expected result rowtype, now coerce it */
674                                                 coerce_function_result_tuple(&estate, tupdesc);
675                                                 /* and check domain constraints */
676                                                 /* XXX allowing caching here would be good, too */
677                                                 domain_check(estate.retval, false, resultTypeId,
678                                                                          NULL, NULL);
679                                                 break;
680                                         case TYPEFUNC_RECORD:
681
682                                                 /*
683                                                  * Failed to determine actual type of RECORD.  We
684                                                  * could raise an error here, but what this means in
685                                                  * practice is that the caller is expecting any old
686                                                  * generic rowtype, so we don't really need to be
687                                                  * restrictive.  Pass back the generated result as-is.
688                                                  */
689                                                 estate.retval = SPI_datumTransfer(estate.retval,
690                                                                                                                   false,
691                                                                                                                   -1);
692                                                 break;
693                                         default:
694                                                 /* shouldn't get here if retistuple is true ... */
695                                                 elog(ERROR, "return type must be a row type");
696                                                 break;
697                                 }
698                         }
699                 }
700                 else
701                 {
702                         /* Scalar case: use exec_cast_value */
703                         estate.retval = exec_cast_value(&estate,
704                                                                                         estate.retval,
705                                                                                         &fcinfo->isnull,
706                                                                                         estate.rettype,
707                                                                                         -1,
708                                                                                         func->fn_rettype,
709                                                                                         -1);
710
711                         /*
712                          * If the function's return type isn't by value, copy the value
713                          * into upper executor memory context.  However, if we have a R/W
714                          * expanded datum, we can just transfer its ownership out to the
715                          * upper executor context.
716                          */
717                         if (!fcinfo->isnull && !func->fn_retbyval)
718                                 estate.retval = SPI_datumTransfer(estate.retval,
719                                                                                                   false,
720                                                                                                   func->fn_rettyplen);
721                 }
722         }
723         else
724         {
725                 /*
726                  * We're returning a NULL, which normally requires no conversion work
727                  * regardless of datatypes.  But, if we are casting it to a domain
728                  * return type, we'd better check that the domain's constraints pass.
729                  */
730                 if (func->fn_retisdomain)
731                         estate.retval = exec_cast_value(&estate,
732                                                                                         estate.retval,
733                                                                                         &fcinfo->isnull,
734                                                                                         estate.rettype,
735                                                                                         -1,
736                                                                                         func->fn_rettype,
737                                                                                         -1);
738         }
739
740         estate.err_text = gettext_noop("during function exit");
741
742         /*
743          * Let the instrumentation plugin peek at this function
744          */
745         if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
746                 ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
747
748         /* Clean up any leftover temporary memory */
749         plpgsql_destroy_econtext(&estate);
750         exec_eval_cleanup(&estate);
751         /* stmt_mcontext will be destroyed when function's main context is */
752
753         /*
754          * Pop the error context stack
755          */
756         error_context_stack = plerrcontext.previous;
757
758         /*
759          * Return the function's result
760          */
761         return estate.retval;
762 }
763
764 /*
765  * Helper for plpgsql_exec_function: coerce composite result to the specified
766  * tuple descriptor, and copy it out to upper executor memory.  This is split
767  * out mostly for cosmetic reasons --- the logic would be very deeply nested
768  * otherwise.
769  *
770  * estate->retval is updated in-place.
771  */
772 static void
773 coerce_function_result_tuple(PLpgSQL_execstate *estate, TupleDesc tupdesc)
774 {
775         HeapTuple       rettup;
776         TupleDesc       retdesc;
777         TupleConversionMap *tupmap;
778
779         /* We assume exec_stmt_return verified that result is composite */
780         Assert(type_is_rowtype(estate->rettype));
781
782         /* We can special-case expanded records for speed */
783         if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(estate->retval)))
784         {
785                 ExpandedRecordHeader *erh = (ExpandedRecordHeader *) DatumGetEOHP(estate->retval);
786
787                 Assert(erh->er_magic == ER_MAGIC);
788
789                 /* Extract record's TupleDesc */
790                 retdesc = expanded_record_get_tupdesc(erh);
791
792                 /* check rowtype compatibility */
793                 tupmap = convert_tuples_by_position(retdesc,
794                                                                                         tupdesc,
795                                                                                         gettext_noop("returned record type does not match expected record type"));
796
797                 /* it might need conversion */
798                 if (tupmap)
799                 {
800                         rettup = expanded_record_get_tuple(erh);
801                         Assert(rettup);
802                         rettup = execute_attr_map_tuple(rettup, tupmap);
803
804                         /*
805                          * Copy tuple to upper executor memory, as a tuple Datum.  Make
806                          * sure it is labeled with the caller-supplied tuple type.
807                          */
808                         estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
809                         /* no need to free map, we're about to return anyway */
810                 }
811                 else if (!(tupdesc->tdtypeid == erh->er_decltypeid ||
812                                    (tupdesc->tdtypeid == RECORDOID &&
813                                         !ExpandedRecordIsDomain(erh))))
814                 {
815                         /*
816                          * The expanded record has the right physical tupdesc, but the
817                          * wrong type ID.  (Typically, the expanded record is RECORDOID
818                          * but the function is declared to return a named composite type.
819                          * As in exec_move_row_from_datum, we don't allow returning a
820                          * composite-domain record from a function declared to return
821                          * RECORD.)  So we must flatten the record to a tuple datum and
822                          * overwrite its type fields with the right thing.  spi.c doesn't
823                          * provide any easy way to deal with this case, so we end up
824                          * duplicating the guts of datumCopy() :-(
825                          */
826                         Size            resultsize;
827                         HeapTupleHeader tuphdr;
828
829                         resultsize = EOH_get_flat_size(&erh->hdr);
830                         tuphdr = (HeapTupleHeader) SPI_palloc(resultsize);
831                         EOH_flatten_into(&erh->hdr, (void *) tuphdr, resultsize);
832                         HeapTupleHeaderSetTypeId(tuphdr, tupdesc->tdtypeid);
833                         HeapTupleHeaderSetTypMod(tuphdr, tupdesc->tdtypmod);
834                         estate->retval = PointerGetDatum(tuphdr);
835                 }
836                 else
837                 {
838                         /*
839                          * We need only copy result into upper executor memory context.
840                          * However, if we have a R/W expanded datum, we can just transfer
841                          * its ownership out to the upper executor context.
842                          */
843                         estate->retval = SPI_datumTransfer(estate->retval,
844                                                                                            false,
845                                                                                            -1);
846                 }
847         }
848         else
849         {
850                 /* Convert composite datum to a HeapTuple and TupleDesc */
851                 HeapTupleData tmptup;
852
853                 retdesc = deconstruct_composite_datum(estate->retval, &tmptup);
854                 rettup = &tmptup;
855
856                 /* check rowtype compatibility */
857                 tupmap = convert_tuples_by_position(retdesc,
858                                                                                         tupdesc,
859                                                                                         gettext_noop("returned record type does not match expected record type"));
860
861                 /* it might need conversion */
862                 if (tupmap)
863                         rettup = execute_attr_map_tuple(rettup, tupmap);
864
865                 /*
866                  * Copy tuple to upper executor memory, as a tuple Datum.  Make sure
867                  * it is labeled with the caller-supplied tuple type.
868                  */
869                 estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
870
871                 /* no need to free map, we're about to return anyway */
872
873                 ReleaseTupleDesc(retdesc);
874         }
875 }
876
877
878 /* ----------
879  * plpgsql_exec_trigger         Called by the call handler for
880  *                              trigger execution.
881  * ----------
882  */
883 HeapTuple
884 plpgsql_exec_trigger(PLpgSQL_function *func,
885                                          TriggerData *trigdata)
886 {
887         PLpgSQL_execstate estate;
888         ErrorContextCallback plerrcontext;
889         int                     rc;
890         TupleDesc       tupdesc;
891         PLpgSQL_rec *rec_new,
892                            *rec_old;
893         HeapTuple       rettup;
894
895         /*
896          * Setup the execution state
897          */
898         plpgsql_estate_setup(&estate, func, NULL, NULL);
899         estate.trigdata = trigdata;
900
901         /*
902          * Setup error traceback support for ereport()
903          */
904         plerrcontext.callback = plpgsql_exec_error_callback;
905         plerrcontext.arg = &estate;
906         plerrcontext.previous = error_context_stack;
907         error_context_stack = &plerrcontext;
908
909         /*
910          * Make local execution copies of all the datums
911          */
912         estate.err_text = gettext_noop("during initialization of execution state");
913         copy_plpgsql_datums(&estate, func);
914
915         /*
916          * Put the OLD and NEW tuples into record variables
917          *
918          * We set up expanded records for both variables even though only one may
919          * have a value.  This allows record references to succeed in functions
920          * that are used for multiple trigger types.  For example, we might have a
921          * test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')", which should
922          * work regardless of the current trigger type.  If a value is actually
923          * fetched from an unsupplied tuple, it will read as NULL.
924          */
925         tupdesc = RelationGetDescr(trigdata->tg_relation);
926
927         rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
928         rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
929
930         rec_new->erh = make_expanded_record_from_tupdesc(tupdesc,
931                                                                                                          estate.datum_context);
932         rec_old->erh = make_expanded_record_from_exprecord(rec_new->erh,
933                                                                                                            estate.datum_context);
934
935         if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
936         {
937                 /*
938                  * Per-statement triggers don't use OLD/NEW variables
939                  */
940         }
941         else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
942         {
943                 expanded_record_set_tuple(rec_new->erh, trigdata->tg_trigtuple,
944                                                                   false, false);
945         }
946         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
947         {
948                 expanded_record_set_tuple(rec_new->erh, trigdata->tg_newtuple,
949                                                                   false, false);
950                 expanded_record_set_tuple(rec_old->erh, trigdata->tg_trigtuple,
951                                                                   false, false);
952
953                 /*
954                  * In BEFORE trigger, stored generated columns are not computed yet,
955                  * so make them null in the NEW row.  (Only needed in UPDATE branch;
956                  * in the INSERT case, they are already null, but in UPDATE, the field
957                  * still contains the old value.)  Alternatively, we could construct a
958                  * whole new row structure without the generated columns, but this way
959                  * seems more efficient and potentially less confusing.
960                  */
961                 if (tupdesc->constr && tupdesc->constr->has_generated_stored &&
962                         TRIGGER_FIRED_BEFORE(trigdata->tg_event))
963                 {
964                         for (int i = 0; i < tupdesc->natts; i++)
965                                 if (TupleDescAttr(tupdesc, i)->attgenerated == ATTRIBUTE_GENERATED_STORED)
966                                         expanded_record_set_field_internal(rec_new->erh,
967                                                                                                            i + 1,
968                                                                                                            (Datum) 0,
969                                                                                                            true,        /* isnull */
970                                                                                                            false, false);
971                 }
972         }
973         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
974         {
975                 expanded_record_set_tuple(rec_old->erh, trigdata->tg_trigtuple,
976                                                                   false, false);
977         }
978         else
979                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
980
981         /* Make transition tables visible to this SPI connection */
982         rc = SPI_register_trigger_data(trigdata);
983         Assert(rc >= 0);
984
985         estate.err_text = gettext_noop("during function entry");
986
987         /*
988          * Set the magic variable FOUND to false
989          */
990         exec_set_found(&estate, false);
991
992         /*
993          * Let the instrumentation plugin peek at this function
994          */
995         if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
996                 ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
997
998         /*
999          * Now call the toplevel block of statements
1000          */
1001         estate.err_text = NULL;
1002         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
1003         rc = exec_stmt(&estate, (PLpgSQL_stmt *) func->action);
1004         if (rc != PLPGSQL_RC_RETURN)
1005         {
1006                 estate.err_stmt = NULL;
1007                 estate.err_text = NULL;
1008                 ereport(ERROR,
1009                                 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
1010                                  errmsg("control reached end of trigger procedure without RETURN")));
1011         }
1012
1013         estate.err_stmt = NULL;
1014         estate.err_text = gettext_noop("during function exit");
1015
1016         if (estate.retisset)
1017                 ereport(ERROR,
1018                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1019                                  errmsg("trigger procedure cannot return a set")));
1020
1021         /*
1022          * Check that the returned tuple structure has the same attributes, the
1023          * relation that fired the trigger has. A per-statement trigger always
1024          * needs to return NULL, so we ignore any return value the function itself
1025          * produces (XXX: is this a good idea?)
1026          *
1027          * XXX This way it is possible, that the trigger returns a tuple where
1028          * attributes don't have the correct atttypmod's length. It's up to the
1029          * trigger's programmer to ensure that this doesn't happen. Jan
1030          */
1031         if (estate.retisnull || !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
1032                 rettup = NULL;
1033         else
1034         {
1035                 TupleDesc       retdesc;
1036                 TupleConversionMap *tupmap;
1037
1038                 /* We assume exec_stmt_return verified that result is composite */
1039                 Assert(type_is_rowtype(estate.rettype));
1040
1041                 /* We can special-case expanded records for speed */
1042                 if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(estate.retval)))
1043                 {
1044                         ExpandedRecordHeader *erh = (ExpandedRecordHeader *) DatumGetEOHP(estate.retval);
1045
1046                         Assert(erh->er_magic == ER_MAGIC);
1047
1048                         /* Extract HeapTuple and TupleDesc */
1049                         rettup = expanded_record_get_tuple(erh);
1050                         Assert(rettup);
1051                         retdesc = expanded_record_get_tupdesc(erh);
1052
1053                         if (retdesc != RelationGetDescr(trigdata->tg_relation))
1054                         {
1055                                 /* check rowtype compatibility */
1056                                 tupmap = convert_tuples_by_position(retdesc,
1057                                                                                                         RelationGetDescr(trigdata->tg_relation),
1058                                                                                                         gettext_noop("returned row structure does not match the structure of the triggering table"));
1059                                 /* it might need conversion */
1060                                 if (tupmap)
1061                                         rettup = execute_attr_map_tuple(rettup, tupmap);
1062                                 /* no need to free map, we're about to return anyway */
1063                         }
1064
1065                         /*
1066                          * Copy tuple to upper executor memory.  But if user just did
1067                          * "return new" or "return old" without changing anything, there's
1068                          * no need to copy; we can return the original tuple (which will
1069                          * save a few cycles in trigger.c as well as here).
1070                          */
1071                         if (rettup != trigdata->tg_newtuple &&
1072                                 rettup != trigdata->tg_trigtuple)
1073                                 rettup = SPI_copytuple(rettup);
1074                 }
1075                 else
1076                 {
1077                         /* Convert composite datum to a HeapTuple and TupleDesc */
1078                         HeapTupleData tmptup;
1079
1080                         retdesc = deconstruct_composite_datum(estate.retval, &tmptup);
1081                         rettup = &tmptup;
1082
1083                         /* check rowtype compatibility */
1084                         tupmap = convert_tuples_by_position(retdesc,
1085                                                                                                 RelationGetDescr(trigdata->tg_relation),
1086                                                                                                 gettext_noop("returned row structure does not match the structure of the triggering table"));
1087                         /* it might need conversion */
1088                         if (tupmap)
1089                                 rettup = execute_attr_map_tuple(rettup, tupmap);
1090
1091                         ReleaseTupleDesc(retdesc);
1092                         /* no need to free map, we're about to return anyway */
1093
1094                         /* Copy tuple to upper executor memory */
1095                         rettup = SPI_copytuple(rettup);
1096                 }
1097         }
1098
1099         /*
1100          * Let the instrumentation plugin peek at this function
1101          */
1102         if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
1103                 ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
1104
1105         /* Clean up any leftover temporary memory */
1106         plpgsql_destroy_econtext(&estate);
1107         exec_eval_cleanup(&estate);
1108         /* stmt_mcontext will be destroyed when function's main context is */
1109
1110         /*
1111          * Pop the error context stack
1112          */
1113         error_context_stack = plerrcontext.previous;
1114
1115         /*
1116          * Return the trigger's result
1117          */
1118         return rettup;
1119 }
1120
1121 /* ----------
1122  * plpgsql_exec_event_trigger           Called by the call handler for
1123  *                              event trigger execution.
1124  * ----------
1125  */
1126 void
1127 plpgsql_exec_event_trigger(PLpgSQL_function *func, EventTriggerData *trigdata)
1128 {
1129         PLpgSQL_execstate estate;
1130         ErrorContextCallback plerrcontext;
1131         int                     rc;
1132
1133         /*
1134          * Setup the execution state
1135          */
1136         plpgsql_estate_setup(&estate, func, NULL, NULL);
1137         estate.evtrigdata = trigdata;
1138
1139         /*
1140          * Setup error traceback support for ereport()
1141          */
1142         plerrcontext.callback = plpgsql_exec_error_callback;
1143         plerrcontext.arg = &estate;
1144         plerrcontext.previous = error_context_stack;
1145         error_context_stack = &plerrcontext;
1146
1147         /*
1148          * Make local execution copies of all the datums
1149          */
1150         estate.err_text = gettext_noop("during initialization of execution state");
1151         copy_plpgsql_datums(&estate, func);
1152
1153         /*
1154          * Let the instrumentation plugin peek at this function
1155          */
1156         if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
1157                 ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
1158
1159         /*
1160          * Now call the toplevel block of statements
1161          */
1162         estate.err_text = NULL;
1163         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
1164         rc = exec_stmt(&estate, (PLpgSQL_stmt *) func->action);
1165         if (rc != PLPGSQL_RC_RETURN)
1166         {
1167                 estate.err_stmt = NULL;
1168                 estate.err_text = NULL;
1169                 ereport(ERROR,
1170                                 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
1171                                  errmsg("control reached end of trigger procedure without RETURN")));
1172         }
1173
1174         estate.err_stmt = NULL;
1175         estate.err_text = gettext_noop("during function exit");
1176
1177         /*
1178          * Let the instrumentation plugin peek at this function
1179          */
1180         if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
1181                 ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
1182
1183         /* Clean up any leftover temporary memory */
1184         plpgsql_destroy_econtext(&estate);
1185         exec_eval_cleanup(&estate);
1186         /* stmt_mcontext will be destroyed when function's main context is */
1187
1188         /*
1189          * Pop the error context stack
1190          */
1191         error_context_stack = plerrcontext.previous;
1192
1193         return;
1194 }
1195
1196 /*
1197  * error context callback to let us supply a call-stack traceback
1198  */
1199 static void
1200 plpgsql_exec_error_callback(void *arg)
1201 {
1202         PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
1203
1204         if (estate->err_text != NULL)
1205         {
1206                 /*
1207                  * We don't expend the cycles to run gettext() on err_text unless we
1208                  * actually need it.  Therefore, places that set up err_text should
1209                  * use gettext_noop() to ensure the strings get recorded in the
1210                  * message dictionary.
1211                  *
1212                  * If both err_text and err_stmt are set, use the err_text as
1213                  * description, but report the err_stmt's line number.  When err_stmt
1214                  * is not set, we're in function entry/exit, or some such place not
1215                  * attached to a specific line number.
1216                  */
1217                 if (estate->err_stmt != NULL)
1218                 {
1219                         /*
1220                          * translator: last %s is a phrase such as "during statement block
1221                          * local variable initialization"
1222                          */
1223                         errcontext("PL/pgSQL function %s line %d %s",
1224                                            estate->func->fn_signature,
1225                                            estate->err_stmt->lineno,
1226                                            _(estate->err_text));
1227                 }
1228                 else
1229                 {
1230                         /*
1231                          * translator: last %s is a phrase such as "while storing call
1232                          * arguments into local variables"
1233                          */
1234                         errcontext("PL/pgSQL function %s %s",
1235                                            estate->func->fn_signature,
1236                                            _(estate->err_text));
1237                 }
1238         }
1239         else if (estate->err_stmt != NULL)
1240         {
1241                 /* translator: last %s is a plpgsql statement type name */
1242                 errcontext("PL/pgSQL function %s line %d at %s",
1243                                    estate->func->fn_signature,
1244                                    estate->err_stmt->lineno,
1245                                    plpgsql_stmt_typename(estate->err_stmt));
1246         }
1247         else
1248                 errcontext("PL/pgSQL function %s",
1249                                    estate->func->fn_signature);
1250 }
1251
1252
1253 /* ----------
1254  * Support function for initializing local execution variables
1255  * ----------
1256  */
1257 static void
1258 copy_plpgsql_datums(PLpgSQL_execstate *estate,
1259                                         PLpgSQL_function *func)
1260 {
1261         int                     ndatums = estate->ndatums;
1262         PLpgSQL_datum **indatums;
1263         PLpgSQL_datum **outdatums;
1264         char       *workspace;
1265         char       *ws_next;
1266         int                     i;
1267
1268         /* Allocate local datum-pointer array */
1269         estate->datums = (PLpgSQL_datum **)
1270                 palloc(sizeof(PLpgSQL_datum *) * ndatums);
1271
1272         /*
1273          * To reduce palloc overhead, we make a single palloc request for all the
1274          * space needed for locally-instantiated datums.
1275          */
1276         workspace = palloc(func->copiable_size);
1277         ws_next = workspace;
1278
1279         /* Fill datum-pointer array, copying datums into workspace as needed */
1280         indatums = func->datums;
1281         outdatums = estate->datums;
1282         for (i = 0; i < ndatums; i++)
1283         {
1284                 PLpgSQL_datum *indatum = indatums[i];
1285                 PLpgSQL_datum *outdatum;
1286
1287                 /* This must agree with plpgsql_finish_datums on what is copiable */
1288                 switch (indatum->dtype)
1289                 {
1290                         case PLPGSQL_DTYPE_VAR:
1291                         case PLPGSQL_DTYPE_PROMISE:
1292                                 outdatum = (PLpgSQL_datum *) ws_next;
1293                                 memcpy(outdatum, indatum, sizeof(PLpgSQL_var));
1294                                 ws_next += MAXALIGN(sizeof(PLpgSQL_var));
1295                                 break;
1296
1297                         case PLPGSQL_DTYPE_REC:
1298                                 outdatum = (PLpgSQL_datum *) ws_next;
1299                                 memcpy(outdatum, indatum, sizeof(PLpgSQL_rec));
1300                                 ws_next += MAXALIGN(sizeof(PLpgSQL_rec));
1301                                 break;
1302
1303                         case PLPGSQL_DTYPE_ROW:
1304                         case PLPGSQL_DTYPE_RECFIELD:
1305                         case PLPGSQL_DTYPE_ARRAYELEM:
1306
1307                                 /*
1308                                  * These datum records are read-only at runtime, so no need to
1309                                  * copy them (well, RECFIELD and ARRAYELEM contain cached
1310                                  * data, but we'd just as soon centralize the caching anyway).
1311                                  */
1312                                 outdatum = indatum;
1313                                 break;
1314
1315                         default:
1316                                 elog(ERROR, "unrecognized dtype: %d", indatum->dtype);
1317                                 outdatum = NULL;        /* keep compiler quiet */
1318                                 break;
1319                 }
1320
1321                 outdatums[i] = outdatum;
1322         }
1323
1324         Assert(ws_next == workspace + func->copiable_size);
1325 }
1326
1327 /*
1328  * If the variable has an armed "promise", compute the promised value
1329  * and assign it to the variable.
1330  * The assignment automatically disarms the promise.
1331  */
1332 static void
1333 plpgsql_fulfill_promise(PLpgSQL_execstate *estate,
1334                                                 PLpgSQL_var *var)
1335 {
1336         MemoryContext oldcontext;
1337
1338         if (var->promise == PLPGSQL_PROMISE_NONE)
1339                 return;                                 /* nothing to do */
1340
1341         /*
1342          * This will typically be invoked in a short-lived context such as the
1343          * mcontext.  We must create variable values in the estate's datum
1344          * context.  This quick-and-dirty solution risks leaking some additional
1345          * cruft there, but since any one promise is honored at most once per
1346          * function call, it's probably not worth being more careful.
1347          */
1348         oldcontext = MemoryContextSwitchTo(estate->datum_context);
1349
1350         switch (var->promise)
1351         {
1352                 case PLPGSQL_PROMISE_TG_NAME:
1353                         if (estate->trigdata == NULL)
1354                                 elog(ERROR, "trigger promise is not in a trigger function");
1355                         assign_simple_var(estate, var,
1356                                                           DirectFunctionCall1(namein,
1357                                                                                                   CStringGetDatum(estate->trigdata->tg_trigger->tgname)),
1358                                                           false, true);
1359                         break;
1360
1361                 case PLPGSQL_PROMISE_TG_WHEN:
1362                         if (estate->trigdata == NULL)
1363                                 elog(ERROR, "trigger promise is not in a trigger function");
1364                         if (TRIGGER_FIRED_BEFORE(estate->trigdata->tg_event))
1365                                 assign_text_var(estate, var, "BEFORE");
1366                         else if (TRIGGER_FIRED_AFTER(estate->trigdata->tg_event))
1367                                 assign_text_var(estate, var, "AFTER");
1368                         else if (TRIGGER_FIRED_INSTEAD(estate->trigdata->tg_event))
1369                                 assign_text_var(estate, var, "INSTEAD OF");
1370                         else
1371                                 elog(ERROR, "unrecognized trigger execution time: not BEFORE, AFTER, or INSTEAD OF");
1372                         break;
1373
1374                 case PLPGSQL_PROMISE_TG_LEVEL:
1375                         if (estate->trigdata == NULL)
1376                                 elog(ERROR, "trigger promise is not in a trigger function");
1377                         if (TRIGGER_FIRED_FOR_ROW(estate->trigdata->tg_event))
1378                                 assign_text_var(estate, var, "ROW");
1379                         else if (TRIGGER_FIRED_FOR_STATEMENT(estate->trigdata->tg_event))
1380                                 assign_text_var(estate, var, "STATEMENT");
1381                         else
1382                                 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
1383                         break;
1384
1385                 case PLPGSQL_PROMISE_TG_OP:
1386                         if (estate->trigdata == NULL)
1387                                 elog(ERROR, "trigger promise is not in a trigger function");
1388                         if (TRIGGER_FIRED_BY_INSERT(estate->trigdata->tg_event))
1389                                 assign_text_var(estate, var, "INSERT");
1390                         else if (TRIGGER_FIRED_BY_UPDATE(estate->trigdata->tg_event))
1391                                 assign_text_var(estate, var, "UPDATE");
1392                         else if (TRIGGER_FIRED_BY_DELETE(estate->trigdata->tg_event))
1393                                 assign_text_var(estate, var, "DELETE");
1394                         else if (TRIGGER_FIRED_BY_TRUNCATE(estate->trigdata->tg_event))
1395                                 assign_text_var(estate, var, "TRUNCATE");
1396                         else
1397                                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
1398                         break;
1399
1400                 case PLPGSQL_PROMISE_TG_RELID:
1401                         if (estate->trigdata == NULL)
1402                                 elog(ERROR, "trigger promise is not in a trigger function");
1403                         assign_simple_var(estate, var,
1404                                                           ObjectIdGetDatum(estate->trigdata->tg_relation->rd_id),
1405                                                           false, false);
1406                         break;
1407
1408                 case PLPGSQL_PROMISE_TG_TABLE_NAME:
1409                         if (estate->trigdata == NULL)
1410                                 elog(ERROR, "trigger promise is not in a trigger function");
1411                         assign_simple_var(estate, var,
1412                                                           DirectFunctionCall1(namein,
1413                                                                                                   CStringGetDatum(RelationGetRelationName(estate->trigdata->tg_relation))),
1414                                                           false, true);
1415                         break;
1416
1417                 case PLPGSQL_PROMISE_TG_TABLE_SCHEMA:
1418                         if (estate->trigdata == NULL)
1419                                 elog(ERROR, "trigger promise is not in a trigger function");
1420                         assign_simple_var(estate, var,
1421                                                           DirectFunctionCall1(namein,
1422                                                                                                   CStringGetDatum(get_namespace_name(RelationGetNamespace(estate->trigdata->tg_relation)))),
1423                                                           false, true);
1424                         break;
1425
1426                 case PLPGSQL_PROMISE_TG_NARGS:
1427                         if (estate->trigdata == NULL)
1428                                 elog(ERROR, "trigger promise is not in a trigger function");
1429                         assign_simple_var(estate, var,
1430                                                           Int16GetDatum(estate->trigdata->tg_trigger->tgnargs),
1431                                                           false, false);
1432                         break;
1433
1434                 case PLPGSQL_PROMISE_TG_ARGV:
1435                         if (estate->trigdata == NULL)
1436                                 elog(ERROR, "trigger promise is not in a trigger function");
1437                         if (estate->trigdata->tg_trigger->tgnargs > 0)
1438                         {
1439                                 /*
1440                                  * For historical reasons, tg_argv[] subscripts start at zero
1441                                  * not one.  So we can't use construct_array().
1442                                  */
1443                                 int                     nelems = estate->trigdata->tg_trigger->tgnargs;
1444                                 Datum      *elems;
1445                                 int                     dims[1];
1446                                 int                     lbs[1];
1447                                 int                     i;
1448
1449                                 elems = palloc(sizeof(Datum) * nelems);
1450                                 for (i = 0; i < nelems; i++)
1451                                         elems[i] = CStringGetTextDatum(estate->trigdata->tg_trigger->tgargs[i]);
1452                                 dims[0] = nelems;
1453                                 lbs[0] = 0;
1454
1455                                 assign_simple_var(estate, var,
1456                                                                   PointerGetDatum(construct_md_array(elems, NULL,
1457                                                                                                                                          1, dims, lbs,
1458                                                                                                                                          TEXTOID,
1459                                                                                                                                          -1, false, 'i')),
1460                                                                   false, true);
1461                         }
1462                         else
1463                         {
1464                                 assign_simple_var(estate, var, (Datum) 0, true, false);
1465                         }
1466                         break;
1467
1468                 case PLPGSQL_PROMISE_TG_EVENT:
1469                         if (estate->evtrigdata == NULL)
1470                                 elog(ERROR, "event trigger promise is not in an event trigger function");
1471                         assign_text_var(estate, var, estate->evtrigdata->event);
1472                         break;
1473
1474                 case PLPGSQL_PROMISE_TG_TAG:
1475                         if (estate->evtrigdata == NULL)
1476                                 elog(ERROR, "event trigger promise is not in an event trigger function");
1477                         assign_text_var(estate, var, estate->evtrigdata->tag);
1478                         break;
1479
1480                 default:
1481                         elog(ERROR, "unrecognized promise type: %d", var->promise);
1482         }
1483
1484         MemoryContextSwitchTo(oldcontext);
1485 }
1486
1487 /*
1488  * Create a memory context for statement-lifespan variables, if we don't
1489  * have one already.  It will be a child of stmt_mcontext_parent, which is
1490  * either the function's main context or a pushed-down outer stmt_mcontext.
1491  */
1492 static MemoryContext
1493 get_stmt_mcontext(PLpgSQL_execstate *estate)
1494 {
1495         if (estate->stmt_mcontext == NULL)
1496         {
1497                 estate->stmt_mcontext =
1498                         AllocSetContextCreate(estate->stmt_mcontext_parent,
1499                                                                   "PLpgSQL per-statement data",
1500                                                                   ALLOCSET_DEFAULT_SIZES);
1501         }
1502         return estate->stmt_mcontext;
1503 }
1504
1505 /*
1506  * Push down the current stmt_mcontext so that called statements won't use it.
1507  * This is needed by statements that have statement-lifespan data and need to
1508  * preserve it across some inner statements.  The caller should eventually do
1509  * pop_stmt_mcontext().
1510  */
1511 static void
1512 push_stmt_mcontext(PLpgSQL_execstate *estate)
1513 {
1514         /* Should have done get_stmt_mcontext() first */
1515         Assert(estate->stmt_mcontext != NULL);
1516         /* Assert we've not messed up the stack linkage */
1517         Assert(MemoryContextGetParent(estate->stmt_mcontext) == estate->stmt_mcontext_parent);
1518         /* Push it down to become the parent of any nested stmt mcontext */
1519         estate->stmt_mcontext_parent = estate->stmt_mcontext;
1520         /* And make it not available for use directly */
1521         estate->stmt_mcontext = NULL;
1522 }
1523
1524 /*
1525  * Undo push_stmt_mcontext().  We assume this is done just before or after
1526  * resetting the caller's stmt_mcontext; since that action will also delete
1527  * any child contexts, there's no need to explicitly delete whatever context
1528  * might currently be estate->stmt_mcontext.
1529  */
1530 static void
1531 pop_stmt_mcontext(PLpgSQL_execstate *estate)
1532 {
1533         /* We need only pop the stack */
1534         estate->stmt_mcontext = estate->stmt_mcontext_parent;
1535         estate->stmt_mcontext_parent = MemoryContextGetParent(estate->stmt_mcontext);
1536 }
1537
1538
1539 /*
1540  * Subroutine for exec_stmt_block: does any condition in the condition list
1541  * match the current exception?
1542  */
1543 static bool
1544 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
1545 {
1546         for (; cond != NULL; cond = cond->next)
1547         {
1548                 int                     sqlerrstate = cond->sqlerrstate;
1549
1550                 /*
1551                  * OTHERS matches everything *except* query-canceled and
1552                  * assert-failure.  If you're foolish enough, you can match those
1553                  * explicitly.
1554                  */
1555                 if (sqlerrstate == 0)
1556                 {
1557                         if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED &&
1558                                 edata->sqlerrcode != ERRCODE_ASSERT_FAILURE)
1559                                 return true;
1560                 }
1561                 /* Exact match? */
1562                 else if (edata->sqlerrcode == sqlerrstate)
1563                         return true;
1564                 /* Category match? */
1565                 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
1566                                  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
1567                         return true;
1568         }
1569         return false;
1570 }
1571
1572
1573 /* ----------
1574  * exec_stmt_block                      Execute a block of statements
1575  * ----------
1576  */
1577 static int
1578 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
1579 {
1580         volatile int rc = -1;
1581         int                     i;
1582
1583         /*
1584          * First initialize all variables declared in this block
1585          */
1586         estate->err_text = gettext_noop("during statement block local variable initialization");
1587
1588         for (i = 0; i < block->n_initvars; i++)
1589         {
1590                 int                     n = block->initvarnos[i];
1591                 PLpgSQL_datum *datum = estate->datums[n];
1592
1593                 /*
1594                  * The set of dtypes handled here must match plpgsql_add_initdatums().
1595                  *
1596                  * Note that we currently don't support promise datums within blocks,
1597                  * only at a function's outermost scope, so we needn't handle those
1598                  * here.
1599                  */
1600                 switch (datum->dtype)
1601                 {
1602                         case PLPGSQL_DTYPE_VAR:
1603                                 {
1604                                         PLpgSQL_var *var = (PLpgSQL_var *) datum;
1605
1606                                         /*
1607                                          * Free any old value, in case re-entering block, and
1608                                          * initialize to NULL
1609                                          */
1610                                         assign_simple_var(estate, var, (Datum) 0, true, false);
1611
1612                                         if (var->default_val == NULL)
1613                                         {
1614                                                 /*
1615                                                  * If needed, give the datatype a chance to reject
1616                                                  * NULLs, by assigning a NULL to the variable.  We
1617                                                  * claim the value is of type UNKNOWN, not the var's
1618                                                  * datatype, else coercion will be skipped.
1619                                                  */
1620                                                 if (var->datatype->typtype == TYPTYPE_DOMAIN)
1621                                                         exec_assign_value(estate,
1622                                                                                           (PLpgSQL_datum *) var,
1623                                                                                           (Datum) 0,
1624                                                                                           true,
1625                                                                                           UNKNOWNOID,
1626                                                                                           -1);
1627
1628                                                 /* parser should have rejected NOT NULL */
1629                                                 Assert(!var->notnull);
1630                                         }
1631                                         else
1632                                         {
1633                                                 exec_assign_expr(estate, (PLpgSQL_datum *) var,
1634                                                                                  var->default_val);
1635                                         }
1636                                 }
1637                                 break;
1638
1639                         case PLPGSQL_DTYPE_REC:
1640                                 {
1641                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
1642
1643                                         /*
1644                                          * Deletion of any existing object will be handled during
1645                                          * the assignments below, and in some cases it's more
1646                                          * efficient for us not to get rid of it beforehand.
1647                                          */
1648                                         if (rec->default_val == NULL)
1649                                         {
1650                                                 /*
1651                                                  * If needed, give the datatype a chance to reject
1652                                                  * NULLs, by assigning a NULL to the variable.
1653                                                  */
1654                                                 exec_move_row(estate, (PLpgSQL_variable *) rec,
1655                                                                           NULL, NULL);
1656
1657                                                 /* parser should have rejected NOT NULL */
1658                                                 Assert(!rec->notnull);
1659                                         }
1660                                         else
1661                                         {
1662                                                 exec_assign_expr(estate, (PLpgSQL_datum *) rec,
1663                                                                                  rec->default_val);
1664                                         }
1665                                 }
1666                                 break;
1667
1668                         default:
1669                                 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
1670                 }
1671         }
1672
1673         if (block->exceptions)
1674         {
1675                 /*
1676                  * Execute the statements in the block's body inside a sub-transaction
1677                  */
1678                 MemoryContext oldcontext = CurrentMemoryContext;
1679                 ResourceOwner oldowner = CurrentResourceOwner;
1680                 ExprContext *old_eval_econtext = estate->eval_econtext;
1681                 ErrorData  *save_cur_error = estate->cur_error;
1682                 MemoryContext stmt_mcontext;
1683
1684                 estate->err_text = gettext_noop("during statement block entry");
1685
1686                 /*
1687                  * We will need a stmt_mcontext to hold the error data if an error
1688                  * occurs.  It seems best to force it to exist before entering the
1689                  * subtransaction, so that we reduce the risk of out-of-memory during
1690                  * error recovery, and because this greatly simplifies restoring the
1691                  * stmt_mcontext stack to the correct state after an error.  We can
1692                  * ameliorate the cost of this by allowing the called statements to
1693                  * use this mcontext too; so we don't push it down here.
1694                  */
1695                 stmt_mcontext = get_stmt_mcontext(estate);
1696
1697                 BeginInternalSubTransaction(NULL);
1698                 /* Want to run statements inside function's memory context */
1699                 MemoryContextSwitchTo(oldcontext);
1700
1701                 PG_TRY();
1702                 {
1703                         /*
1704                          * We need to run the block's statements with a new eval_econtext
1705                          * that belongs to the current subtransaction; if we try to use
1706                          * the outer econtext then ExprContext shutdown callbacks will be
1707                          * called at the wrong times.
1708                          */
1709                         plpgsql_create_econtext(estate);
1710
1711                         estate->err_text = NULL;
1712
1713                         /* Run the block's statements */
1714                         rc = exec_stmts(estate, block->body);
1715
1716                         estate->err_text = gettext_noop("during statement block exit");
1717
1718                         /*
1719                          * If the block ended with RETURN, we may need to copy the return
1720                          * value out of the subtransaction eval_context.  We can avoid a
1721                          * physical copy if the value happens to be a R/W expanded object.
1722                          */
1723                         if (rc == PLPGSQL_RC_RETURN &&
1724                                 !estate->retisset &&
1725                                 !estate->retisnull)
1726                         {
1727                                 int16           resTypLen;
1728                                 bool            resTypByVal;
1729
1730                                 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1731                                 estate->retval = datumTransfer(estate->retval,
1732                                                                                            resTypByVal, resTypLen);
1733                         }
1734
1735                         /* Commit the inner transaction, return to outer xact context */
1736                         ReleaseCurrentSubTransaction();
1737                         MemoryContextSwitchTo(oldcontext);
1738                         CurrentResourceOwner = oldowner;
1739
1740                         /* Assert that the stmt_mcontext stack is unchanged */
1741                         Assert(stmt_mcontext == estate->stmt_mcontext);
1742
1743                         /*
1744                          * Revert to outer eval_econtext.  (The inner one was
1745                          * automatically cleaned up during subxact exit.)
1746                          */
1747                         estate->eval_econtext = old_eval_econtext;
1748                 }
1749                 PG_CATCH();
1750                 {
1751                         ErrorData  *edata;
1752                         ListCell   *e;
1753
1754                         estate->err_text = gettext_noop("during exception cleanup");
1755
1756                         /* Save error info in our stmt_mcontext */
1757                         MemoryContextSwitchTo(stmt_mcontext);
1758                         edata = CopyErrorData();
1759                         FlushErrorState();
1760
1761                         /* Abort the inner transaction */
1762                         RollbackAndReleaseCurrentSubTransaction();
1763                         MemoryContextSwitchTo(oldcontext);
1764                         CurrentResourceOwner = oldowner;
1765
1766                         /*
1767                          * Set up the stmt_mcontext stack as though we had restored our
1768                          * previous state and then done push_stmt_mcontext().  The push is
1769                          * needed so that statements in the exception handler won't
1770                          * clobber the error data that's in our stmt_mcontext.
1771                          */
1772                         estate->stmt_mcontext_parent = stmt_mcontext;
1773                         estate->stmt_mcontext = NULL;
1774
1775                         /*
1776                          * Now we can delete any nested stmt_mcontexts that might have
1777                          * been created as children of ours.  (Note: we do not immediately
1778                          * release any statement-lifespan data that might have been left
1779                          * behind in stmt_mcontext itself.  We could attempt that by doing
1780                          * a MemoryContextReset on it before collecting the error data
1781                          * above, but it seems too risky to do any significant amount of
1782                          * work before collecting the error.)
1783                          */
1784                         MemoryContextDeleteChildren(stmt_mcontext);
1785
1786                         /* Revert to outer eval_econtext */
1787                         estate->eval_econtext = old_eval_econtext;
1788
1789                         /*
1790                          * Must clean up the econtext too.  However, any tuple table made
1791                          * in the subxact will have been thrown away by SPI during subxact
1792                          * abort, so we don't need to (and mustn't try to) free the
1793                          * eval_tuptable.
1794                          */
1795                         estate->eval_tuptable = NULL;
1796                         exec_eval_cleanup(estate);
1797
1798                         /* Look for a matching exception handler */
1799                         foreach(e, block->exceptions->exc_list)
1800                         {
1801                                 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1802
1803                                 if (exception_matches_conditions(edata, exception->conditions))
1804                                 {
1805                                         /*
1806                                          * Initialize the magic SQLSTATE and SQLERRM variables for
1807                                          * the exception block; this also frees values from any
1808                                          * prior use of the same exception. We needn't do this
1809                                          * until we have found a matching exception.
1810                                          */
1811                                         PLpgSQL_var *state_var;
1812                                         PLpgSQL_var *errm_var;
1813
1814                                         state_var = (PLpgSQL_var *)
1815                                                 estate->datums[block->exceptions->sqlstate_varno];
1816                                         errm_var = (PLpgSQL_var *)
1817                                                 estate->datums[block->exceptions->sqlerrm_varno];
1818
1819                                         assign_text_var(estate, state_var,
1820                                                                         unpack_sql_state(edata->sqlerrcode));
1821                                         assign_text_var(estate, errm_var, edata->message);
1822
1823                                         /*
1824                                          * Also set up cur_error so the error data is accessible
1825                                          * inside the handler.
1826                                          */
1827                                         estate->cur_error = edata;
1828
1829                                         estate->err_text = NULL;
1830
1831                                         rc = exec_stmts(estate, exception->action);
1832
1833                                         break;
1834                                 }
1835                         }
1836
1837                         /*
1838                          * Restore previous state of cur_error, whether or not we executed
1839                          * a handler.  This is needed in case an error got thrown from
1840                          * some inner block's exception handler.
1841                          */
1842                         estate->cur_error = save_cur_error;
1843
1844                         /* If no match found, re-throw the error */
1845                         if (e == NULL)
1846                                 ReThrowError(edata);
1847
1848                         /* Restore stmt_mcontext stack and release the error data */
1849                         pop_stmt_mcontext(estate);
1850                         MemoryContextReset(stmt_mcontext);
1851                 }
1852                 PG_END_TRY();
1853
1854                 Assert(save_cur_error == estate->cur_error);
1855         }
1856         else
1857         {
1858                 /*
1859                  * Just execute the statements in the block's body
1860                  */
1861                 estate->err_text = NULL;
1862
1863                 rc = exec_stmts(estate, block->body);
1864         }
1865
1866         estate->err_text = NULL;
1867
1868         /*
1869          * Handle the return code.  This is intentionally different from
1870          * LOOP_RC_PROCESSING(): CONTINUE never matches a block, and EXIT matches
1871          * a block only if there is a label match.
1872          */
1873         switch (rc)
1874         {
1875                 case PLPGSQL_RC_OK:
1876                 case PLPGSQL_RC_RETURN:
1877                 case PLPGSQL_RC_CONTINUE:
1878                         return rc;
1879
1880                 case PLPGSQL_RC_EXIT:
1881                         if (estate->exitlabel == NULL)
1882                                 return PLPGSQL_RC_EXIT;
1883                         if (block->label == NULL)
1884                                 return PLPGSQL_RC_EXIT;
1885                         if (strcmp(block->label, estate->exitlabel) != 0)
1886                                 return PLPGSQL_RC_EXIT;
1887                         estate->exitlabel = NULL;
1888                         return PLPGSQL_RC_OK;
1889
1890                 default:
1891                         elog(ERROR, "unrecognized rc: %d", rc);
1892         }
1893
1894         return PLPGSQL_RC_OK;
1895 }
1896
1897
1898 /* ----------
1899  * exec_stmts                   Iterate over a list of statements
1900  *                              as long as their return code is OK
1901  * ----------
1902  */
1903 static int
1904 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1905 {
1906         ListCell   *s;
1907
1908         if (stmts == NIL)
1909         {
1910                 /*
1911                  * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1912                  * statement.  This prevents hangup in a tight loop if, for instance,
1913                  * there is a LOOP construct with an empty body.
1914                  */
1915                 CHECK_FOR_INTERRUPTS();
1916                 return PLPGSQL_RC_OK;
1917         }
1918
1919         foreach(s, stmts)
1920         {
1921                 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1922                 int                     rc = exec_stmt(estate, stmt);
1923
1924                 if (rc != PLPGSQL_RC_OK)
1925                         return rc;
1926         }
1927
1928         return PLPGSQL_RC_OK;
1929 }
1930
1931
1932 /* ----------
1933  * exec_stmt                    Distribute one statement to the statements
1934  *                              type specific execution function.
1935  * ----------
1936  */
1937 static int
1938 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1939 {
1940         PLpgSQL_stmt *save_estmt;
1941         int                     rc = -1;
1942
1943         save_estmt = estate->err_stmt;
1944         estate->err_stmt = stmt;
1945
1946         /* Let the plugin know that we are about to execute this statement */
1947         if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_beg)
1948                 ((*plpgsql_plugin_ptr)->stmt_beg) (estate, stmt);
1949
1950         CHECK_FOR_INTERRUPTS();
1951
1952         switch (stmt->cmd_type)
1953         {
1954                 case PLPGSQL_STMT_BLOCK:
1955                         rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1956                         break;
1957
1958                 case PLPGSQL_STMT_ASSIGN:
1959                         rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1960                         break;
1961
1962                 case PLPGSQL_STMT_PERFORM:
1963                         rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1964                         break;
1965
1966                 case PLPGSQL_STMT_CALL:
1967                         rc = exec_stmt_call(estate, (PLpgSQL_stmt_call *) stmt);
1968                         break;
1969
1970                 case PLPGSQL_STMT_GETDIAG:
1971                         rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1972                         break;
1973
1974                 case PLPGSQL_STMT_IF:
1975                         rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1976                         break;
1977
1978                 case PLPGSQL_STMT_CASE:
1979                         rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1980                         break;
1981
1982                 case PLPGSQL_STMT_LOOP:
1983                         rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1984                         break;
1985
1986                 case PLPGSQL_STMT_WHILE:
1987                         rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1988                         break;
1989
1990                 case PLPGSQL_STMT_FORI:
1991                         rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1992                         break;
1993
1994                 case PLPGSQL_STMT_FORS:
1995                         rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1996                         break;
1997
1998                 case PLPGSQL_STMT_FORC:
1999                         rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
2000                         break;
2001
2002                 case PLPGSQL_STMT_FOREACH_A:
2003                         rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
2004                         break;
2005
2006                 case PLPGSQL_STMT_EXIT:
2007                         rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
2008                         break;
2009
2010                 case PLPGSQL_STMT_RETURN:
2011                         rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
2012                         break;
2013
2014                 case PLPGSQL_STMT_RETURN_NEXT:
2015                         rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
2016                         break;
2017
2018                 case PLPGSQL_STMT_RETURN_QUERY:
2019                         rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
2020                         break;
2021
2022                 case PLPGSQL_STMT_RAISE:
2023                         rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
2024                         break;
2025
2026                 case PLPGSQL_STMT_ASSERT:
2027                         rc = exec_stmt_assert(estate, (PLpgSQL_stmt_assert *) stmt);
2028                         break;
2029
2030                 case PLPGSQL_STMT_EXECSQL:
2031                         rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
2032                         break;
2033
2034                 case PLPGSQL_STMT_DYNEXECUTE:
2035                         rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
2036                         break;
2037
2038                 case PLPGSQL_STMT_DYNFORS:
2039                         rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
2040                         break;
2041
2042                 case PLPGSQL_STMT_OPEN:
2043                         rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
2044                         break;
2045
2046                 case PLPGSQL_STMT_FETCH:
2047                         rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
2048                         break;
2049
2050                 case PLPGSQL_STMT_CLOSE:
2051                         rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
2052                         break;
2053
2054                 case PLPGSQL_STMT_COMMIT:
2055                         rc = exec_stmt_commit(estate, (PLpgSQL_stmt_commit *) stmt);
2056                         break;
2057
2058                 case PLPGSQL_STMT_ROLLBACK:
2059                         rc = exec_stmt_rollback(estate, (PLpgSQL_stmt_rollback *) stmt);
2060                         break;
2061
2062                 case PLPGSQL_STMT_SET:
2063                         rc = exec_stmt_set(estate, (PLpgSQL_stmt_set *) stmt);
2064                         break;
2065
2066                 default:
2067                         estate->err_stmt = save_estmt;
2068                         elog(ERROR, "unrecognized cmd_type: %d", stmt->cmd_type);
2069         }
2070
2071         /* Let the plugin know that we have finished executing this statement */
2072         if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_end)
2073                 ((*plpgsql_plugin_ptr)->stmt_end) (estate, stmt);
2074
2075         estate->err_stmt = save_estmt;
2076
2077         return rc;
2078 }
2079
2080
2081 /* ----------
2082  * exec_stmt_assign                     Evaluate an expression and
2083  *                                      put the result into a variable.
2084  * ----------
2085  */
2086 static int
2087 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
2088 {
2089         Assert(stmt->varno >= 0);
2090
2091         exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
2092
2093         return PLPGSQL_RC_OK;
2094 }
2095
2096 /* ----------
2097  * exec_stmt_perform            Evaluate query and discard result (but set
2098  *                                                      FOUND depending on whether at least one row
2099  *                                                      was returned).
2100  * ----------
2101  */
2102 static int
2103 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
2104 {
2105         PLpgSQL_expr *expr = stmt->expr;
2106
2107         (void) exec_run_select(estate, expr, 0, NULL);
2108         exec_set_found(estate, (estate->eval_processed != 0));
2109         exec_eval_cleanup(estate);
2110
2111         return PLPGSQL_RC_OK;
2112 }
2113
2114 /*
2115  * exec_stmt_call
2116  */
2117 static int
2118 exec_stmt_call(PLpgSQL_execstate *estate, PLpgSQL_stmt_call *stmt)
2119 {
2120         PLpgSQL_expr *expr = stmt->expr;
2121         volatile LocalTransactionId before_lxid;
2122         LocalTransactionId after_lxid;
2123         volatile bool pushed_active_snap = false;
2124         volatile int rc;
2125
2126         /* PG_TRY to ensure we clear the plan link, if needed, on failure */
2127         PG_TRY();
2128         {
2129                 SPIPlanPtr      plan = expr->plan;
2130                 ParamListInfo paramLI;
2131
2132                 if (plan == NULL)
2133                 {
2134
2135                         /*
2136                          * Don't save the plan if not in atomic context.  Otherwise,
2137                          * transaction ends would cause errors about plancache leaks.
2138                          *
2139                          * XXX This would be fixable with some plancache/resowner surgery
2140                          * elsewhere, but for now we'll just work around this here.
2141                          */
2142                         exec_prepare_plan(estate, expr, 0, estate->atomic);
2143
2144                         /*
2145                          * The procedure call could end transactions, which would upset
2146                          * the snapshot management in SPI_execute*, so don't let it do it.
2147                          * Instead, we set the snapshots ourselves below.
2148                          */
2149                         plan = expr->plan;
2150                         plan->no_snapshots = true;
2151
2152                         /*
2153                          * Force target to be recalculated whenever the plan changes, in
2154                          * case the procedure's argument list has changed.
2155                          */
2156                         stmt->target = NULL;
2157                 }
2158
2159                 /*
2160                  * We construct a DTYPE_ROW datum representing the plpgsql variables
2161                  * associated with the procedure's output arguments.  Then we can use
2162                  * exec_move_row() to do the assignments.
2163                  */
2164                 if (stmt->is_call && stmt->target == NULL)
2165                 {
2166                         Node       *node;
2167                         FuncExpr   *funcexpr;
2168                         HeapTuple       func_tuple;
2169                         List       *funcargs;
2170                         Oid                *argtypes;
2171                         char      **argnames;
2172                         char       *argmodes;
2173                         MemoryContext oldcontext;
2174                         PLpgSQL_row *row;
2175                         int                     nfields;
2176                         int                     i;
2177                         ListCell   *lc;
2178
2179                         /*
2180                          * Get the parsed CallStmt, and look up the called procedure
2181                          */
2182                         node = linitial_node(Query,
2183                                                                  ((CachedPlanSource *) linitial(plan->plancache_list))->query_list)->utilityStmt;
2184                         if (node == NULL || !IsA(node, CallStmt))
2185                                 elog(ERROR, "query for CALL statement is not a CallStmt");
2186
2187                         funcexpr = ((CallStmt *) node)->funcexpr;
2188
2189                         func_tuple = SearchSysCache1(PROCOID,
2190                                                                                  ObjectIdGetDatum(funcexpr->funcid));
2191                         if (!HeapTupleIsValid(func_tuple))
2192                                 elog(ERROR, "cache lookup failed for function %u",
2193                                          funcexpr->funcid);
2194
2195                         /*
2196                          * Extract function arguments, and expand any named-arg notation
2197                          */
2198                         funcargs = expand_function_arguments(funcexpr->args,
2199                                                                                                  funcexpr->funcresulttype,
2200                                                                                                  func_tuple);
2201
2202                         /*
2203                          * Get the argument names and modes, too
2204                          */
2205                         get_func_arg_info(func_tuple, &argtypes, &argnames, &argmodes);
2206
2207                         ReleaseSysCache(func_tuple);
2208
2209                         /*
2210                          * Begin constructing row Datum
2211                          */
2212                         oldcontext = MemoryContextSwitchTo(estate->func->fn_cxt);
2213
2214                         row = (PLpgSQL_row *) palloc0(sizeof(PLpgSQL_row));
2215                         row->dtype = PLPGSQL_DTYPE_ROW;
2216                         row->refname = "(unnamed row)";
2217                         row->lineno = -1;
2218                         row->varnos = (int *) palloc(sizeof(int) * list_length(funcargs));
2219
2220                         MemoryContextSwitchTo(oldcontext);
2221
2222                         /*
2223                          * Examine procedure's argument list.  Each output arg position
2224                          * should be an unadorned plpgsql variable (Datum), which we can
2225                          * insert into the row Datum.
2226                          */
2227                         nfields = 0;
2228                         i = 0;
2229                         foreach(lc, funcargs)
2230                         {
2231                                 Node       *n = lfirst(lc);
2232
2233                                 if (argmodes &&
2234                                         (argmodes[i] == PROARGMODE_INOUT ||
2235                                          argmodes[i] == PROARGMODE_OUT))
2236                                 {
2237                                         if (IsA(n, Param))
2238                                         {
2239                                                 Param      *param = (Param *) n;
2240
2241                                                 /* paramid is offset by 1 (see make_datum_param()) */
2242                                                 row->varnos[nfields++] = param->paramid - 1;
2243                                         }
2244                                         else
2245                                         {
2246                                                 /* report error using parameter name, if available */
2247                                                 if (argnames && argnames[i] && argnames[i][0])
2248                                                         ereport(ERROR,
2249                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2250                                                                          errmsg("procedure parameter \"%s\" is an output parameter but corresponding argument is not writable",
2251                                                                                         argnames[i])));
2252                                                 else
2253                                                         ereport(ERROR,
2254                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2255                                                                          errmsg("procedure parameter %d is an output parameter but corresponding argument is not writable",
2256                                                                                         i + 1)));
2257                                         }
2258                                 }
2259                                 i++;
2260                         }
2261
2262                         row->nfields = nfields;
2263
2264                         stmt->target = (PLpgSQL_variable *) row;
2265                 }
2266
2267                 paramLI = setup_param_list(estate, expr);
2268
2269                 before_lxid = MyProc->lxid;
2270
2271                 /*
2272                  * Set snapshot only for non-read-only procedures, similar to SPI
2273                  * behavior.
2274                  */
2275                 if (!estate->readonly_func)
2276                 {
2277                         PushActiveSnapshot(GetTransactionSnapshot());
2278                         pushed_active_snap = true;
2279                 }
2280
2281                 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
2282                                                                                          estate->readonly_func, 0);
2283         }
2284         PG_CATCH();
2285         {
2286                 /*
2287                  * If we aren't saving the plan, unset the pointer.  Note that it
2288                  * could have been unset already, in case of a recursive call.
2289                  */
2290                 if (expr->plan && !expr->plan->saved)
2291                         expr->plan = NULL;
2292                 PG_RE_THROW();
2293         }
2294         PG_END_TRY();
2295
2296         if (expr->plan && !expr->plan->saved)
2297                 expr->plan = NULL;
2298
2299         if (rc < 0)
2300                 elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
2301                          expr->query, SPI_result_code_string(rc));
2302
2303         after_lxid = MyProc->lxid;
2304
2305         if (before_lxid == after_lxid)
2306         {
2307                 /*
2308                  * If we are still in the same transaction after the call, pop the
2309                  * snapshot that we might have pushed.  (If it's a new transaction,
2310                  * then all the snapshots are gone already.)
2311                  */
2312                 if (pushed_active_snap)
2313                         PopActiveSnapshot();
2314         }
2315         else
2316         {
2317                 /*
2318                  * If we are in a new transaction after the call, we need to reset
2319                  * some internal state.
2320                  */
2321                 estate->simple_eval_estate = NULL;
2322                 plpgsql_create_econtext(estate);
2323         }
2324
2325         /*
2326          * Check result rowcount; if there's one row, assign procedure's output
2327          * values back to the appropriate variables.
2328          */
2329         if (SPI_processed == 1)
2330         {
2331                 SPITupleTable *tuptab = SPI_tuptable;
2332
2333                 if (!stmt->target)
2334                         elog(ERROR, "DO statement returned a row");
2335
2336                 exec_move_row(estate, stmt->target, tuptab->vals[0], tuptab->tupdesc);
2337         }
2338         else if (SPI_processed > 1)
2339                 elog(ERROR, "procedure call returned more than one row");
2340
2341         exec_eval_cleanup(estate);
2342         SPI_freetuptable(SPI_tuptable);
2343
2344         return PLPGSQL_RC_OK;
2345 }
2346
2347 /* ----------
2348  * exec_stmt_getdiag                                    Put internal PG information into
2349  *                                                                              specified variables.
2350  * ----------
2351  */
2352 static int
2353 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
2354 {
2355         ListCell   *lc;
2356
2357         /*
2358          * GET STACKED DIAGNOSTICS is only valid inside an exception handler.
2359          *
2360          * Note: we trust the grammar to have disallowed the relevant item kinds
2361          * if not is_stacked, otherwise we'd dump core below.
2362          */
2363         if (stmt->is_stacked && estate->cur_error == NULL)
2364                 ereport(ERROR,
2365                                 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
2366                                  errmsg("GET STACKED DIAGNOSTICS cannot be used outside an exception handler")));
2367
2368         foreach(lc, stmt->diag_items)
2369         {
2370                 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
2371                 PLpgSQL_datum *var = estate->datums[diag_item->target];
2372
2373                 switch (diag_item->kind)
2374                 {
2375                         case PLPGSQL_GETDIAG_ROW_COUNT:
2376                                 exec_assign_value(estate, var,
2377                                                                   UInt64GetDatum(estate->eval_processed),
2378                                                                   false, INT8OID, -1);
2379                                 break;
2380
2381                         case PLPGSQL_GETDIAG_ERROR_CONTEXT:
2382                                 exec_assign_c_string(estate, var,
2383                                                                          estate->cur_error->context);
2384                                 break;
2385
2386                         case PLPGSQL_GETDIAG_ERROR_DETAIL:
2387                                 exec_assign_c_string(estate, var,
2388                                                                          estate->cur_error->detail);
2389                                 break;
2390
2391                         case PLPGSQL_GETDIAG_ERROR_HINT:
2392                                 exec_assign_c_string(estate, var,
2393                                                                          estate->cur_error->hint);
2394                                 break;
2395
2396                         case PLPGSQL_GETDIAG_RETURNED_SQLSTATE:
2397                                 exec_assign_c_string(estate, var,
2398                                                                          unpack_sql_state(estate->cur_error->sqlerrcode));
2399                                 break;
2400
2401                         case PLPGSQL_GETDIAG_COLUMN_NAME:
2402                                 exec_assign_c_string(estate, var,
2403                                                                          estate->cur_error->column_name);
2404                                 break;
2405
2406                         case PLPGSQL_GETDIAG_CONSTRAINT_NAME:
2407                                 exec_assign_c_string(estate, var,
2408                                                                          estate->cur_error->constraint_name);
2409                                 break;
2410
2411                         case PLPGSQL_GETDIAG_DATATYPE_NAME:
2412                                 exec_assign_c_string(estate, var,
2413                                                                          estate->cur_error->datatype_name);
2414                                 break;
2415
2416                         case PLPGSQL_GETDIAG_MESSAGE_TEXT:
2417                                 exec_assign_c_string(estate, var,
2418                                                                          estate->cur_error->message);
2419                                 break;
2420
2421                         case PLPGSQL_GETDIAG_TABLE_NAME:
2422                                 exec_assign_c_string(estate, var,
2423                                                                          estate->cur_error->table_name);
2424                                 break;
2425
2426                         case PLPGSQL_GETDIAG_SCHEMA_NAME:
2427                                 exec_assign_c_string(estate, var,
2428                                                                          estate->cur_error->schema_name);
2429                                 break;
2430
2431                         case PLPGSQL_GETDIAG_CONTEXT:
2432                                 {
2433                                         char       *contextstackstr;
2434                                         MemoryContext oldcontext;
2435
2436                                         /* Use eval_mcontext for short-lived string */
2437                                         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
2438                                         contextstackstr = GetErrorContextStack();
2439                                         MemoryContextSwitchTo(oldcontext);
2440
2441                                         exec_assign_c_string(estate, var, contextstackstr);
2442                                 }
2443                                 break;
2444
2445                         default:
2446                                 elog(ERROR, "unrecognized diagnostic item kind: %d",
2447                                          diag_item->kind);
2448                 }
2449         }
2450
2451         exec_eval_cleanup(estate);
2452
2453         return PLPGSQL_RC_OK;
2454 }
2455
2456 /* ----------
2457  * exec_stmt_if                         Evaluate a bool expression and
2458  *                                      execute the true or false body
2459  *                                      conditionally.
2460  * ----------
2461  */
2462 static int
2463 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
2464 {
2465         bool            value;
2466         bool            isnull;
2467         ListCell   *lc;
2468
2469         value = exec_eval_boolean(estate, stmt->cond, &isnull);
2470         exec_eval_cleanup(estate);
2471         if (!isnull && value)
2472                 return exec_stmts(estate, stmt->then_body);
2473
2474         foreach(lc, stmt->elsif_list)
2475         {
2476                 PLpgSQL_if_elsif *elif = (PLpgSQL_if_elsif *) lfirst(lc);
2477
2478                 value = exec_eval_boolean(estate, elif->cond, &isnull);
2479                 exec_eval_cleanup(estate);
2480                 if (!isnull && value)
2481                         return exec_stmts(estate, elif->stmts);
2482         }
2483
2484         return exec_stmts(estate, stmt->else_body);
2485 }
2486
2487
2488 /*-----------
2489  * exec_stmt_case
2490  *-----------
2491  */
2492 static int
2493 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
2494 {
2495         PLpgSQL_var *t_var = NULL;
2496         bool            isnull;
2497         ListCell   *l;
2498
2499         if (stmt->t_expr != NULL)
2500         {
2501                 /* simple case */
2502                 Datum           t_val;
2503                 Oid                     t_typoid;
2504                 int32           t_typmod;
2505
2506                 t_val = exec_eval_expr(estate, stmt->t_expr,
2507                                                            &isnull, &t_typoid, &t_typmod);
2508
2509                 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
2510
2511                 /*
2512                  * When expected datatype is different from real, change it. Note that
2513                  * what we're modifying here is an execution copy of the datum, so
2514                  * this doesn't affect the originally stored function parse tree. (In
2515                  * theory, if the expression datatype keeps changing during execution,
2516                  * this could cause a function-lifespan memory leak.  Doesn't seem
2517                  * worth worrying about though.)
2518                  */
2519                 if (t_var->datatype->typoid != t_typoid ||
2520                         t_var->datatype->atttypmod != t_typmod)
2521                         t_var->datatype = plpgsql_build_datatype(t_typoid,
2522                                                                                                          t_typmod,
2523                                                                                                          estate->func->fn_input_collation,
2524                                                                                                          NULL);
2525
2526                 /* now we can assign to the variable */
2527                 exec_assign_value(estate,
2528                                                   (PLpgSQL_datum *) t_var,
2529                                                   t_val,
2530                                                   isnull,
2531                                                   t_typoid,
2532                                                   t_typmod);
2533
2534                 exec_eval_cleanup(estate);
2535         }
2536
2537         /* Now search for a successful WHEN clause */
2538         foreach(l, stmt->case_when_list)
2539         {
2540                 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
2541                 bool            value;
2542
2543                 value = exec_eval_boolean(estate, cwt->expr, &isnull);
2544                 exec_eval_cleanup(estate);
2545                 if (!isnull && value)
2546                 {
2547                         /* Found it */
2548
2549                         /* We can now discard any value we had for the temp variable */
2550                         if (t_var != NULL)
2551                                 assign_simple_var(estate, t_var, (Datum) 0, true, false);
2552
2553                         /* Evaluate the statement(s), and we're done */
2554                         return exec_stmts(estate, cwt->stmts);
2555                 }
2556         }
2557
2558         /* We can now discard any value we had for the temp variable */
2559         if (t_var != NULL)
2560                 assign_simple_var(estate, t_var, (Datum) 0, true, false);
2561
2562         /* SQL2003 mandates this error if there was no ELSE clause */
2563         if (!stmt->have_else)
2564                 ereport(ERROR,
2565                                 (errcode(ERRCODE_CASE_NOT_FOUND),
2566                                  errmsg("case not found"),
2567                                  errhint("CASE statement is missing ELSE part.")));
2568
2569         /* Evaluate the ELSE statements, and we're done */
2570         return exec_stmts(estate, stmt->else_stmts);
2571 }
2572
2573
2574 /* ----------
2575  * exec_stmt_loop                       Loop over statements until
2576  *                                      an exit occurs.
2577  * ----------
2578  */
2579 static int
2580 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
2581 {
2582         int                     rc = PLPGSQL_RC_OK;
2583
2584         for (;;)
2585         {
2586                 rc = exec_stmts(estate, stmt->body);
2587
2588                 LOOP_RC_PROCESSING(stmt->label, break);
2589         }
2590
2591         return rc;
2592 }
2593
2594
2595 /* ----------
2596  * exec_stmt_while                      Loop over statements as long
2597  *                                      as an expression evaluates to
2598  *                                      true or an exit occurs.
2599  * ----------
2600  */
2601 static int
2602 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
2603 {
2604         int                     rc = PLPGSQL_RC_OK;
2605
2606         for (;;)
2607         {
2608                 bool            value;
2609                 bool            isnull;
2610
2611                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2612                 exec_eval_cleanup(estate);
2613
2614                 if (isnull || !value)
2615                         break;
2616
2617                 rc = exec_stmts(estate, stmt->body);
2618
2619                 LOOP_RC_PROCESSING(stmt->label, break);
2620         }
2621
2622         return rc;
2623 }
2624
2625
2626 /* ----------
2627  * exec_stmt_fori                       Iterate an integer variable
2628  *                                      from a lower to an upper value
2629  *                                      incrementing or decrementing by the BY value
2630  * ----------
2631  */
2632 static int
2633 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
2634 {
2635         PLpgSQL_var *var;
2636         Datum           value;
2637         bool            isnull;
2638         Oid                     valtype;
2639         int32           valtypmod;
2640         int32           loop_value;
2641         int32           end_value;
2642         int32           step_value;
2643         bool            found = false;
2644         int                     rc = PLPGSQL_RC_OK;
2645
2646         var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
2647
2648         /*
2649          * Get the value of the lower bound
2650          */
2651         value = exec_eval_expr(estate, stmt->lower,
2652                                                    &isnull, &valtype, &valtypmod);
2653         value = exec_cast_value(estate, value, &isnull,
2654                                                         valtype, valtypmod,
2655                                                         var->datatype->typoid,
2656                                                         var->datatype->atttypmod);
2657         if (isnull)
2658                 ereport(ERROR,
2659                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2660                                  errmsg("lower bound of FOR loop cannot be null")));
2661         loop_value = DatumGetInt32(value);
2662         exec_eval_cleanup(estate);
2663
2664         /*
2665          * Get the value of the upper bound
2666          */
2667         value = exec_eval_expr(estate, stmt->upper,
2668                                                    &isnull, &valtype, &valtypmod);
2669         value = exec_cast_value(estate, value, &isnull,
2670                                                         valtype, valtypmod,
2671                                                         var->datatype->typoid,
2672                                                         var->datatype->atttypmod);
2673         if (isnull)
2674                 ereport(ERROR,
2675                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2676                                  errmsg("upper bound of FOR loop cannot be null")));
2677         end_value = DatumGetInt32(value);
2678         exec_eval_cleanup(estate);
2679
2680         /*
2681          * Get the step value
2682          */
2683         if (stmt->step)
2684         {
2685                 value = exec_eval_expr(estate, stmt->step,
2686                                                            &isnull, &valtype, &valtypmod);
2687                 value = exec_cast_value(estate, value, &isnull,
2688                                                                 valtype, valtypmod,
2689                                                                 var->datatype->typoid,
2690                                                                 var->datatype->atttypmod);
2691                 if (isnull)
2692                         ereport(ERROR,
2693                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2694                                          errmsg("BY value of FOR loop cannot be null")));
2695                 step_value = DatumGetInt32(value);
2696                 exec_eval_cleanup(estate);
2697                 if (step_value <= 0)
2698                         ereport(ERROR,
2699                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2700                                          errmsg("BY value of FOR loop must be greater than zero")));
2701         }
2702         else
2703                 step_value = 1;
2704
2705         /*
2706          * Now do the loop
2707          */
2708         for (;;)
2709         {
2710                 /*
2711                  * Check against upper bound
2712                  */
2713                 if (stmt->reverse)
2714                 {
2715                         if (loop_value < end_value)
2716                                 break;
2717                 }
2718                 else
2719                 {
2720                         if (loop_value > end_value)
2721                                 break;
2722                 }
2723
2724                 found = true;                   /* looped at least once */
2725
2726                 /*
2727                  * Assign current value to loop var
2728                  */
2729                 assign_simple_var(estate, var, Int32GetDatum(loop_value), false, false);
2730
2731                 /*
2732                  * Execute the statements
2733                  */
2734                 rc = exec_stmts(estate, stmt->body);
2735
2736                 LOOP_RC_PROCESSING(stmt->label, break);
2737
2738                 /*
2739                  * Increase/decrease loop value, unless it would overflow, in which
2740                  * case exit the loop.
2741                  */
2742                 if (stmt->reverse)
2743                 {
2744                         if (loop_value < (PG_INT32_MIN + step_value))
2745                                 break;
2746                         loop_value -= step_value;
2747                 }
2748                 else
2749                 {
2750                         if (loop_value > (PG_INT32_MAX - step_value))
2751                                 break;
2752                         loop_value += step_value;
2753                 }
2754         }
2755
2756         /*
2757          * Set the FOUND variable to indicate the result of executing the loop
2758          * (namely, whether we looped one or more times). This must be set here so
2759          * that it does not interfere with the value of the FOUND variable inside
2760          * the loop processing itself.
2761          */
2762         exec_set_found(estate, found);
2763
2764         return rc;
2765 }
2766
2767
2768 /* ----------
2769  * exec_stmt_fors                       Execute a query, assign each
2770  *                                      tuple to a record or row and
2771  *                                      execute a group of statements
2772  *                                      for it.
2773  * ----------
2774  */
2775 static int
2776 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
2777 {
2778         Portal          portal;
2779         int                     rc;
2780
2781         /*
2782          * Open the implicit cursor for the statement using exec_run_select
2783          */
2784         exec_run_select(estate, stmt->query, 0, &portal);
2785
2786         /*
2787          * Execute the loop
2788          */
2789         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
2790
2791         /*
2792          * Close the implicit cursor
2793          */
2794         SPI_cursor_close(portal);
2795
2796         return rc;
2797 }
2798
2799
2800 /* ----------
2801  * exec_stmt_forc                       Execute a loop for each row from a cursor.
2802  * ----------
2803  */
2804 static int
2805 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
2806 {
2807         PLpgSQL_var *curvar;
2808         MemoryContext stmt_mcontext = NULL;
2809         char       *curname = NULL;
2810         PLpgSQL_expr *query;
2811         ParamListInfo paramLI;
2812         Portal          portal;
2813         int                     rc;
2814
2815         /* ----------
2816          * Get the cursor variable and if it has an assigned name, check
2817          * that it's not in use currently.
2818          * ----------
2819          */
2820         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2821         if (!curvar->isnull)
2822         {
2823                 MemoryContext oldcontext;
2824
2825                 /* We only need stmt_mcontext to hold the cursor name string */
2826                 stmt_mcontext = get_stmt_mcontext(estate);
2827                 oldcontext = MemoryContextSwitchTo(stmt_mcontext);
2828                 curname = TextDatumGetCString(curvar->value);
2829                 MemoryContextSwitchTo(oldcontext);
2830
2831                 if (SPI_cursor_find(curname) != NULL)
2832                         ereport(ERROR,
2833                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
2834                                          errmsg("cursor \"%s\" already in use", curname)));
2835         }
2836
2837         /* ----------
2838          * Open the cursor just like an OPEN command
2839          *
2840          * Note: parser should already have checked that statement supplies
2841          * args iff cursor needs them, but we check again to be safe.
2842          * ----------
2843          */
2844         if (stmt->argquery != NULL)
2845         {
2846                 /* ----------
2847                  * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
2848                  * statement to evaluate the args and put 'em into the
2849                  * internal row.
2850                  * ----------
2851                  */
2852                 PLpgSQL_stmt_execsql set_args;
2853
2854                 if (curvar->cursor_explicit_argrow < 0)
2855                         ereport(ERROR,
2856                                         (errcode(ERRCODE_SYNTAX_ERROR),
2857                                          errmsg("arguments given for cursor without arguments")));
2858
2859                 memset(&set_args, 0, sizeof(set_args));
2860                 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
2861                 set_args.lineno = stmt->lineno;
2862                 set_args.sqlstmt = stmt->argquery;
2863                 set_args.into = true;
2864                 /* XXX historically this has not been STRICT */
2865                 set_args.target = (PLpgSQL_variable *)
2866                         (estate->datums[curvar->cursor_explicit_argrow]);
2867
2868                 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
2869                         elog(ERROR, "open cursor failed during argument processing");
2870         }
2871         else
2872         {
2873                 if (curvar->cursor_explicit_argrow >= 0)
2874                         ereport(ERROR,
2875                                         (errcode(ERRCODE_SYNTAX_ERROR),
2876                                          errmsg("arguments required for cursor")));
2877         }
2878
2879         query = curvar->cursor_explicit_expr;
2880         Assert(query);
2881
2882         if (query->plan == NULL)
2883                 exec_prepare_plan(estate, query, curvar->cursor_options, true);
2884
2885         /*
2886          * Set up ParamListInfo for this query
2887          */
2888         paramLI = setup_param_list(estate, query);
2889
2890         /*
2891          * Open the cursor (the paramlist will get copied into the portal)
2892          */
2893         portal = SPI_cursor_open_with_paramlist(curname, query->plan,
2894                                                                                         paramLI,
2895                                                                                         estate->readonly_func);
2896         if (portal == NULL)
2897                 elog(ERROR, "could not open cursor: %s",
2898                          SPI_result_code_string(SPI_result));
2899
2900         /*
2901          * If cursor variable was NULL, store the generated portal name in it
2902          */
2903         if (curname == NULL)
2904                 assign_text_var(estate, curvar, portal->name);
2905
2906         /*
2907          * Clean up before entering exec_for_query
2908          */
2909         exec_eval_cleanup(estate);
2910         if (stmt_mcontext)
2911                 MemoryContextReset(stmt_mcontext);
2912
2913         /*
2914          * Execute the loop.  We can't prefetch because the cursor is accessible
2915          * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2916          */
2917         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2918
2919         /* ----------
2920          * Close portal, and restore cursor variable if it was initially NULL.
2921          * ----------
2922          */
2923         SPI_cursor_close(portal);
2924
2925         if (curname == NULL)
2926                 assign_simple_var(estate, curvar, (Datum) 0, true, false);
2927
2928         return rc;
2929 }
2930
2931
2932 /* ----------
2933  * exec_stmt_foreach_a                  Loop over elements or slices of an array
2934  *
2935  * When looping over elements, the loop variable is the same type that the
2936  * array stores (eg: integer), when looping through slices, the loop variable
2937  * is an array of size and dimensions to match the size of the slice.
2938  * ----------
2939  */
2940 static int
2941 exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
2942 {
2943         ArrayType  *arr;
2944         Oid                     arrtype;
2945         int32           arrtypmod;
2946         PLpgSQL_datum *loop_var;
2947         Oid                     loop_var_elem_type;
2948         bool            found = false;
2949         int                     rc = PLPGSQL_RC_OK;
2950         MemoryContext stmt_mcontext;
2951         MemoryContext oldcontext;
2952         ArrayIterator array_iterator;
2953         Oid                     iterator_result_type;
2954         int32           iterator_result_typmod;
2955         Datum           value;
2956         bool            isnull;
2957
2958         /* get the value of the array expression */
2959         value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype, &arrtypmod);
2960         if (isnull)
2961                 ereport(ERROR,
2962                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2963                                  errmsg("FOREACH expression must not be null")));
2964
2965         /*
2966          * Do as much as possible of the code below in stmt_mcontext, to avoid any
2967          * leaks from called subroutines.  We need a private stmt_mcontext since
2968          * we'll be calling arbitrary statement code.
2969          */
2970         stmt_mcontext = get_stmt_mcontext(estate);
2971         push_stmt_mcontext(estate);
2972         oldcontext = MemoryContextSwitchTo(stmt_mcontext);
2973
2974         /* check the type of the expression - must be an array */
2975         if (!OidIsValid(get_element_type(arrtype)))
2976                 ereport(ERROR,
2977                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2978                                  errmsg("FOREACH expression must yield an array, not type %s",
2979                                                 format_type_be(arrtype))));
2980
2981         /*
2982          * We must copy the array into stmt_mcontext, else it will disappear in
2983          * exec_eval_cleanup.  This is annoying, but cleanup will certainly happen
2984          * while running the loop body, so we have little choice.
2985          */
2986         arr = DatumGetArrayTypePCopy(value);
2987
2988         /* Clean up any leftover temporary memory */
2989         exec_eval_cleanup(estate);
2990
2991         /* Slice dimension must be less than or equal to array dimension */
2992         if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
2993                 ereport(ERROR,
2994                                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2995                                  errmsg("slice dimension (%d) is out of the valid range 0..%d",
2996                                                 stmt->slice, ARR_NDIM(arr))));
2997
2998         /* Set up the loop variable and see if it is of an array type */
2999         loop_var = estate->datums[stmt->varno];
3000         if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
3001                 loop_var->dtype == PLPGSQL_DTYPE_ROW)
3002         {
3003                 /*
3004                  * Record/row variable is certainly not of array type, and might not
3005                  * be initialized at all yet, so don't try to get its type
3006                  */
3007                 loop_var_elem_type = InvalidOid;
3008         }
3009         else
3010                 loop_var_elem_type = get_element_type(plpgsql_exec_get_datum_type(estate,
3011                                                                                                                                                   loop_var));
3012
3013         /*
3014          * Sanity-check the loop variable type.  We don't try very hard here, and
3015          * should not be too picky since it's possible that exec_assign_value can
3016          * coerce values of different types.  But it seems worthwhile to complain
3017          * if the array-ness of the loop variable is not right.
3018          */
3019         if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
3020                 ereport(ERROR,
3021                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3022                                  errmsg("FOREACH ... SLICE loop variable must be of an array type")));
3023         if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
3024                 ereport(ERROR,
3025                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3026                                  errmsg("FOREACH loop variable must not be of an array type")));
3027
3028         /* Create an iterator to step through the array */
3029         array_iterator = array_create_iterator(arr, stmt->slice, NULL);
3030
3031         /* Identify iterator result type */
3032         if (stmt->slice > 0)
3033         {
3034                 /* When slicing, nominal type of result is same as array type */
3035                 iterator_result_type = arrtype;
3036                 iterator_result_typmod = arrtypmod;
3037         }
3038         else
3039         {
3040                 /* Without slicing, results are individual array elements */
3041                 iterator_result_type = ARR_ELEMTYPE(arr);
3042                 iterator_result_typmod = arrtypmod;
3043         }
3044
3045         /* Iterate over the array elements or slices */
3046         while (array_iterate(array_iterator, &value, &isnull))
3047         {
3048                 found = true;                   /* looped at least once */
3049
3050                 /* exec_assign_value and exec_stmts must run in the main context */
3051                 MemoryContextSwitchTo(oldcontext);
3052
3053                 /* Assign current element/slice to the loop variable */
3054                 exec_assign_value(estate, loop_var, value, isnull,
3055                                                   iterator_result_type, iterator_result_typmod);
3056
3057                 /* In slice case, value is temporary; must free it to avoid leakage */
3058                 if (stmt->slice > 0)
3059                         pfree(DatumGetPointer(value));
3060
3061                 /*
3062                  * Execute the statements
3063                  */
3064                 rc = exec_stmts(estate, stmt->body);
3065
3066                 LOOP_RC_PROCESSING(stmt->label, break);
3067
3068                 MemoryContextSwitchTo(stmt_mcontext);
3069         }
3070
3071         /* Restore memory context state */
3072         MemoryContextSwitchTo(oldcontext);
3073         pop_stmt_mcontext(estate);
3074
3075         /* Release temporary memory, including the array value */
3076         MemoryContextReset(stmt_mcontext);
3077
3078         /*
3079          * Set the FOUND variable to indicate the result of executing the loop
3080          * (namely, whether we looped one or more times). This must be set here so
3081          * that it does not interfere with the value of the FOUND variable inside
3082          * the loop processing itself.
3083          */
3084         exec_set_found(estate, found);
3085
3086         return rc;
3087 }
3088
3089
3090 /* ----------
3091  * exec_stmt_exit                       Implements EXIT and CONTINUE
3092  *
3093  * This begins the process of exiting / restarting a loop.
3094  * ----------
3095  */
3096 static int
3097 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
3098 {
3099         /*
3100          * If the exit / continue has a condition, evaluate it
3101          */
3102         if (stmt->cond != NULL)
3103         {
3104                 bool            value;
3105                 bool            isnull;
3106
3107                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
3108                 exec_eval_cleanup(estate);
3109                 if (isnull || value == false)
3110                         return PLPGSQL_RC_OK;
3111         }
3112
3113         estate->exitlabel = stmt->label;
3114         if (stmt->is_exit)
3115                 return PLPGSQL_RC_EXIT;
3116         else
3117                 return PLPGSQL_RC_CONTINUE;
3118 }
3119
3120
3121 /* ----------
3122  * exec_stmt_return                     Evaluate an expression and start
3123  *                                      returning from the function.
3124  *
3125  * Note: The result may be in the eval_mcontext.  Therefore, we must not
3126  * do exec_eval_cleanup while unwinding the control stack.
3127  * ----------
3128  */
3129 static int
3130 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
3131 {
3132         /*
3133          * If processing a set-returning PL/pgSQL function, the final RETURN
3134          * indicates that the function is finished producing tuples.  The rest of
3135          * the work will be done at the top level.
3136          */
3137         if (estate->retisset)
3138                 return PLPGSQL_RC_RETURN;
3139
3140         /* initialize for null result */
3141         estate->retval = (Datum) 0;
3142         estate->retisnull = true;
3143         estate->rettype = InvalidOid;
3144
3145         /*
3146          * Special case path when the RETURN expression is a simple variable
3147          * reference; in particular, this path is always taken in functions with
3148          * one or more OUT parameters.
3149          *
3150          * This special case is especially efficient for returning variables that
3151          * have R/W expanded values: we can put the R/W pointer directly into
3152          * estate->retval, leading to transferring the value to the caller's
3153          * context cheaply.  If we went through exec_eval_expr we'd end up with a
3154          * R/O pointer.  It's okay to skip MakeExpandedObjectReadOnly here since
3155          * we know we won't need the variable's value within the function anymore.
3156          */
3157         if (stmt->retvarno >= 0)
3158         {
3159                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
3160
3161                 switch (retvar->dtype)
3162                 {
3163                         case PLPGSQL_DTYPE_PROMISE:
3164                                 /* fulfill promise if needed, then handle like regular var */
3165                                 plpgsql_fulfill_promise(estate, (PLpgSQL_var *) retvar);
3166
3167                                 /* FALL THRU */
3168
3169                         case PLPGSQL_DTYPE_VAR:
3170                                 {
3171                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
3172
3173                                         estate->retval = var->value;
3174                                         estate->retisnull = var->isnull;
3175                                         estate->rettype = var->datatype->typoid;
3176
3177                                         /*
3178                                          * A PLpgSQL_var could not be of composite type, so
3179                                          * conversion must fail if retistuple.  We throw a custom
3180                                          * error mainly for consistency with historical behavior.
3181                                          * For the same reason, we don't throw error if the result
3182                                          * is NULL.  (Note that plpgsql_exec_trigger assumes that
3183                                          * any non-null result has been verified to be composite.)
3184                                          */
3185                                         if (estate->retistuple && !estate->retisnull)
3186                                                 ereport(ERROR,
3187                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3188                                                                  errmsg("cannot return non-composite value from function returning composite type")));
3189                                 }
3190                                 break;
3191
3192                         case PLPGSQL_DTYPE_REC:
3193                                 {
3194                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
3195
3196                                         /* If record is empty, we return NULL not a row of nulls */
3197                                         if (rec->erh && !ExpandedRecordIsEmpty(rec->erh))
3198                                         {
3199                                                 estate->retval = ExpandedRecordGetDatum(rec->erh);
3200                                                 estate->retisnull = false;
3201                                                 estate->rettype = rec->rectypeid;
3202                                         }
3203                                 }
3204                                 break;
3205
3206                         case PLPGSQL_DTYPE_ROW:
3207                                 {
3208                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
3209                                         int32           rettypmod;
3210
3211                                         /* We get here if there are multiple OUT parameters */
3212                                         exec_eval_datum(estate,
3213                                                                         (PLpgSQL_datum *) row,
3214                                                                         &estate->rettype,
3215                                                                         &rettypmod,
3216                                                                         &estate->retval,
3217                                                                         &estate->retisnull);
3218                                 }
3219                                 break;
3220
3221                         default:
3222                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
3223                 }
3224
3225                 return PLPGSQL_RC_RETURN;
3226         }
3227
3228         if (stmt->expr != NULL)
3229         {
3230                 int32           rettypmod;
3231
3232                 estate->retval = exec_eval_expr(estate, stmt->expr,
3233                                                                                 &(estate->retisnull),
3234                                                                                 &(estate->rettype),
3235                                                                                 &rettypmod);
3236
3237                 /*
3238                  * As in the DTYPE_VAR case above, throw a custom error if a non-null,
3239                  * non-composite value is returned in a function returning tuple.
3240                  */
3241                 if (estate->retistuple && !estate->retisnull &&
3242                         !type_is_rowtype(estate->rettype))
3243                         ereport(ERROR,
3244                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3245                                          errmsg("cannot return non-composite value from function returning composite type")));
3246
3247                 return PLPGSQL_RC_RETURN;
3248         }
3249
3250         /*
3251          * Special hack for function returning VOID: instead of NULL, return a
3252          * non-null VOID value.  This is of dubious importance but is kept for
3253          * backwards compatibility.  We don't do it for procedures, though.
3254          */
3255         if (estate->fn_rettype == VOIDOID &&
3256                 estate->func->fn_prokind != PROKIND_PROCEDURE)
3257         {
3258                 estate->retval = (Datum) 0;
3259                 estate->retisnull = false;
3260                 estate->rettype = VOIDOID;
3261         }
3262
3263         return PLPGSQL_RC_RETURN;
3264 }
3265
3266 /* ----------
3267  * exec_stmt_return_next                Evaluate an expression and add it to the
3268  *                                                              list of tuples returned by the current
3269  *                                                              SRF.
3270  * ----------
3271  */
3272 static int
3273 exec_stmt_return_next(PLpgSQL_execstate *estate,
3274                                           PLpgSQL_stmt_return_next *stmt)
3275 {
3276         TupleDesc       tupdesc;
3277         int                     natts;
3278         HeapTuple       tuple;
3279         MemoryContext oldcontext;
3280
3281         if (!estate->retisset)
3282                 ereport(ERROR,
3283                                 (errcode(ERRCODE_SYNTAX_ERROR),
3284                                  errmsg("cannot use RETURN NEXT in a non-SETOF function")));
3285
3286         if (estate->tuple_store == NULL)
3287                 exec_init_tuple_store(estate);
3288
3289         /* tuple_store_desc will be filled by exec_init_tuple_store */
3290         tupdesc = estate->tuple_store_desc;
3291         natts = tupdesc->natts;
3292
3293         /*
3294          * Special case path when the RETURN NEXT expression is a simple variable
3295          * reference; in particular, this path is always taken in functions with
3296          * one or more OUT parameters.
3297          *
3298          * Unlike exec_stmt_return, there's no special win here for R/W expanded
3299          * values, since they'll have to get flattened to go into the tuplestore.
3300          * Indeed, we'd better make them R/O to avoid any risk of the casting step
3301          * changing them in-place.
3302          */
3303         if (stmt->retvarno >= 0)
3304         {
3305                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
3306
3307                 switch (retvar->dtype)
3308                 {
3309                         case PLPGSQL_DTYPE_PROMISE:
3310                                 /* fulfill promise if needed, then handle like regular var */
3311                                 plpgsql_fulfill_promise(estate, (PLpgSQL_var *) retvar);
3312
3313                                 /* FALL THRU */
3314
3315                         case PLPGSQL_DTYPE_VAR:
3316                                 {
3317                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
3318                                         Datum           retval = var->value;
3319                                         bool            isNull = var->isnull;
3320                                         Form_pg_attribute attr = TupleDescAttr(tupdesc, 0);
3321
3322                                         if (natts != 1)
3323                                                 ereport(ERROR,
3324                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3325                                                                  errmsg("wrong result type supplied in RETURN NEXT")));
3326
3327                                         /* let's be very paranoid about the cast step */
3328                                         retval = MakeExpandedObjectReadOnly(retval,
3329                                                                                                                 isNull,
3330                                                                                                                 var->datatype->typlen);
3331
3332                                         /* coerce type if needed */
3333                                         retval = exec_cast_value(estate,
3334                                                                                          retval,
3335                                                                                          &isNull,
3336                                                                                          var->datatype->typoid,
3337                                                                                          var->datatype->atttypmod,
3338                                                                                          attr->atttypid,
3339                                                                                          attr->atttypmod);
3340
3341                                         tuplestore_putvalues(estate->tuple_store, tupdesc,
3342                                                                                  &retval, &isNull);
3343                                 }
3344                                 break;
3345
3346                         case PLPGSQL_DTYPE_REC:
3347                                 {
3348                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
3349                                         TupleDesc       rec_tupdesc;
3350                                         TupleConversionMap *tupmap;
3351
3352                                         /* If rec is null, try to convert it to a row of nulls */
3353                                         if (rec->erh == NULL)
3354                                                 instantiate_empty_record_variable(estate, rec);
3355                                         if (ExpandedRecordIsEmpty(rec->erh))
3356                                                 deconstruct_expanded_record(rec->erh);
3357
3358                                         /* Use eval_mcontext for tuple conversion work */
3359                                         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3360                                         rec_tupdesc = expanded_record_get_tupdesc(rec->erh);
3361                                         tupmap = convert_tuples_by_position(rec_tupdesc,
3362                                                                                                                 tupdesc,
3363                                                                                                                 gettext_noop("wrong record type supplied in RETURN NEXT"));
3364                                         tuple = expanded_record_get_tuple(rec->erh);
3365                                         if (tupmap)
3366                                                 tuple = execute_attr_map_tuple(tuple, tupmap);
3367                                         tuplestore_puttuple(estate->tuple_store, tuple);
3368                                         MemoryContextSwitchTo(oldcontext);
3369                                 }
3370                                 break;
3371
3372                         case PLPGSQL_DTYPE_ROW:
3373                                 {
3374                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
3375
3376                                         /* We get here if there are multiple OUT parameters */
3377
3378                                         /* Use eval_mcontext for tuple conversion work */
3379                                         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3380                                         tuple = make_tuple_from_row(estate, row, tupdesc);
3381                                         if (tuple == NULL)      /* should not happen */
3382                                                 ereport(ERROR,
3383                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3384                                                                  errmsg("wrong record type supplied in RETURN NEXT")));
3385                                         tuplestore_puttuple(estate->tuple_store, tuple);
3386                                         MemoryContextSwitchTo(oldcontext);
3387                                 }
3388                                 break;
3389
3390                         default:
3391                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
3392                                 break;
3393                 }
3394         }
3395         else if (stmt->expr)
3396         {
3397                 Datum           retval;
3398                 bool            isNull;
3399                 Oid                     rettype;
3400                 int32           rettypmod;
3401
3402                 retval = exec_eval_expr(estate,
3403                                                                 stmt->expr,
3404                                                                 &isNull,
3405                                                                 &rettype,
3406                                                                 &rettypmod);
3407
3408                 if (estate->retistuple)
3409                 {
3410                         /* Expression should be of RECORD or composite type */
3411                         if (!isNull)
3412                         {
3413                                 HeapTupleData tmptup;
3414                                 TupleDesc       retvaldesc;
3415                                 TupleConversionMap *tupmap;
3416
3417                                 if (!type_is_rowtype(rettype))
3418                                         ereport(ERROR,
3419                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3420                                                          errmsg("cannot return non-composite value from function returning composite type")));
3421
3422                                 /* Use eval_mcontext for tuple conversion work */
3423                                 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3424                                 retvaldesc = deconstruct_composite_datum(retval, &tmptup);
3425                                 tuple = &tmptup;
3426                                 tupmap = convert_tuples_by_position(retvaldesc, tupdesc,
3427                                                                                                         gettext_noop("returned record type does not match expected record type"));
3428                                 if (tupmap)
3429                                         tuple = execute_attr_map_tuple(tuple, tupmap);
3430                                 tuplestore_puttuple(estate->tuple_store, tuple);
3431                                 ReleaseTupleDesc(retvaldesc);
3432                                 MemoryContextSwitchTo(oldcontext);
3433                         }
3434                         else
3435                         {
3436                                 /* Composite NULL --- store a row of nulls */
3437                                 Datum      *nulldatums;
3438                                 bool       *nullflags;
3439
3440                                 nulldatums = (Datum *)
3441                                         eval_mcontext_alloc0(estate, natts * sizeof(Datum));
3442                                 nullflags = (bool *)
3443                                         eval_mcontext_alloc(estate, natts * sizeof(bool));
3444                                 memset(nullflags, true, natts * sizeof(bool));
3445                                 tuplestore_putvalues(estate->tuple_store, tupdesc,
3446                                                                          nulldatums, nullflags);
3447                         }
3448                 }
3449                 else
3450                 {
3451                         Form_pg_attribute attr = TupleDescAttr(tupdesc, 0);
3452
3453                         /* Simple scalar result */
3454                         if (natts != 1)
3455                                 ereport(ERROR,
3456                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3457                                                  errmsg("wrong result type supplied in RETURN NEXT")));
3458
3459                         /* coerce type if needed */
3460                         retval = exec_cast_value(estate,
3461                                                                          retval,
3462                                                                          &isNull,
3463                                                                          rettype,
3464                                                                          rettypmod,
3465                                                                          attr->atttypid,
3466                                                                          attr->atttypmod);
3467
3468                         tuplestore_putvalues(estate->tuple_store, tupdesc,
3469                                                                  &retval, &isNull);
3470                 }
3471         }
3472         else
3473         {
3474                 ereport(ERROR,
3475                                 (errcode(ERRCODE_SYNTAX_ERROR),
3476                                  errmsg("RETURN NEXT must have a parameter")));
3477         }
3478
3479         exec_eval_cleanup(estate);
3480
3481         return PLPGSQL_RC_OK;
3482 }
3483
3484 /* ----------
3485  * exec_stmt_return_query               Evaluate a query and add it to the
3486  *                                                              list of tuples returned by the current
3487  *                                                              SRF.
3488  * ----------
3489  */
3490 static int
3491 exec_stmt_return_query(PLpgSQL_execstate *estate,
3492                                            PLpgSQL_stmt_return_query *stmt)
3493 {
3494         Portal          portal;
3495         uint64          processed = 0;
3496         TupleConversionMap *tupmap;
3497         MemoryContext oldcontext;
3498
3499         if (!estate->retisset)
3500                 ereport(ERROR,
3501                                 (errcode(ERRCODE_SYNTAX_ERROR),
3502                                  errmsg("cannot use RETURN QUERY in a non-SETOF function")));
3503
3504         if (estate->tuple_store == NULL)
3505                 exec_init_tuple_store(estate);
3506
3507         if (stmt->query != NULL)
3508         {
3509                 /* static query */
3510                 exec_run_select(estate, stmt->query, 0, &portal);
3511         }
3512         else
3513         {
3514                 /* RETURN QUERY EXECUTE */
3515                 Assert(stmt->dynquery != NULL);
3516                 portal = exec_dynquery_with_params(estate, stmt->dynquery,
3517                                                                                    stmt->params, NULL,
3518                                                                                    0);
3519         }
3520
3521         /* Use eval_mcontext for tuple conversion work */
3522         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3523
3524         tupmap = convert_tuples_by_position(portal->tupDesc,
3525                                                                                 estate->tuple_store_desc,
3526                                                                                 gettext_noop("structure of query does not match function result type"));
3527
3528         while (true)
3529         {
3530                 uint64          i;
3531
3532                 SPI_cursor_fetch(portal, true, 50);
3533
3534                 /* SPI will have changed CurrentMemoryContext */
3535                 MemoryContextSwitchTo(get_eval_mcontext(estate));
3536
3537                 if (SPI_processed == 0)
3538                         break;
3539
3540                 for (i = 0; i < SPI_processed; i++)
3541                 {
3542                         HeapTuple       tuple = SPI_tuptable->vals[i];
3543
3544                         if (tupmap)
3545                                 tuple = execute_attr_map_tuple(tuple, tupmap);
3546                         tuplestore_puttuple(estate->tuple_store, tuple);
3547                         if (tupmap)
3548                                 heap_freetuple(tuple);
3549                         processed++;
3550                 }
3551
3552                 SPI_freetuptable(SPI_tuptable);
3553         }
3554
3555         SPI_freetuptable(SPI_tuptable);
3556         SPI_cursor_close(portal);
3557
3558         MemoryContextSwitchTo(oldcontext);
3559         exec_eval_cleanup(estate);
3560
3561         estate->eval_processed = processed;
3562         exec_set_found(estate, processed != 0);
3563
3564         return PLPGSQL_RC_OK;
3565 }
3566
3567 static void
3568 exec_init_tuple_store(PLpgSQL_execstate *estate)
3569 {
3570         ReturnSetInfo *rsi = estate->rsi;
3571         MemoryContext oldcxt;
3572         ResourceOwner oldowner;
3573
3574         /*
3575          * Check caller can handle a set result in the way we want
3576          */
3577         if (!rsi || !IsA(rsi, ReturnSetInfo) ||
3578                 (rsi->allowedModes & SFRM_Materialize) == 0 ||
3579                 rsi->expectedDesc == NULL)
3580                 ereport(ERROR,
3581                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3582                                  errmsg("set-valued function called in context that cannot accept a set")));
3583
3584         /*
3585          * Switch to the right memory context and resource owner for storing the
3586          * tuplestore for return set. If we're within a subtransaction opened for
3587          * an exception-block, for example, we must still create the tuplestore in
3588          * the resource owner that was active when this function was entered, and
3589          * not in the subtransaction resource owner.
3590          */
3591         oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
3592         oldowner = CurrentResourceOwner;
3593         CurrentResourceOwner = estate->tuple_store_owner;
3594
3595         estate->tuple_store =
3596                 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
3597                                                           false, work_mem);
3598
3599         CurrentResourceOwner = oldowner;
3600         MemoryContextSwitchTo(oldcxt);
3601
3602         estate->tuple_store_desc = rsi->expectedDesc;
3603 }
3604
3605 #define SET_RAISE_OPTION_TEXT(opt, name) \
3606 do { \
3607         if (opt) \
3608                 ereport(ERROR, \
3609                                 (errcode(ERRCODE_SYNTAX_ERROR), \
3610                                  errmsg("RAISE option already specified: %s", \
3611                                                 name))); \
3612         opt = MemoryContextStrdup(stmt_mcontext, extval); \
3613 } while (0)
3614
3615 /* ----------
3616  * exec_stmt_raise                      Build a message and throw it with elog()
3617  * ----------
3618  */
3619 static int
3620 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
3621 {
3622         int                     err_code = 0;
3623         char       *condname = NULL;
3624         char       *err_message = NULL;
3625         char       *err_detail = NULL;
3626         char       *err_hint = NULL;
3627         char       *err_column = NULL;
3628         char       *err_constraint = NULL;
3629         char       *err_datatype = NULL;
3630         char       *err_table = NULL;
3631         char       *err_schema = NULL;
3632         MemoryContext stmt_mcontext;
3633         ListCell   *lc;
3634
3635         /* RAISE with no parameters: re-throw current exception */
3636         if (stmt->condname == NULL && stmt->message == NULL &&
3637                 stmt->options == NIL)
3638         {
3639                 if (estate->cur_error != NULL)
3640                         ReThrowError(estate->cur_error);
3641                 /* oops, we're not inside a handler */
3642                 ereport(ERROR,
3643                                 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
3644                                  errmsg("RAISE without parameters cannot be used outside an exception handler")));
3645         }
3646
3647         /* We'll need to accumulate the various strings in stmt_mcontext */
3648         stmt_mcontext = get_stmt_mcontext(estate);
3649
3650         if (stmt->condname)
3651         {
3652                 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
3653                 condname = MemoryContextStrdup(stmt_mcontext, stmt->condname);
3654         }
3655
3656         if (stmt->message)
3657         {
3658                 StringInfoData ds;
3659                 ListCell   *current_param;
3660                 char       *cp;
3661                 MemoryContext oldcontext;
3662
3663                 /* build string in stmt_mcontext */
3664                 oldcontext = MemoryContextSwitchTo(stmt_mcontext);
3665                 initStringInfo(&ds);
3666                 MemoryContextSwitchTo(oldcontext);
3667
3668                 current_param = list_head(stmt->params);
3669
3670                 for (cp = stmt->message; *cp; cp++)
3671                 {
3672                         /*
3673                          * Occurrences of a single % are replaced by the next parameter's
3674                          * external representation. Double %'s are converted to one %.
3675                          */
3676                         if (cp[0] == '%')
3677                         {
3678                                 Oid                     paramtypeid;
3679                                 int32           paramtypmod;
3680                                 Datum           paramvalue;
3681                                 bool            paramisnull;
3682                                 char       *extval;
3683
3684                                 if (cp[1] == '%')
3685                                 {
3686                                         appendStringInfoChar(&ds, '%');
3687                                         cp++;
3688                                         continue;
3689                                 }
3690
3691                                 /* should have been checked at compile time */
3692                                 if (current_param == NULL)
3693                                         elog(ERROR, "unexpected RAISE parameter list length");
3694
3695                                 paramvalue = exec_eval_expr(estate,
3696                                                                                         (PLpgSQL_expr *) lfirst(current_param),
3697                                                                                         &paramisnull,
3698                                                                                         &paramtypeid,
3699                                                                                         &paramtypmod);
3700
3701                                 if (paramisnull)
3702                                         extval = "<NULL>";
3703                                 else
3704                                         extval = convert_value_to_string(estate,
3705                                                                                                          paramvalue,
3706                                                                                                          paramtypeid);
3707                                 appendStringInfoString(&ds, extval);
3708                                 current_param = lnext(stmt->params, current_param);
3709                                 exec_eval_cleanup(estate);
3710                         }
3711                         else
3712                                 appendStringInfoChar(&ds, cp[0]);
3713                 }
3714
3715                 /* should have been checked at compile time */
3716                 if (current_param != NULL)
3717                         elog(ERROR, "unexpected RAISE parameter list length");
3718
3719                 err_message = ds.data;
3720         }
3721
3722         foreach(lc, stmt->options)
3723         {
3724                 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
3725                 Datum           optionvalue;
3726                 bool            optionisnull;
3727                 Oid                     optiontypeid;
3728                 int32           optiontypmod;
3729                 char       *extval;
3730
3731                 optionvalue = exec_eval_expr(estate, opt->expr,
3732                                                                          &optionisnull,
3733                                                                          &optiontypeid,
3734                                                                          &optiontypmod);
3735                 if (optionisnull)
3736                         ereport(ERROR,
3737                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3738                                          errmsg("RAISE statement option cannot be null")));
3739
3740                 extval = convert_value_to_string(estate, optionvalue, optiontypeid);
3741
3742                 switch (opt->opt_type)
3743                 {
3744                         case PLPGSQL_RAISEOPTION_ERRCODE:
3745                                 if (err_code)
3746                                         ereport(ERROR,
3747                                                         (errcode(ERRCODE_SYNTAX_ERROR),
3748                                                          errmsg("RAISE option already specified: %s",
3749                                                                         "ERRCODE")));
3750                                 err_code = plpgsql_recognize_err_condition(extval, true);
3751                                 condname = MemoryContextStrdup(stmt_mcontext, extval);
3752                                 break;
3753                         case PLPGSQL_RAISEOPTION_MESSAGE:
3754                                 SET_RAISE_OPTION_TEXT(err_message, "MESSAGE");
3755                                 break;
3756                         case PLPGSQL_RAISEOPTION_DETAIL:
3757                                 SET_RAISE_OPTION_TEXT(err_detail, "DETAIL");
3758                                 break;
3759                         case PLPGSQL_RAISEOPTION_HINT:
3760                                 SET_RAISE_OPTION_TEXT(err_hint, "HINT");
3761                                 break;
3762                         case PLPGSQL_RAISEOPTION_COLUMN:
3763                                 SET_RAISE_OPTION_TEXT(err_column, "COLUMN");
3764                                 break;
3765                         case PLPGSQL_RAISEOPTION_CONSTRAINT:
3766                                 SET_RAISE_OPTION_TEXT(err_constraint, "CONSTRAINT");
3767                                 break;
3768                         case PLPGSQL_RAISEOPTION_DATATYPE:
3769                                 SET_RAISE_OPTION_TEXT(err_datatype, "DATATYPE");
3770                                 break;
3771                         case PLPGSQL_RAISEOPTION_TABLE:
3772                                 SET_RAISE_OPTION_TEXT(err_table, "TABLE");
3773                                 break;
3774                         case PLPGSQL_RAISEOPTION_SCHEMA:
3775                                 SET_RAISE_OPTION_TEXT(err_schema, "SCHEMA");
3776                                 break;
3777                         default:
3778                                 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
3779                 }
3780
3781                 exec_eval_cleanup(estate);
3782         }
3783
3784         /* Default code if nothing specified */
3785         if (err_code == 0 && stmt->elog_level >= ERROR)
3786                 err_code = ERRCODE_RAISE_EXCEPTION;
3787
3788         /* Default error message if nothing specified */
3789         if (err_message == NULL)
3790         {
3791                 if (condname)
3792                 {
3793                         err_message = condname;
3794                         condname = NULL;
3795                 }
3796                 else
3797                         err_message = MemoryContextStrdup(stmt_mcontext,
3798                                                                                           unpack_sql_state(err_code));
3799         }
3800
3801         /*
3802          * Throw the error (may or may not come back)
3803          */
3804         ereport(stmt->elog_level,
3805                         (err_code ? errcode(err_code) : 0,
3806                          errmsg_internal("%s", err_message),
3807                          (err_detail != NULL) ? errdetail_internal("%s", err_detail) : 0,
3808                          (err_hint != NULL) ? errhint("%s", err_hint) : 0,
3809                          (err_column != NULL) ?
3810                          err_generic_string(PG_DIAG_COLUMN_NAME, err_column) : 0,
3811                          (err_constraint != NULL) ?
3812                          err_generic_string(PG_DIAG_CONSTRAINT_NAME, err_constraint) : 0,
3813                          (err_datatype != NULL) ?
3814                          err_generic_string(PG_DIAG_DATATYPE_NAME, err_datatype) : 0,
3815                          (err_table != NULL) ?
3816                          err_generic_string(PG_DIAG_TABLE_NAME, err_table) : 0,
3817                          (err_schema != NULL) ?
3818                          err_generic_string(PG_DIAG_SCHEMA_NAME, err_schema) : 0));
3819
3820         /* Clean up transient strings */
3821         MemoryContextReset(stmt_mcontext);
3822
3823         return PLPGSQL_RC_OK;
3824 }
3825
3826 /* ----------
3827  * exec_stmt_assert                     Assert statement
3828  * ----------
3829  */
3830 static int
3831 exec_stmt_assert(PLpgSQL_execstate *estate, PLpgSQL_stmt_assert *stmt)
3832 {
3833         bool            value;
3834         bool            isnull;
3835
3836         /* do nothing when asserts are not enabled */
3837         if (!plpgsql_check_asserts)
3838                 return PLPGSQL_RC_OK;
3839
3840         value = exec_eval_boolean(estate, stmt->cond, &isnull);
3841         exec_eval_cleanup(estate);
3842
3843         if (isnull || !value)
3844         {
3845                 char       *message = NULL;
3846
3847                 if (stmt->message != NULL)
3848                 {
3849                         Datum           val;
3850                         Oid                     typeid;
3851                         int32           typmod;
3852
3853                         val = exec_eval_expr(estate, stmt->message,
3854                                                                  &isnull, &typeid, &typmod);
3855                         if (!isnull)
3856                                 message = convert_value_to_string(estate, val, typeid);
3857                         /* we mustn't do exec_eval_cleanup here */
3858                 }
3859
3860                 ereport(ERROR,
3861                                 (errcode(ERRCODE_ASSERT_FAILURE),
3862                                  message ? errmsg_internal("%s", message) :
3863                                  errmsg("assertion failed")));
3864         }
3865
3866         return PLPGSQL_RC_OK;
3867 }
3868
3869 /* ----------
3870  * Initialize a mostly empty execution state
3871  * ----------
3872  */
3873 static void
3874 plpgsql_estate_setup(PLpgSQL_execstate *estate,
3875                                          PLpgSQL_function *func,
3876                                          ReturnSetInfo *rsi,
3877                                          EState *simple_eval_estate)
3878 {
3879         HASHCTL         ctl;
3880
3881         /* this link will be restored at exit from plpgsql_call_handler */
3882         func->cur_estate = estate;
3883
3884         estate->func = func;
3885         estate->trigdata = NULL;
3886         estate->evtrigdata = NULL;
3887
3888         estate->retval = (Datum) 0;
3889         estate->retisnull = true;
3890         estate->rettype = InvalidOid;
3891
3892         estate->fn_rettype = func->fn_rettype;
3893         estate->retistuple = func->fn_retistuple;
3894         estate->retisset = func->fn_retset;
3895
3896         estate->readonly_func = func->fn_readonly;
3897         estate->atomic = true;
3898
3899         estate->exitlabel = NULL;
3900         estate->cur_error = NULL;
3901
3902         estate->tuple_store = NULL;
3903         estate->tuple_store_desc = NULL;
3904         if (rsi)
3905         {
3906                 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
3907                 estate->tuple_store_owner = CurrentResourceOwner;
3908         }
3909         else
3910         {
3911                 estate->tuple_store_cxt = NULL;
3912                 estate->tuple_store_owner = NULL;
3913         }
3914         estate->rsi = rsi;
3915
3916         estate->found_varno = func->found_varno;
3917         estate->ndatums = func->ndatums;
3918         estate->datums = NULL;
3919         /* the datums array will be filled by copy_plpgsql_datums() */
3920         estate->datum_context = CurrentMemoryContext;
3921
3922         /* initialize our ParamListInfo with appropriate hook functions */
3923         estate->paramLI = makeParamList(0);
3924         estate->paramLI->paramFetch = plpgsql_param_fetch;
3925         estate->paramLI->paramFetchArg = (void *) estate;
3926         estate->paramLI->paramCompile = plpgsql_param_compile;
3927         estate->paramLI->paramCompileArg = NULL;        /* not needed */
3928         estate->paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
3929         estate->paramLI->parserSetupArg = NULL; /* filled during use */
3930         estate->paramLI->numParams = estate->ndatums;
3931
3932         /* set up for use of appropriate simple-expression EState and cast hash */
3933         if (simple_eval_estate)
3934         {
3935                 estate->simple_eval_estate = simple_eval_estate;
3936                 /* Private cast hash just lives in function's main context */
3937                 memset(&ctl, 0, sizeof(ctl));
3938                 ctl.keysize = sizeof(plpgsql_CastHashKey);
3939                 ctl.entrysize = sizeof(plpgsql_CastHashEntry);
3940                 ctl.hcxt = CurrentMemoryContext;
3941                 estate->cast_hash = hash_create("PLpgSQL private cast cache",
3942                                                                                 16, /* start small and extend */
3943                                                                                 &ctl,
3944                                                                                 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
3945                 estate->cast_hash_context = CurrentMemoryContext;
3946         }
3947         else
3948         {
3949                 estate->simple_eval_estate = shared_simple_eval_estate;
3950                 /* Create the session-wide cast-info hash table if we didn't already */
3951                 if (shared_cast_hash == NULL)
3952                 {
3953                         shared_cast_context = AllocSetContextCreate(TopMemoryContext,
3954                                                                                                                 "PLpgSQL cast info",
3955                                                                                                                 ALLOCSET_DEFAULT_SIZES);
3956                         memset(&ctl, 0, sizeof(ctl));
3957                         ctl.keysize = sizeof(plpgsql_CastHashKey);
3958                         ctl.entrysize = sizeof(plpgsql_CastHashEntry);
3959                         ctl.hcxt = shared_cast_context;
3960                         shared_cast_hash = hash_create("PLpgSQL cast cache",
3961                                                                                    16,  /* start small and extend */
3962                                                                                    &ctl,
3963                                                                                    HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
3964                 }
3965                 estate->cast_hash = shared_cast_hash;
3966                 estate->cast_hash_context = shared_cast_context;
3967         }
3968
3969         /*
3970          * We start with no stmt_mcontext; one will be created only if needed.
3971          * That context will be a direct child of the function's main execution
3972          * context.  Additional stmt_mcontexts might be created as children of it.
3973          */
3974         estate->stmt_mcontext = NULL;
3975         estate->stmt_mcontext_parent = CurrentMemoryContext;
3976
3977         estate->eval_tuptable = NULL;
3978         estate->eval_processed = 0;
3979         estate->eval_econtext = NULL;
3980
3981         estate->err_stmt = NULL;
3982         estate->err_text = NULL;
3983
3984         estate->plugin_info = NULL;
3985
3986         /*
3987          * Create an EState and ExprContext for evaluation of simple expressions.
3988          */
3989         plpgsql_create_econtext(estate);
3990
3991         /*
3992          * Let the plugin see this function before we initialize any local
3993          * PL/pgSQL variables - note that we also give the plugin a few function
3994          * pointers so it can call back into PL/pgSQL for doing things like
3995          * variable assignments and stack traces
3996          */
3997         if (*plpgsql_plugin_ptr)
3998         {
3999                 (*plpgsql_plugin_ptr)->error_callback = plpgsql_exec_error_callback;
4000                 (*plpgsql_plugin_ptr)->assign_expr = exec_assign_expr;
4001
4002                 if ((*plpgsql_plugin_ptr)->func_setup)
4003                         ((*plpgsql_plugin_ptr)->func_setup) (estate, func);
4004         }
4005 }
4006
4007 /* ----------
4008  * Release temporary memory used by expression/subselect evaluation
4009  *
4010  * NB: the result of the evaluation is no longer valid after this is done,
4011  * unless it is a pass-by-value datatype.
4012  *
4013  * NB: if you change this code, see also the hacks in exec_assign_value's
4014  * PLPGSQL_DTYPE_ARRAYELEM case for partial cleanup after subscript evals.
4015  * ----------
4016  */
4017 static void
4018 exec_eval_cleanup(PLpgSQL_execstate *estate)
4019 {
4020         /* Clear result of a full SPI_execute */
4021         if (estate->eval_tuptable != NULL)
4022                 SPI_freetuptable(estate->eval_tuptable);
4023         estate->eval_tuptable = NULL;
4024
4025         /*
4026          * Clear result of exec_eval_simple_expr (but keep the econtext).  This
4027          * also clears any short-lived allocations done via get_eval_mcontext.
4028          */
4029         if (estate->eval_econtext != NULL)
4030                 ResetExprContext(estate->eval_econtext);
4031 }
4032
4033
4034 /* ----------
4035  * Generate a prepared plan
4036  * ----------
4037  */
4038 static void
4039 exec_prepare_plan(PLpgSQL_execstate *estate,
4040                                   PLpgSQL_expr *expr, int cursorOptions,
4041                                   bool keepplan)
4042 {
4043         SPIPlanPtr      plan;
4044
4045         /*
4046          * The grammar can't conveniently set expr->func while building the parse
4047          * tree, so make sure it's set before parser hooks need it.
4048          */
4049         expr->func = estate->func;
4050
4051         /*
4052          * Generate and save the plan
4053          */
4054         plan = SPI_prepare_params(expr->query,
4055                                                           (ParserSetupHook) plpgsql_parser_setup,
4056                                                           (void *) expr,
4057                                                           cursorOptions);
4058         if (plan == NULL)
4059                 elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
4060                          expr->query, SPI_result_code_string(SPI_result));
4061         if (keepplan)
4062                 SPI_keepplan(plan);
4063         expr->plan = plan;
4064
4065         /* Check to see if it's a simple expression */
4066         exec_simple_check_plan(estate, expr);
4067
4068         /*
4069          * Mark expression as not using a read-write param.  exec_assign_value has
4070          * to take steps to override this if appropriate; that seems cleaner than
4071          * adding parameters to all other callers.
4072          */
4073         expr->rwparam = -1;
4074 }
4075
4076
4077 /* ----------
4078  * exec_stmt_execsql                    Execute an SQL statement (possibly with INTO).
4079  *
4080  * Note: some callers rely on this not touching stmt_mcontext.  If it ever
4081  * needs to use that, fix those callers to push/pop stmt_mcontext.
4082  * ----------
4083  */
4084 static int
4085 exec_stmt_execsql(PLpgSQL_execstate *estate,
4086                                   PLpgSQL_stmt_execsql *stmt)
4087 {
4088         ParamListInfo paramLI;
4089         long            tcount;
4090         int                     rc;
4091         PLpgSQL_expr *expr = stmt->sqlstmt;
4092         int                     too_many_rows_level = 0;
4093
4094         if (plpgsql_extra_errors & PLPGSQL_XCHECK_TOOMANYROWS)
4095                 too_many_rows_level = ERROR;
4096         else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_TOOMANYROWS)
4097                 too_many_rows_level = WARNING;
4098
4099         /*
4100          * On the first call for this statement generate the plan, and detect
4101          * whether the statement is INSERT/UPDATE/DELETE
4102          */
4103         if (expr->plan == NULL)
4104         {
4105                 ListCell   *l;
4106
4107                 exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK, true);
4108                 stmt->mod_stmt = false;
4109                 foreach(l, SPI_plan_get_plan_sources(expr->plan))
4110                 {
4111                         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
4112
4113                         /*
4114                          * We could look at the raw_parse_tree, but it seems simpler to
4115                          * check the command tag.  Note we should *not* look at the Query
4116                          * tree(s), since those are the result of rewriting and could have
4117                          * been transmogrified into something else entirely.
4118                          */
4119                         if (plansource->commandTag &&
4120                                 (strcmp(plansource->commandTag, "INSERT") == 0 ||
4121                                  strcmp(plansource->commandTag, "UPDATE") == 0 ||
4122                                  strcmp(plansource->commandTag, "DELETE") == 0))
4123                         {
4124                                 stmt->mod_stmt = true;
4125                                 break;
4126                         }
4127                 }
4128         }
4129
4130         /*
4131          * Set up ParamListInfo to pass to executor
4132          */
4133         paramLI = setup_param_list(estate, expr);
4134
4135         /*
4136          * If we have INTO, then we only need one row back ... but if we have INTO
4137          * STRICT or extra check too_many_rows, ask for two rows, so that we can
4138          * verify the statement returns only one.  INSERT/UPDATE/DELETE are always
4139          * treated strictly. Without INTO, just run the statement to completion
4140          * (tcount = 0).
4141          *
4142          * We could just ask for two rows always when using INTO, but there are
4143          * some cases where demanding the extra row costs significant time, eg by
4144          * forcing completion of a sequential scan.  So don't do it unless we need
4145          * to enforce strictness.
4146          */
4147         if (stmt->into)
4148         {
4149                 if (stmt->strict || stmt->mod_stmt || too_many_rows_level)
4150                         tcount = 2;
4151                 else
4152                         tcount = 1;
4153         }
4154         else
4155                 tcount = 0;
4156
4157         /*
4158          * Execute the plan
4159          */
4160         rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4161                                                                                  estate->readonly_func, tcount);
4162
4163         /*
4164          * Check for error, and set FOUND if appropriate (for historical reasons
4165          * we set FOUND only for certain query types).  Also Assert that we
4166          * identified the statement type the same as SPI did.
4167          */
4168         switch (rc)
4169         {
4170                 case SPI_OK_SELECT:
4171                         Assert(!stmt->mod_stmt);
4172                         exec_set_found(estate, (SPI_processed != 0));
4173                         break;
4174
4175                 case SPI_OK_INSERT:
4176                 case SPI_OK_UPDATE:
4177                 case SPI_OK_DELETE:
4178                 case SPI_OK_INSERT_RETURNING:
4179                 case SPI_OK_UPDATE_RETURNING:
4180                 case SPI_OK_DELETE_RETURNING:
4181                         Assert(stmt->mod_stmt);
4182                         exec_set_found(estate, (SPI_processed != 0));
4183                         break;
4184
4185                 case SPI_OK_SELINTO:
4186                 case SPI_OK_UTILITY:
4187                         Assert(!stmt->mod_stmt);
4188                         break;
4189
4190                 case SPI_OK_REWRITTEN:
4191
4192                         /*
4193                          * The command was rewritten into another kind of command. It's
4194                          * not clear what FOUND would mean in that case (and SPI doesn't
4195                          * return the row count either), so just set it to false.  Note
4196                          * that we can't assert anything about mod_stmt here.
4197                          */
4198                         exec_set_found(estate, false);
4199                         break;
4200
4201                         /* Some SPI errors deserve specific error messages */
4202                 case SPI_ERROR_COPY:
4203                         ereport(ERROR,
4204                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4205                                          errmsg("cannot COPY to/from client in PL/pgSQL")));
4206                         break;
4207
4208                 case SPI_ERROR_TRANSACTION:
4209                         ereport(ERROR,
4210                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4211                                          errmsg("unsupported transaction command in PL/pgSQL")));
4212                         break;
4213
4214                 default:
4215                         elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
4216                                  expr->query, SPI_result_code_string(rc));
4217                         break;
4218         }
4219
4220         /* All variants should save result info for GET DIAGNOSTICS */
4221         estate->eval_processed = SPI_processed;
4222
4223         /* Process INTO if present */
4224         if (stmt->into)
4225         {
4226                 SPITupleTable *tuptab = SPI_tuptable;
4227                 uint64          n = SPI_processed;
4228                 PLpgSQL_variable *target;
4229
4230                 /* If the statement did not return a tuple table, complain */
4231                 if (tuptab == NULL)
4232                         ereport(ERROR,
4233                                         (errcode(ERRCODE_SYNTAX_ERROR),
4234                                          errmsg("INTO used with a command that cannot return data")));
4235
4236                 /* Fetch target's datum entry */
4237                 target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4238
4239                 /*
4240                  * If SELECT ... INTO specified STRICT, and the query didn't find
4241                  * exactly one row, throw an error.  If STRICT was not specified, then
4242                  * allow the query to find any number of rows.
4243                  */
4244                 if (n == 0)
4245                 {
4246                         if (stmt->strict)
4247                         {
4248                                 char       *errdetail;
4249
4250                                 if (estate->func->print_strict_params)
4251                                         errdetail = format_expr_params(estate, expr);
4252                                 else
4253                                         errdetail = NULL;
4254
4255                                 ereport(ERROR,
4256                                                 (errcode(ERRCODE_NO_DATA_FOUND),
4257                                                  errmsg("query returned no rows"),
4258                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4259                         }
4260                         /* set the target to NULL(s) */
4261                         exec_move_row(estate, target, NULL, tuptab->tupdesc);
4262                 }
4263                 else
4264                 {
4265                         if (n > 1 && (stmt->strict || stmt->mod_stmt || too_many_rows_level))
4266                         {
4267                                 char       *errdetail;
4268                                 int                     errlevel;
4269
4270                                 if (estate->func->print_strict_params)
4271                                         errdetail = format_expr_params(estate, expr);
4272                                 else
4273                                         errdetail = NULL;
4274
4275                                 errlevel = (stmt->strict || stmt->mod_stmt) ? ERROR : too_many_rows_level;
4276
4277                                 ereport(errlevel,
4278                                                 (errcode(ERRCODE_TOO_MANY_ROWS),
4279                                                  errmsg("query returned more than one row"),
4280                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0,
4281                                                  errhint("Make sure the query returns a single row, or use LIMIT 1.")));
4282                         }
4283                         /* Put the first result row into the target */
4284                         exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4285                 }
4286
4287                 /* Clean up */
4288                 exec_eval_cleanup(estate);
4289                 SPI_freetuptable(SPI_tuptable);
4290         }
4291         else
4292         {
4293                 /* If the statement returned a tuple table, complain */
4294                 if (SPI_tuptable != NULL)
4295                         ereport(ERROR,
4296                                         (errcode(ERRCODE_SYNTAX_ERROR),
4297                                          errmsg("query has no destination for result data"),
4298                                          (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
4299         }
4300
4301         return PLPGSQL_RC_OK;
4302 }
4303
4304
4305 /* ----------
4306  * exec_stmt_dynexecute                 Execute a dynamic SQL query
4307  *                                      (possibly with INTO).
4308  * ----------
4309  */
4310 static int
4311 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
4312                                          PLpgSQL_stmt_dynexecute *stmt)
4313 {
4314         Datum           query;
4315         bool            isnull;
4316         Oid                     restype;
4317         int32           restypmod;
4318         char       *querystr;
4319         int                     exec_res;
4320         PreparedParamsData *ppd = NULL;
4321         MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
4322
4323         /*
4324          * First we evaluate the string expression after the EXECUTE keyword. Its
4325          * result is the querystring we have to execute.
4326          */
4327         query = exec_eval_expr(estate, stmt->query, &isnull, &restype, &restypmod);
4328         if (isnull)
4329                 ereport(ERROR,
4330                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4331                                  errmsg("query string argument of EXECUTE is null")));
4332
4333         /* Get the C-String representation */
4334         querystr = convert_value_to_string(estate, query, restype);
4335
4336         /* copy it into the stmt_mcontext before we clean up */
4337         querystr = MemoryContextStrdup(stmt_mcontext, querystr);
4338
4339         exec_eval_cleanup(estate);
4340
4341         /*
4342          * Execute the query without preparing a saved plan.
4343          */
4344         if (stmt->params)
4345         {
4346                 ppd = exec_eval_using_params(estate, stmt->params);
4347                 exec_res = SPI_execute_with_args(querystr,
4348                                                                                  ppd->nargs, ppd->types,
4349                                                                                  ppd->values, ppd->nulls,
4350                                                                                  estate->readonly_func, 0);
4351         }
4352         else
4353                 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
4354
4355         switch (exec_res)
4356         {
4357                 case SPI_OK_SELECT:
4358                 case SPI_OK_INSERT:
4359                 case SPI_OK_UPDATE:
4360                 case SPI_OK_DELETE:
4361                 case SPI_OK_INSERT_RETURNING:
4362                 case SPI_OK_UPDATE_RETURNING:
4363                 case SPI_OK_DELETE_RETURNING:
4364                 case SPI_OK_UTILITY:
4365                 case SPI_OK_REWRITTEN:
4366                         break;
4367
4368                 case 0:
4369
4370                         /*
4371                          * Also allow a zero return, which implies the querystring
4372                          * contained no commands.
4373                          */
4374                         break;
4375
4376                 case SPI_OK_SELINTO:
4377
4378                         /*
4379                          * We want to disallow SELECT INTO for now, because its behavior
4380                          * is not consistent with SELECT INTO in a normal plpgsql context.
4381                          * (We need to reimplement EXECUTE to parse the string as a
4382                          * plpgsql command, not just feed it to SPI_execute.)  This is not
4383                          * a functional limitation because CREATE TABLE AS is allowed.
4384                          */
4385                         ereport(ERROR,
4386                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4387                                          errmsg("EXECUTE of SELECT ... INTO is not implemented"),
4388                                          errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
4389                         break;
4390
4391                         /* Some SPI errors deserve specific error messages */
4392                 case SPI_ERROR_COPY:
4393                         ereport(ERROR,
4394                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4395                                          errmsg("cannot COPY to/from client in PL/pgSQL")));
4396                         break;
4397
4398                 case SPI_ERROR_TRANSACTION:
4399                         ereport(ERROR,
4400                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4401                                          errmsg("EXECUTE of transaction commands is not implemented")));
4402                         break;
4403
4404                 default:
4405                         elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
4406                                  querystr, SPI_result_code_string(exec_res));
4407                         break;
4408         }
4409
4410         /* Save result info for GET DIAGNOSTICS */
4411         estate->eval_processed = SPI_processed;
4412
4413         /* Process INTO if present */
4414         if (stmt->into)
4415         {
4416                 SPITupleTable *tuptab = SPI_tuptable;
4417                 uint64          n = SPI_processed;
4418                 PLpgSQL_variable *target;
4419
4420                 /* If the statement did not return a tuple table, complain */
4421                 if (tuptab == NULL)
4422                         ereport(ERROR,
4423                                         (errcode(ERRCODE_SYNTAX_ERROR),
4424                                          errmsg("INTO used with a command that cannot return data")));
4425
4426                 /* Fetch target's datum entry */
4427                 target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4428
4429                 /*
4430                  * If SELECT ... INTO specified STRICT, and the query didn't find
4431                  * exactly one row, throw an error.  If STRICT was not specified, then
4432                  * allow the query to find any number of rows.
4433                  */
4434                 if (n == 0)
4435                 {
4436                         if (stmt->strict)
4437                         {
4438                                 char       *errdetail;
4439
4440                                 if (estate->func->print_strict_params)
4441                                         errdetail = format_preparedparamsdata(estate, ppd);
4442                                 else
4443                                         errdetail = NULL;
4444
4445                                 ereport(ERROR,
4446                                                 (errcode(ERRCODE_NO_DATA_FOUND),
4447                                                  errmsg("query returned no rows"),
4448                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4449                         }
4450                         /* set the target to NULL(s) */
4451                         exec_move_row(estate, target, NULL, tuptab->tupdesc);
4452                 }
4453                 else
4454                 {
4455                         if (n > 1 && stmt->strict)
4456                         {
4457                                 char       *errdetail;
4458
4459                                 if (estate->func->print_strict_params)
4460                                         errdetail = format_preparedparamsdata(estate, ppd);
4461                                 else
4462                                         errdetail = NULL;
4463
4464                                 ereport(ERROR,
4465                                                 (errcode(ERRCODE_TOO_MANY_ROWS),
4466                                                  errmsg("query returned more than one row"),
4467                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4468                         }
4469
4470                         /* Put the first result row into the target */
4471                         exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4472                 }
4473                 /* clean up after exec_move_row() */
4474                 exec_eval_cleanup(estate);
4475         }
4476         else
4477         {
4478                 /*
4479                  * It might be a good idea to raise an error if the query returned
4480                  * tuples that are being ignored, but historically we have not done
4481                  * that.
4482                  */
4483         }
4484
4485         /* Release any result from SPI_execute, as well as transient data */
4486         SPI_freetuptable(SPI_tuptable);
4487         MemoryContextReset(stmt_mcontext);
4488
4489         return PLPGSQL_RC_OK;
4490 }
4491
4492
4493 /* ----------
4494  * exec_stmt_dynfors                    Execute a dynamic query, assign each
4495  *                                      tuple to a record or row and
4496  *                                      execute a group of statements
4497  *                                      for it.
4498  * ----------
4499  */
4500 static int
4501 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
4502 {
4503         Portal          portal;
4504         int                     rc;
4505
4506         portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
4507                                                                            NULL, 0);
4508
4509         /*
4510          * Execute the loop
4511          */
4512         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
4513
4514         /*
4515          * Close the implicit cursor
4516          */
4517         SPI_cursor_close(portal);
4518
4519         return rc;
4520 }
4521
4522
4523 /* ----------
4524  * exec_stmt_open                       Execute an OPEN cursor statement
4525  * ----------
4526  */
4527 static int
4528 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
4529 {
4530         PLpgSQL_var *curvar;
4531         MemoryContext stmt_mcontext = NULL;
4532         char       *curname = NULL;
4533         PLpgSQL_expr *query;
4534         Portal          portal;
4535         ParamListInfo paramLI;
4536
4537         /* ----------
4538          * Get the cursor variable and if it has an assigned name, check
4539          * that it's not in use currently.
4540          * ----------
4541          */
4542         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4543         if (!curvar->isnull)
4544         {
4545                 MemoryContext oldcontext;
4546
4547                 /* We only need stmt_mcontext to hold the cursor name string */
4548                 stmt_mcontext = get_stmt_mcontext(estate);
4549                 oldcontext = MemoryContextSwitchTo(stmt_mcontext);
4550                 curname = TextDatumGetCString(curvar->value);
4551                 MemoryContextSwitchTo(oldcontext);
4552
4553                 if (SPI_cursor_find(curname) != NULL)
4554                         ereport(ERROR,
4555                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
4556                                          errmsg("cursor \"%s\" already in use", curname)));
4557         }
4558
4559         /* ----------
4560          * Process the OPEN according to it's type.
4561          * ----------
4562          */
4563         if (stmt->query != NULL)
4564         {
4565                 /* ----------
4566                  * This is an OPEN refcursor FOR SELECT ...
4567                  *
4568                  * We just make sure the query is planned. The real work is
4569                  * done downstairs.
4570                  * ----------
4571                  */
4572                 query = stmt->query;
4573                 if (query->plan == NULL)
4574                         exec_prepare_plan(estate, query, stmt->cursor_options, true);
4575         }
4576         else if (stmt->dynquery != NULL)
4577         {
4578                 /* ----------
4579                  * This is an OPEN refcursor FOR EXECUTE ...
4580                  * ----------
4581                  */
4582                 portal = exec_dynquery_with_params(estate,
4583                                                                                    stmt->dynquery,
4584                                                                                    stmt->params,
4585                                                                                    curname,
4586                                                                                    stmt->cursor_options);
4587
4588                 /*
4589                  * If cursor variable was NULL, store the generated portal name in it.
4590                  * Note: exec_dynquery_with_params already reset the stmt_mcontext, so
4591                  * curname is a dangling pointer here; but testing it for nullness is
4592                  * OK.
4593                  */
4594                 if (curname == NULL)
4595                         assign_text_var(estate, curvar, portal->name);
4596
4597                 return PLPGSQL_RC_OK;
4598         }
4599         else
4600         {
4601                 /* ----------
4602                  * This is an OPEN cursor
4603                  *
4604                  * Note: parser should already have checked that statement supplies
4605                  * args iff cursor needs them, but we check again to be safe.
4606                  * ----------
4607                  */
4608                 if (stmt->argquery != NULL)
4609                 {
4610                         /* ----------
4611                          * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
4612                          * statement to evaluate the args and put 'em into the
4613                          * internal row.
4614                          * ----------
4615                          */
4616                         PLpgSQL_stmt_execsql set_args;
4617
4618                         if (curvar->cursor_explicit_argrow < 0)
4619                                 ereport(ERROR,
4620                                                 (errcode(ERRCODE_SYNTAX_ERROR),
4621                                                  errmsg("arguments given for cursor without arguments")));
4622
4623                         memset(&set_args, 0, sizeof(set_args));
4624                         set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
4625                         set_args.lineno = stmt->lineno;
4626                         set_args.sqlstmt = stmt->argquery;
4627                         set_args.into = true;
4628                         /* XXX historically this has not been STRICT */
4629                         set_args.target = (PLpgSQL_variable *)
4630                                 (estate->datums[curvar->cursor_explicit_argrow]);
4631
4632                         if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
4633                                 elog(ERROR, "open cursor failed during argument processing");
4634                 }
4635                 else
4636                 {
4637                         if (curvar->cursor_explicit_argrow >= 0)
4638                                 ereport(ERROR,
4639                                                 (errcode(ERRCODE_SYNTAX_ERROR),
4640                                                  errmsg("arguments required for cursor")));
4641                 }
4642
4643                 query = curvar->cursor_explicit_expr;
4644                 if (query->plan == NULL)
4645                         exec_prepare_plan(estate, query, curvar->cursor_options, true);
4646         }
4647
4648         /*
4649          * Set up ParamListInfo for this query
4650          */
4651         paramLI = setup_param_list(estate, query);
4652
4653         /*
4654          * Open the cursor (the paramlist will get copied into the portal)
4655          */
4656         portal = SPI_cursor_open_with_paramlist(curname, query->plan,
4657                                                                                         paramLI,
4658                                                                                         estate->readonly_func);
4659         if (portal == NULL)
4660                 elog(ERROR, "could not open cursor: %s",
4661                          SPI_result_code_string(SPI_result));
4662
4663         /*
4664          * If cursor variable was NULL, store the generated portal name in it
4665          */
4666         if (curname == NULL)
4667                 assign_text_var(estate, curvar, portal->name);
4668
4669         /* If we had any transient data, clean it up */
4670         exec_eval_cleanup(estate);
4671         if (stmt_mcontext)
4672                 MemoryContextReset(stmt_mcontext);
4673
4674         return PLPGSQL_RC_OK;
4675 }
4676
4677
4678 /* ----------
4679  * exec_stmt_fetch                      Fetch from a cursor into a target, or just
4680  *                                                      move the current position of the cursor
4681  * ----------
4682  */
4683 static int
4684 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
4685 {
4686         PLpgSQL_var *curvar;
4687         long            how_many = stmt->how_many;
4688         SPITupleTable *tuptab;
4689         Portal          portal;
4690         char       *curname;
4691         uint64          n;
4692         MemoryContext oldcontext;
4693
4694         /* ----------
4695          * Get the portal of the cursor by name
4696          * ----------
4697          */
4698         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4699         if (curvar->isnull)
4700                 ereport(ERROR,
4701                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4702                                  errmsg("cursor variable \"%s\" is null", curvar->refname)));
4703
4704         /* Use eval_mcontext for short-lived string */
4705         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4706         curname = TextDatumGetCString(curvar->value);
4707         MemoryContextSwitchTo(oldcontext);
4708
4709         portal = SPI_cursor_find(curname);
4710         if (portal == NULL)
4711                 ereport(ERROR,
4712                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
4713                                  errmsg("cursor \"%s\" does not exist", curname)));
4714
4715         /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
4716         if (stmt->expr)
4717         {
4718                 bool            isnull;
4719
4720                 /* XXX should be doing this in LONG not INT width */
4721                 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
4722
4723                 if (isnull)
4724                         ereport(ERROR,
4725                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4726                                          errmsg("relative or absolute cursor position is null")));
4727
4728                 exec_eval_cleanup(estate);
4729         }
4730
4731         if (!stmt->is_move)
4732         {
4733                 PLpgSQL_variable *target;
4734
4735                 /* ----------
4736                  * Fetch 1 tuple from the cursor
4737                  * ----------
4738                  */
4739                 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
4740                 tuptab = SPI_tuptable;
4741                 n = SPI_processed;
4742
4743                 /* ----------
4744                  * Set the target appropriately.
4745                  * ----------
4746                  */
4747                 target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4748                 if (n == 0)
4749                         exec_move_row(estate, target, NULL, tuptab->tupdesc);
4750                 else
4751                         exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4752
4753                 exec_eval_cleanup(estate);
4754                 SPI_freetuptable(tuptab);
4755         }
4756         else
4757         {
4758                 /* Move the cursor */
4759                 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
4760                 n = SPI_processed;
4761         }
4762
4763         /* Set the ROW_COUNT and the global FOUND variable appropriately. */
4764         estate->eval_processed = n;
4765         exec_set_found(estate, n != 0);
4766
4767         return PLPGSQL_RC_OK;
4768 }
4769
4770 /* ----------
4771  * exec_stmt_close                      Close a cursor
4772  * ----------
4773  */
4774 static int
4775 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
4776 {
4777         PLpgSQL_var *curvar;
4778         Portal          portal;
4779         char       *curname;
4780         MemoryContext oldcontext;
4781
4782         /* ----------
4783          * Get the portal of the cursor by name
4784          * ----------
4785          */
4786         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4787         if (curvar->isnull)
4788                 ereport(ERROR,
4789                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4790                                  errmsg("cursor variable \"%s\" is null", curvar->refname)));
4791
4792         /* Use eval_mcontext for short-lived string */
4793         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4794         curname = TextDatumGetCString(curvar->value);
4795         MemoryContextSwitchTo(oldcontext);
4796
4797         portal = SPI_cursor_find(curname);
4798         if (portal == NULL)
4799                 ereport(ERROR,
4800                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
4801                                  errmsg("cursor \"%s\" does not exist", curname)));
4802
4803         /* ----------
4804          * And close it.
4805          * ----------
4806          */
4807         SPI_cursor_close(portal);
4808
4809         return PLPGSQL_RC_OK;
4810 }
4811
4812 /*
4813  * exec_stmt_commit
4814  *
4815  * Commit the transaction.
4816  */
4817 static int
4818 exec_stmt_commit(PLpgSQL_execstate *estate, PLpgSQL_stmt_commit *stmt)
4819 {
4820         if (stmt->chain)
4821                 SPI_commit_and_chain();
4822         else
4823         {
4824                 SPI_commit();
4825                 SPI_start_transaction();
4826         }
4827
4828         estate->simple_eval_estate = NULL;
4829         plpgsql_create_econtext(estate);
4830
4831         return PLPGSQL_RC_OK;
4832 }
4833
4834 /*
4835  * exec_stmt_rollback
4836  *
4837  * Abort the transaction.
4838  */
4839 static int
4840 exec_stmt_rollback(PLpgSQL_execstate *estate, PLpgSQL_stmt_rollback *stmt)
4841 {
4842         if (stmt->chain)
4843                 SPI_rollback_and_chain();
4844         else
4845         {
4846                 SPI_rollback();
4847                 SPI_start_transaction();
4848         }
4849
4850         estate->simple_eval_estate = NULL;
4851         plpgsql_create_econtext(estate);
4852
4853         return PLPGSQL_RC_OK;
4854 }
4855
4856 /*
4857  * exec_stmt_set
4858  *
4859  * Execute SET/RESET statement.
4860  *
4861  * We just parse and execute the statement normally, but we have to do it
4862  * without setting a snapshot, for things like SET TRANSACTION.
4863  */
4864 static int
4865 exec_stmt_set(PLpgSQL_execstate *estate, PLpgSQL_stmt_set *stmt)
4866 {
4867         PLpgSQL_expr *expr = stmt->expr;
4868         int                     rc;
4869
4870         if (expr->plan == NULL)
4871         {
4872                 exec_prepare_plan(estate, expr, 0, true);
4873                 expr->plan->no_snapshots = true;
4874         }
4875
4876         rc = SPI_execute_plan(expr->plan, NULL, NULL, estate->readonly_func, 0);
4877
4878         if (rc != SPI_OK_UTILITY)
4879                 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
4880                          expr->query, SPI_result_code_string(rc));
4881
4882         return PLPGSQL_RC_OK;
4883 }
4884
4885 /* ----------
4886  * exec_assign_expr                     Put an expression's result into a variable.
4887  * ----------
4888  */
4889 static void
4890 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
4891                                  PLpgSQL_expr *expr)
4892 {
4893         Datum           value;
4894         bool            isnull;
4895         Oid                     valtype;
4896         int32           valtypmod;
4897
4898         /*
4899          * If first time through, create a plan for this expression, and then see
4900          * if we can pass the target variable as a read-write parameter to the
4901          * expression.  (This is a bit messy, but it seems cleaner than modifying
4902          * the API of exec_eval_expr for the purpose.)
4903          */
4904         if (expr->plan == NULL)
4905         {
4906                 exec_prepare_plan(estate, expr, 0, true);
4907                 if (target->dtype == PLPGSQL_DTYPE_VAR)
4908                         exec_check_rw_parameter(expr, target->dno);
4909         }
4910
4911         value = exec_eval_expr(estate, expr, &isnull, &valtype, &valtypmod);
4912         exec_assign_value(estate, target, value, isnull, valtype, valtypmod);
4913         exec_eval_cleanup(estate);
4914 }
4915
4916
4917 /* ----------
4918  * exec_assign_c_string         Put a C string into a text variable.
4919  *
4920  * We take a NULL pointer as signifying empty string, not SQL null.
4921  *
4922  * As with the underlying exec_assign_value, caller is expected to do
4923  * exec_eval_cleanup later.
4924  * ----------
4925  */
4926 static void
4927 exec_assign_c_string(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
4928                                          const char *str)
4929 {
4930         text       *value;
4931         MemoryContext oldcontext;
4932
4933         /* Use eval_mcontext for short-lived text value */
4934         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4935         if (str != NULL)
4936                 value = cstring_to_text(str);
4937         else
4938                 value = cstring_to_text("");
4939         MemoryContextSwitchTo(oldcontext);
4940
4941         exec_assign_value(estate, target, PointerGetDatum(value), false,
4942                                           TEXTOID, -1);
4943 }
4944
4945
4946 /* ----------
4947  * exec_assign_value                    Put a value into a target datum
4948  *
4949  * Note: in some code paths, this will leak memory in the eval_mcontext;
4950  * we assume that will be cleaned up later by exec_eval_cleanup.  We cannot
4951  * call exec_eval_cleanup here for fear of destroying the input Datum value.
4952  * ----------
4953  */
4954 static void
4955 exec_assign_value(PLpgSQL_execstate *estate,
4956                                   PLpgSQL_datum *target,
4957                                   Datum value, bool isNull,
4958                                   Oid valtype, int32 valtypmod)
4959 {
4960         switch (target->dtype)
4961         {
4962                 case PLPGSQL_DTYPE_VAR:
4963                 case PLPGSQL_DTYPE_PROMISE:
4964                         {
4965                                 /*
4966                                  * Target is a variable
4967                                  */
4968                                 PLpgSQL_var *var = (PLpgSQL_var *) target;
4969                                 Datum           newvalue;
4970
4971                                 newvalue = exec_cast_value(estate,
4972                                                                                    value,
4973                                                                                    &isNull,
4974                                                                                    valtype,
4975                                                                                    valtypmod,
4976                                                                                    var->datatype->typoid,
4977                                                                                    var->datatype->atttypmod);
4978
4979                                 if (isNull && var->notnull)
4980                                         ereport(ERROR,
4981                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4982                                                          errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
4983                                                                         var->refname)));
4984
4985                                 /*
4986                                  * If type is by-reference, copy the new value (which is
4987                                  * probably in the eval_mcontext) into the procedure's main
4988                                  * memory context.  But if it's a read/write reference to an
4989                                  * expanded object, no physical copy needs to happen; at most
4990                                  * we need to reparent the object's memory context.
4991                                  *
4992                                  * If it's an array, we force the value to be stored in R/W
4993                                  * expanded form.  This wins if the function later does, say,
4994                                  * a lot of array subscripting operations on the variable, and
4995                                  * otherwise might lose.  We might need to use a different
4996                                  * heuristic, but it's too soon to tell.  Also, are there
4997                                  * cases where it'd be useful to force non-array values into
4998                                  * expanded form?
4999                                  */
5000                                 if (!var->datatype->typbyval && !isNull)
5001                                 {
5002                                         if (var->datatype->typisarray &&
5003                                                 !VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(newvalue)))
5004                                         {
5005                                                 /* array and not already R/W, so apply expand_array */
5006                                                 newvalue = expand_array(newvalue,
5007                                                                                                 estate->datum_context,
5008                                                                                                 NULL);
5009                                         }
5010                                         else
5011                                         {
5012                                                 /* else transfer value if R/W, else just datumCopy */
5013                                                 newvalue = datumTransfer(newvalue,
5014                                                                                                  false,
5015                                                                                                  var->datatype->typlen);
5016                                         }
5017                                 }
5018
5019                                 /*
5020                                  * Now free the old value, if any, and assign the new one. But
5021                                  * skip the assignment if old and new values are the same.
5022                                  * Note that for expanded objects, this test is necessary and
5023                                  * cannot reliably be made any earlier; we have to be looking
5024                                  * at the object's standard R/W pointer to be sure pointer
5025                                  * equality is meaningful.
5026                                  *
5027                                  * Also, if it's a promise variable, we should disarm the
5028                                  * promise in any case --- otherwise, assigning null to an
5029                                  * armed promise variable would fail to disarm the promise.
5030                                  */
5031                                 if (var->value != newvalue || var->isnull || isNull)
5032                                         assign_simple_var(estate, var, newvalue, isNull,
5033                                                                           (!var->datatype->typbyval && !isNull));
5034                                 else
5035                                         var->promise = PLPGSQL_PROMISE_NONE;
5036                                 break;
5037                         }
5038
5039                 case PLPGSQL_DTYPE_ROW:
5040                         {
5041                                 /*
5042                                  * Target is a row variable
5043                                  */
5044                                 PLpgSQL_row *row = (PLpgSQL_row *) target;
5045
5046                                 if (isNull)
5047                                 {
5048                                         /* If source is null, just assign nulls to the row */
5049                                         exec_move_row(estate, (PLpgSQL_variable *) row,
5050                                                                   NULL, NULL);
5051                                 }
5052                                 else
5053                                 {
5054                                         /* Source must be of RECORD or composite type */
5055                                         if (!type_is_rowtype(valtype))
5056                                                 ereport(ERROR,
5057                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
5058                                                                  errmsg("cannot assign non-composite value to a row variable")));
5059                                         exec_move_row_from_datum(estate, (PLpgSQL_variable *) row,
5060                                                                                          value);
5061                                 }
5062                                 break;
5063                         }
5064
5065                 case PLPGSQL_DTYPE_REC:
5066                         {
5067                                 /*
5068                                  * Target is a record variable
5069                                  */
5070                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
5071
5072                                 if (isNull)
5073                                 {
5074                                         if (rec->notnull)
5075                                                 ereport(ERROR,
5076                                                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5077                                                                  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
5078                                                                                 rec->refname)));
5079
5080                                         /* Set variable to a simple NULL */
5081                                         exec_move_row(estate, (PLpgSQL_variable *) rec,
5082                                                                   NULL, NULL);
5083                                 }
5084                                 else
5085                                 {
5086                                         /* Source must be of RECORD or composite type */
5087                                         if (!type_is_rowtype(valtype))
5088                                                 ereport(ERROR,
5089                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
5090                                                                  errmsg("cannot assign non-composite value to a record variable")));
5091                                         exec_move_row_from_datum(estate, (PLpgSQL_variable *) rec,
5092                                                                                          value);
5093                                 }
5094                                 break;
5095                         }
5096
5097                 case PLPGSQL_DTYPE_RECFIELD:
5098                         {
5099                                 /*
5100                                  * Target is a field of a record
5101                                  */
5102                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
5103                                 PLpgSQL_rec *rec;
5104                                 ExpandedRecordHeader *erh;
5105
5106                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5107                                 erh = rec->erh;
5108
5109                                 /*
5110                                  * If record variable is NULL, instantiate it if it has a
5111                                  * named composite type, else complain.  (This won't change
5112                                  * the logical state of the record, but if we successfully
5113                                  * assign below, the unassigned fields will all become NULLs.)
5114                                  */
5115                                 if (erh == NULL)
5116                                 {
5117                                         instantiate_empty_record_variable(estate, rec);
5118                                         erh = rec->erh;
5119                                 }
5120
5121                                 /*
5122                                  * Look up the field's properties if we have not already, or
5123                                  * if the tuple descriptor ID changed since last time.
5124                                  */
5125                                 if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5126                                 {
5127                                         if (!expanded_record_lookup_field(erh,
5128                                                                                                           recfield->fieldname,
5129                                                                                                           &recfield->finfo))
5130                                                 ereport(ERROR,
5131                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5132                                                                  errmsg("record \"%s\" has no field \"%s\"",
5133                                                                                 rec->refname, recfield->fieldname)));
5134                                         recfield->rectupledescid = erh->er_tupdesc_id;
5135                                 }
5136
5137                                 /* We don't support assignments to system columns. */
5138                                 if (recfield->finfo.fnumber <= 0)
5139                                         ereport(ERROR,
5140                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5141                                                          errmsg("cannot assign to system column \"%s\"",
5142                                                                         recfield->fieldname)));
5143
5144                                 /* Cast the new value to the right type, if needed. */
5145                                 value = exec_cast_value(estate,
5146                                                                                 value,
5147                                                                                 &isNull,
5148                                                                                 valtype,
5149                                                                                 valtypmod,
5150                                                                                 recfield->finfo.ftypeid,
5151                                                                                 recfield->finfo.ftypmod);
5152
5153                                 /* And assign it. */
5154                                 expanded_record_set_field(erh, recfield->finfo.fnumber,
5155                                                                                   value, isNull, !estate->atomic);
5156                                 break;
5157                         }
5158
5159                 case PLPGSQL_DTYPE_ARRAYELEM:
5160                         {
5161                                 /*
5162                                  * Target is an element of an array
5163                                  */
5164                                 PLpgSQL_arrayelem *arrayelem;
5165                                 int                     nsubscripts;
5166                                 int                     i;
5167                                 PLpgSQL_expr *subscripts[MAXDIM];
5168                                 int                     subscriptvals[MAXDIM];
5169                                 Datum           oldarraydatum,
5170                                                         newarraydatum,
5171                                                         coerced_value;
5172                                 bool            oldarrayisnull;
5173                                 Oid                     parenttypoid;
5174                                 int32           parenttypmod;
5175                                 SPITupleTable *save_eval_tuptable;
5176                                 MemoryContext oldcontext;
5177
5178                                 /*
5179                                  * We need to do subscript evaluation, which might require
5180                                  * evaluating general expressions; and the caller might have
5181                                  * done that too in order to prepare the input Datum.  We have
5182                                  * to save and restore the caller's SPI_execute result, if
5183                                  * any.
5184                                  */
5185                                 save_eval_tuptable = estate->eval_tuptable;
5186                                 estate->eval_tuptable = NULL;
5187
5188                                 /*
5189                                  * To handle constructs like x[1][2] := something, we have to
5190                                  * be prepared to deal with a chain of arrayelem datums. Chase
5191                                  * back to find the base array datum, and save the subscript
5192                                  * expressions as we go.  (We are scanning right to left here,
5193                                  * but want to evaluate the subscripts left-to-right to
5194                                  * minimize surprises.)  Note that arrayelem is left pointing
5195                                  * to the leftmost arrayelem datum, where we will cache the
5196                                  * array element type data.
5197                                  */
5198                                 nsubscripts = 0;
5199                                 do
5200                                 {
5201                                         arrayelem = (PLpgSQL_arrayelem *) target;
5202                                         if (nsubscripts >= MAXDIM)
5203                                                 ereport(ERROR,
5204                                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5205                                                                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
5206                                                                                 nsubscripts + 1, MAXDIM)));
5207                                         subscripts[nsubscripts++] = arrayelem->subscript;
5208                                         target = estate->datums[arrayelem->arrayparentno];
5209                                 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
5210
5211                                 /* Fetch current value of array datum */
5212                                 exec_eval_datum(estate, target,
5213                                                                 &parenttypoid, &parenttypmod,
5214                                                                 &oldarraydatum, &oldarrayisnull);
5215
5216                                 /* Update cached type data if necessary */
5217                                 if (arrayelem->parenttypoid != parenttypoid ||
5218                                         arrayelem->parenttypmod != parenttypmod)
5219                                 {
5220                                         Oid                     arraytypoid;
5221                                         int32           arraytypmod = parenttypmod;
5222                                         int16           arraytyplen;
5223                                         Oid                     elemtypoid;
5224                                         int16           elemtyplen;
5225                                         bool            elemtypbyval;
5226                                         char            elemtypalign;
5227
5228                                         /* If target is domain over array, reduce to base type */
5229                                         arraytypoid = getBaseTypeAndTypmod(parenttypoid,
5230                                                                                                            &arraytypmod);
5231
5232                                         /* ... and identify the element type */
5233                                         elemtypoid = get_element_type(arraytypoid);
5234                                         if (!OidIsValid(elemtypoid))
5235                                                 ereport(ERROR,
5236                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
5237                                                                  errmsg("subscripted object is not an array")));
5238
5239                                         /* Collect needed data about the types */
5240                                         arraytyplen = get_typlen(arraytypoid);
5241
5242                                         get_typlenbyvalalign(elemtypoid,
5243                                                                                  &elemtyplen,
5244                                                                                  &elemtypbyval,
5245                                                                                  &elemtypalign);
5246
5247                                         /* Now safe to update the cached data */
5248                                         arrayelem->parenttypoid = parenttypoid;
5249                                         arrayelem->parenttypmod = parenttypmod;
5250                                         arrayelem->arraytypoid = arraytypoid;
5251                                         arrayelem->arraytypmod = arraytypmod;
5252                                         arrayelem->arraytyplen = arraytyplen;
5253                                         arrayelem->elemtypoid = elemtypoid;
5254                                         arrayelem->elemtyplen = elemtyplen;
5255                                         arrayelem->elemtypbyval = elemtypbyval;
5256                                         arrayelem->elemtypalign = elemtypalign;
5257                                 }
5258
5259                                 /*
5260                                  * Evaluate the subscripts, switch into left-to-right order.
5261                                  * Like the expression built by ExecInitSubscriptingRef(),
5262                                  * complain if any subscript is null.
5263                                  */
5264                                 for (i = 0; i < nsubscripts; i++)
5265                                 {
5266                                         bool            subisnull;
5267
5268                                         subscriptvals[i] =
5269                                                 exec_eval_integer(estate,
5270                                                                                   subscripts[nsubscripts - 1 - i],
5271                                                                                   &subisnull);
5272                                         if (subisnull)
5273                                                 ereport(ERROR,
5274                                                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5275                                                                  errmsg("array subscript in assignment must not be null")));
5276
5277                                         /*
5278                                          * Clean up in case the subscript expression wasn't
5279                                          * simple. We can't do exec_eval_cleanup, but we can do
5280                                          * this much (which is safe because the integer subscript
5281                                          * value is surely pass-by-value), and we must do it in
5282                                          * case the next subscript expression isn't simple either.
5283                                          */
5284                                         if (estate->eval_tuptable != NULL)
5285                                                 SPI_freetuptable(estate->eval_tuptable);
5286                                         estate->eval_tuptable = NULL;
5287                                 }
5288
5289                                 /* Now we can restore caller's SPI_execute result if any. */
5290                                 Assert(estate->eval_tuptable == NULL);
5291                                 estate->eval_tuptable = save_eval_tuptable;
5292
5293                                 /* Coerce source value to match array element type. */
5294                                 coerced_value = exec_cast_value(estate,
5295                                                                                                 value,
5296                                                                                                 &isNull,
5297                                                                                                 valtype,
5298                                                                                                 valtypmod,
5299                                                                                                 arrayelem->elemtypoid,
5300                                                                                                 arrayelem->arraytypmod);
5301
5302                                 /*
5303                                  * If the original array is null, cons up an empty array so
5304                                  * that the assignment can proceed; we'll end with a
5305                                  * one-element array containing just the assigned-to
5306                                  * subscript.  This only works for varlena arrays, though; for
5307                                  * fixed-length array types we skip the assignment.  We can't
5308                                  * support assignment of a null entry into a fixed-length
5309                                  * array, either, so that's a no-op too.  This is all ugly but
5310                                  * corresponds to the current behavior of execExpr*.c.
5311                                  */
5312                                 if (arrayelem->arraytyplen > 0 &&       /* fixed-length array? */
5313                                         (oldarrayisnull || isNull))
5314                                         return;
5315
5316                                 /* empty array, if any, and newarraydatum are short-lived */
5317                                 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5318
5319                                 if (oldarrayisnull)
5320                                         oldarraydatum = PointerGetDatum(construct_empty_array(arrayelem->elemtypoid));
5321
5322                                 /*
5323                                  * Build the modified array value.
5324                                  */
5325                                 newarraydatum = array_set_element(oldarraydatum,
5326                                                                                                   nsubscripts,
5327                                                                                                   subscriptvals,
5328                                                                                                   coerced_value,
5329                                                                                                   isNull,
5330                                                                                                   arrayelem->arraytyplen,
5331                                                                                                   arrayelem->elemtyplen,
5332                                                                                                   arrayelem->elemtypbyval,
5333                                                                                                   arrayelem->elemtypalign);
5334
5335                                 MemoryContextSwitchTo(oldcontext);
5336
5337                                 /*
5338                                  * Assign the new array to the base variable.  It's never NULL
5339                                  * at this point.  Note that if the target is a domain,
5340                                  * coercing the base array type back up to the domain will
5341                                  * happen within exec_assign_value.
5342                                  */
5343                                 exec_assign_value(estate, target,
5344                                                                   newarraydatum,
5345                                                                   false,
5346                                                                   arrayelem->arraytypoid,
5347                                                                   arrayelem->arraytypmod);
5348                                 break;
5349                         }
5350
5351                 default:
5352                         elog(ERROR, "unrecognized dtype: %d", target->dtype);
5353         }
5354 }
5355
5356 /*
5357  * exec_eval_datum                              Get current value of a PLpgSQL_datum
5358  *
5359  * The type oid, typmod, value in Datum format, and null flag are returned.
5360  *
5361  * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums;
5362  * that's not needed because we never pass references to such datums to SPI.
5363  *
5364  * NOTE: the returned Datum points right at the stored value in the case of
5365  * pass-by-reference datatypes.  Generally callers should take care not to
5366  * modify the stored value.  Some callers intentionally manipulate variables
5367  * referenced by R/W expanded pointers, though; it is those callers'
5368  * responsibility that the results are semantically OK.
5369  *
5370  * In some cases we have to palloc a return value, and in such cases we put
5371  * it into the estate's eval_mcontext.
5372  */
5373 static void
5374 exec_eval_datum(PLpgSQL_execstate *estate,
5375                                 PLpgSQL_datum *datum,
5376                                 Oid *typeid,
5377                                 int32 *typetypmod,
5378                                 Datum *value,
5379                                 bool *isnull)
5380 {
5381         MemoryContext oldcontext;
5382
5383         switch (datum->dtype)
5384         {
5385                 case PLPGSQL_DTYPE_PROMISE:
5386                         /* fulfill promise if needed, then handle like regular var */
5387                         plpgsql_fulfill_promise(estate, (PLpgSQL_var *) datum);
5388
5389                         /* FALL THRU */
5390
5391                 case PLPGSQL_DTYPE_VAR:
5392                         {
5393                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
5394
5395                                 *typeid = var->datatype->typoid;
5396                                 *typetypmod = var->datatype->atttypmod;
5397                                 *value = var->value;
5398                                 *isnull = var->isnull;
5399                                 break;
5400                         }
5401
5402                 case PLPGSQL_DTYPE_ROW:
5403                         {
5404                                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
5405                                 HeapTuple       tup;
5406
5407                                 /* We get here if there are multiple OUT parameters */
5408                                 if (!row->rowtupdesc)   /* should not happen */
5409                                         elog(ERROR, "row variable has no tupdesc");
5410                                 /* Make sure we have a valid type/typmod setting */
5411                                 BlessTupleDesc(row->rowtupdesc);
5412                                 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5413                                 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
5414                                 if (tup == NULL)        /* should not happen */
5415                                         elog(ERROR, "row not compatible with its own tupdesc");
5416                                 *typeid = row->rowtupdesc->tdtypeid;
5417                                 *typetypmod = row->rowtupdesc->tdtypmod;
5418                                 *value = HeapTupleGetDatum(tup);
5419                                 *isnull = false;
5420                                 MemoryContextSwitchTo(oldcontext);
5421                                 break;
5422                         }
5423
5424                 case PLPGSQL_DTYPE_REC:
5425                         {
5426                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5427
5428                                 if (rec->erh == NULL)
5429                                 {
5430                                         /* Treat uninstantiated record as a simple NULL */
5431                                         *value = (Datum) 0;
5432                                         *isnull = true;
5433                                         /* Report variable's declared type */
5434                                         *typeid = rec->rectypeid;
5435                                         *typetypmod = -1;
5436                                 }
5437                                 else
5438                                 {
5439                                         if (ExpandedRecordIsEmpty(rec->erh))
5440                                         {
5441                                                 /* Empty record is also a NULL */
5442                                                 *value = (Datum) 0;
5443                                                 *isnull = true;
5444                                         }
5445                                         else
5446                                         {
5447                                                 *value = ExpandedRecordGetDatum(rec->erh);
5448                                                 *isnull = false;
5449                                         }
5450                                         if (rec->rectypeid != RECORDOID)
5451                                         {
5452                                                 /* Report variable's declared type, if not RECORD */
5453                                                 *typeid = rec->rectypeid;
5454                                                 *typetypmod = -1;
5455                                         }
5456                                         else
5457                                         {
5458                                                 /* Report record's actual type if declared RECORD */
5459                                                 *typeid = rec->erh->er_typeid;
5460                                                 *typetypmod = rec->erh->er_typmod;
5461                                         }
5462                                 }
5463                                 break;
5464                         }
5465
5466                 case PLPGSQL_DTYPE_RECFIELD:
5467                         {
5468                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5469                                 PLpgSQL_rec *rec;
5470                                 ExpandedRecordHeader *erh;
5471
5472                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5473                                 erh = rec->erh;
5474
5475                                 /*
5476                                  * If record variable is NULL, instantiate it if it has a
5477                                  * named composite type, else complain.  (This won't change
5478                                  * the logical state of the record: it's still NULL.)
5479                                  */
5480                                 if (erh == NULL)
5481                                 {
5482                                         instantiate_empty_record_variable(estate, rec);
5483                                         erh = rec->erh;
5484                                 }
5485
5486                                 /*
5487                                  * Look up the field's properties if we have not already, or
5488                                  * if the tuple descriptor ID changed since last time.
5489                                  */
5490                                 if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5491                                 {
5492                                         if (!expanded_record_lookup_field(erh,
5493                                                                                                           recfield->fieldname,
5494                                                                                                           &recfield->finfo))
5495                                                 ereport(ERROR,
5496                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5497                                                                  errmsg("record \"%s\" has no field \"%s\"",
5498                                                                                 rec->refname, recfield->fieldname)));
5499                                         recfield->rectupledescid = erh->er_tupdesc_id;
5500                                 }
5501
5502                                 /* Report type data. */
5503                                 *typeid = recfield->finfo.ftypeid;
5504                                 *typetypmod = recfield->finfo.ftypmod;
5505
5506                                 /* And fetch the field value. */
5507                                 *value = expanded_record_get_field(erh,
5508                                                                                                    recfield->finfo.fnumber,
5509                                                                                                    isnull);
5510                                 break;
5511                         }
5512
5513                 default:
5514                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5515         }
5516 }
5517
5518 /*
5519  * plpgsql_exec_get_datum_type                          Get datatype of a PLpgSQL_datum
5520  *
5521  * This is the same logic as in exec_eval_datum, but we skip acquiring
5522  * the actual value of the variable.  Also, needn't support DTYPE_ROW.
5523  */
5524 Oid
5525 plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
5526                                                         PLpgSQL_datum *datum)
5527 {
5528         Oid                     typeid;
5529
5530         switch (datum->dtype)
5531         {
5532                 case PLPGSQL_DTYPE_VAR:
5533                 case PLPGSQL_DTYPE_PROMISE:
5534                         {
5535                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
5536
5537                                 typeid = var->datatype->typoid;
5538                                 break;
5539                         }
5540
5541                 case PLPGSQL_DTYPE_REC:
5542                         {
5543                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5544
5545                                 if (rec->erh == NULL || rec->rectypeid != RECORDOID)
5546                                 {
5547                                         /* Report variable's declared type */
5548                                         typeid = rec->rectypeid;
5549                                 }
5550                                 else
5551                                 {
5552                                         /* Report record's actual type if declared RECORD */
5553                                         typeid = rec->erh->er_typeid;
5554                                 }
5555                                 break;
5556                         }
5557
5558                 case PLPGSQL_DTYPE_RECFIELD:
5559                         {
5560                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5561                                 PLpgSQL_rec *rec;
5562
5563                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5564
5565                                 /*
5566                                  * If record variable is NULL, instantiate it if it has a
5567                                  * named composite type, else complain.  (This won't change
5568                                  * the logical state of the record: it's still NULL.)
5569                                  */
5570                                 if (rec->erh == NULL)
5571                                         instantiate_empty_record_variable(estate, rec);
5572
5573                                 /*
5574                                  * Look up the field's properties if we have not already, or
5575                                  * if the tuple descriptor ID changed since last time.
5576                                  */
5577                                 if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
5578                                 {
5579                                         if (!expanded_record_lookup_field(rec->erh,
5580                                                                                                           recfield->fieldname,
5581                                                                                                           &recfield->finfo))
5582                                                 ereport(ERROR,
5583                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5584                                                                  errmsg("record \"%s\" has no field \"%s\"",
5585                                                                                 rec->refname, recfield->fieldname)));
5586                                         recfield->rectupledescid = rec->erh->er_tupdesc_id;
5587                                 }
5588
5589                                 typeid = recfield->finfo.ftypeid;
5590                                 break;
5591                         }
5592
5593                 default:
5594                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5595                         typeid = InvalidOid;    /* keep compiler quiet */
5596                         break;
5597         }
5598
5599         return typeid;
5600 }
5601
5602 /*
5603  * plpgsql_exec_get_datum_type_info                     Get datatype etc of a PLpgSQL_datum
5604  *
5605  * An extended version of plpgsql_exec_get_datum_type, which also retrieves the
5606  * typmod and collation of the datum.  Note however that we don't report the
5607  * possibly-mutable typmod of RECORD values, but say -1 always.
5608  */
5609 void
5610 plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
5611                                                                  PLpgSQL_datum *datum,
5612                                                                  Oid *typeId, int32 *typMod, Oid *collation)
5613 {
5614         switch (datum->dtype)
5615         {
5616                 case PLPGSQL_DTYPE_VAR:
5617                 case PLPGSQL_DTYPE_PROMISE:
5618                         {
5619                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
5620
5621                                 *typeId = var->datatype->typoid;
5622                                 *typMod = var->datatype->atttypmod;
5623                                 *collation = var->datatype->collation;
5624                                 break;
5625                         }
5626
5627                 case PLPGSQL_DTYPE_REC:
5628                         {
5629                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5630
5631                                 if (rec->erh == NULL || rec->rectypeid != RECORDOID)
5632                                 {
5633                                         /* Report variable's declared type */
5634                                         *typeId = rec->rectypeid;
5635                                         *typMod = -1;
5636                                 }
5637                                 else
5638                                 {
5639                                         /* Report record's actual type if declared RECORD */
5640                                         *typeId = rec->erh->er_typeid;
5641                                         /* do NOT return the mutable typmod of a RECORD variable */
5642                                         *typMod = -1;
5643                                 }
5644                                 /* composite types are never collatable */
5645                                 *collation = InvalidOid;
5646                                 break;
5647                         }
5648
5649                 case PLPGSQL_DTYPE_RECFIELD:
5650                         {
5651                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5652                                 PLpgSQL_rec *rec;
5653
5654                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5655
5656                                 /*
5657                                  * If record variable is NULL, instantiate it if it has a
5658                                  * named composite type, else complain.  (This won't change
5659                                  * the logical state of the record: it's still NULL.)
5660                                  */
5661                                 if (rec->erh == NULL)
5662                                         instantiate_empty_record_variable(estate, rec);
5663
5664                                 /*
5665                                  * Look up the field's properties if we have not already, or
5666                                  * if the tuple descriptor ID changed since last time.
5667                                  */
5668                                 if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
5669                                 {
5670                                         if (!expanded_record_lookup_field(rec->erh,
5671                                                                                                           recfield->fieldname,
5672                                                                                                           &recfield->finfo))
5673                                                 ereport(ERROR,
5674                                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
5675                                                                  errmsg("record \"%s\" has no field \"%s\"",
5676                                                                                 rec->refname, recfield->fieldname)));
5677                                         recfield->rectupledescid = rec->erh->er_tupdesc_id;
5678                                 }
5679
5680                                 *typeId = recfield->finfo.ftypeid;
5681                                 *typMod = recfield->finfo.ftypmod;
5682                                 *collation = recfield->finfo.fcollation;
5683                                 break;
5684                         }
5685
5686                 default:
5687                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5688                         *typeId = InvalidOid;   /* keep compiler quiet */
5689                         *typMod = -1;
5690                         *collation = InvalidOid;
5691                         break;
5692         }
5693 }
5694
5695 /* ----------
5696  * exec_eval_integer            Evaluate an expression, coerce result to int4
5697  *
5698  * Note we do not do exec_eval_cleanup here; the caller must do it at
5699  * some later point.  (We do this because the caller may be holding the
5700  * results of other, pass-by-reference, expression evaluations, such as
5701  * an array value to be subscripted.)
5702  * ----------
5703  */
5704 static int
5705 exec_eval_integer(PLpgSQL_execstate *estate,
5706                                   PLpgSQL_expr *expr,
5707                                   bool *isNull)
5708 {
5709         Datum           exprdatum;
5710         Oid                     exprtypeid;
5711         int32           exprtypmod;
5712
5713         exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
5714         exprdatum = exec_cast_value(estate, exprdatum, isNull,
5715                                                                 exprtypeid, exprtypmod,
5716                                                                 INT4OID, -1);
5717         return DatumGetInt32(exprdatum);
5718 }
5719
5720 /* ----------
5721  * exec_eval_boolean            Evaluate an expression, coerce result to bool
5722  *
5723  * Note we do not do exec_eval_cleanup here; the caller must do it at
5724  * some later point.
5725  * ----------
5726  */
5727 static bool
5728 exec_eval_boolean(PLpgSQL_execstate *estate,
5729                                   PLpgSQL_expr *expr,
5730                                   bool *isNull)
5731 {
5732         Datum           exprdatum;
5733         Oid                     exprtypeid;
5734         int32           exprtypmod;
5735
5736         exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
5737         exprdatum = exec_cast_value(estate, exprdatum, isNull,
5738                                                                 exprtypeid, exprtypmod,
5739                                                                 BOOLOID, -1);
5740         return DatumGetBool(exprdatum);
5741 }
5742
5743 /* ----------
5744  * exec_eval_expr                       Evaluate an expression and return
5745  *                                      the result Datum, along with data type/typmod.
5746  *
5747  * NOTE: caller must do exec_eval_cleanup when done with the Datum.
5748  * ----------
5749  */
5750 static Datum
5751 exec_eval_expr(PLpgSQL_execstate *estate,
5752                            PLpgSQL_expr *expr,
5753                            bool *isNull,
5754                            Oid *rettype,
5755                            int32 *rettypmod)
5756 {
5757         Datum           result = 0;
5758         int                     rc;
5759         Form_pg_attribute attr;
5760
5761         /*
5762          * If first time through, create a plan for this expression.
5763          */
5764         if (expr->plan == NULL)
5765                 exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK, true);
5766
5767         /*
5768          * If this is a simple expression, bypass SPI and use the executor
5769          * directly
5770          */
5771         if (exec_eval_simple_expr(estate, expr,
5772                                                           &result, isNull, rettype, rettypmod))
5773                 return result;
5774
5775         /*
5776          * Else do it the hard way via exec_run_select
5777          */
5778         rc = exec_run_select(estate, expr, 2, NULL);
5779         if (rc != SPI_OK_SELECT)
5780                 ereport(ERROR,
5781                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5782                                  errmsg("query \"%s\" did not return data", expr->query)));
5783
5784         /*
5785          * Check that the expression returns exactly one column...
5786          */
5787         if (estate->eval_tuptable->tupdesc->natts != 1)
5788                 ereport(ERROR,
5789                                 (errcode(ERRCODE_SYNTAX_ERROR),
5790                                  errmsg_plural("query \"%s\" returned %d column",
5791                                                            "query \"%s\" returned %d columns",
5792                                                            estate->eval_tuptable->tupdesc->natts,
5793                                                            expr->query,
5794                                                            estate->eval_tuptable->tupdesc->natts)));
5795
5796         /*
5797          * ... and get the column's datatype.
5798          */
5799         attr = TupleDescAttr(estate->eval_tuptable->tupdesc, 0);
5800         *rettype = attr->atttypid;
5801         *rettypmod = attr->atttypmod;
5802
5803         /*
5804          * If there are no rows selected, the result is a NULL of that type.
5805          */
5806         if (estate->eval_processed == 0)
5807         {
5808                 *isNull = true;
5809                 return (Datum) 0;
5810         }
5811
5812         /*
5813          * Check that the expression returned no more than one row.
5814          */
5815         if (estate->eval_processed != 1)
5816                 ereport(ERROR,
5817                                 (errcode(ERRCODE_CARDINALITY_VIOLATION),
5818                                  errmsg("query \"%s\" returned more than one row",
5819                                                 expr->query)));
5820
5821         /*
5822          * Return the single result Datum.
5823          */
5824         return SPI_getbinval(estate->eval_tuptable->vals[0],
5825                                                  estate->eval_tuptable->tupdesc, 1, isNull);
5826 }
5827
5828
5829 /* ----------
5830  * exec_run_select                      Execute a select query
5831  * ----------
5832  */
5833 static int
5834 exec_run_select(PLpgSQL_execstate *estate,
5835                                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
5836 {
5837         ParamListInfo paramLI;
5838         int                     rc;
5839
5840         /*
5841          * On the first call for this expression generate the plan.
5842          *
5843          * If we don't need to return a portal, then we're just going to execute
5844          * the query once, which means it's OK to use a parallel plan, even if the
5845          * number of rows being fetched is limited.  If we do need to return a
5846          * portal, the caller might do cursor operations, which parallel query
5847          * can't support.
5848          */
5849         if (expr->plan == NULL)
5850                 exec_prepare_plan(estate, expr,
5851                                                   portalP == NULL ? CURSOR_OPT_PARALLEL_OK : 0, true);
5852
5853         /*
5854          * Set up ParamListInfo to pass to executor
5855          */
5856         paramLI = setup_param_list(estate, expr);
5857
5858         /*
5859          * If a portal was requested, put the query and paramlist into the portal
5860          */
5861         if (portalP != NULL)
5862         {
5863                 *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
5864                                                                                                   paramLI,
5865                                                                                                   estate->readonly_func);
5866                 if (*portalP == NULL)
5867                         elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5868                                  expr->query, SPI_result_code_string(SPI_result));
5869                 exec_eval_cleanup(estate);
5870                 return SPI_OK_CURSOR;
5871         }
5872
5873         /*
5874          * Execute the query
5875          */
5876         rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
5877                                                                                  estate->readonly_func, maxtuples);
5878         if (rc != SPI_OK_SELECT)
5879                 ereport(ERROR,
5880                                 (errcode(ERRCODE_SYNTAX_ERROR),
5881                                  errmsg("query \"%s\" is not a SELECT", expr->query)));
5882
5883         /* Save query results for eventual cleanup */
5884         Assert(estate->eval_tuptable == NULL);
5885         estate->eval_tuptable = SPI_tuptable;
5886         estate->eval_processed = SPI_processed;
5887
5888         return rc;
5889 }
5890
5891
5892 /*
5893  * exec_for_query --- execute body of FOR loop for each row from a portal
5894  *
5895  * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
5896  */
5897 static int
5898 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
5899                            Portal portal, bool prefetch_ok)
5900 {
5901         PLpgSQL_variable *var;
5902         SPITupleTable *tuptab;
5903         bool            found = false;
5904         int                     rc = PLPGSQL_RC_OK;
5905         uint64          previous_id = INVALID_TUPLEDESC_IDENTIFIER;
5906         bool            tupdescs_match = true;
5907         uint64          n;
5908
5909         /* Fetch loop variable's datum entry */
5910         var = (PLpgSQL_variable *) estate->datums[stmt->var->dno];
5911
5912         /*
5913          * Make sure the portal doesn't get closed by the user statements we
5914          * execute.
5915          */
5916         PinPortal(portal);
5917
5918         /*
5919          * Fetch the initial tuple(s).  If prefetching is allowed then we grab a
5920          * few more rows to avoid multiple trips through executor startup
5921          * overhead.
5922          */
5923         SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
5924         tuptab = SPI_tuptable;
5925         n = SPI_processed;
5926
5927         /*
5928          * If the query didn't return any rows, set the target to NULL and fall
5929          * through with found = false.
5930          */
5931         if (n == 0)
5932         {
5933                 exec_move_row(estate, var, NULL, tuptab->tupdesc);
5934                 exec_eval_cleanup(estate);
5935         }
5936         else
5937                 found = true;                   /* processed at least one tuple */
5938
5939         /*
5940          * Now do the loop
5941          */
5942         while (n > 0)
5943         {
5944                 uint64          i;
5945
5946                 for (i = 0; i < n; i++)
5947                 {
5948                         /*
5949                          * Assign the tuple to the target.  Here, because we know that all
5950                          * loop iterations should be assigning the same tupdesc, we can
5951                          * optimize away repeated creations of expanded records with
5952                          * identical tupdescs.  Testing for changes of er_tupdesc_id is
5953                          * reliable even if the loop body contains assignments that
5954                          * replace the target's value entirely, because it's assigned from
5955                          * a process-global counter.  The case where the tupdescs don't
5956                          * match could possibly be handled more efficiently than this
5957                          * coding does, but it's not clear extra effort is worthwhile.
5958                          */
5959                         if (var->dtype == PLPGSQL_DTYPE_REC)
5960                         {
5961                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) var;
5962
5963                                 if (rec->erh &&
5964                                         rec->erh->er_tupdesc_id == previous_id &&
5965                                         tupdescs_match)
5966                                 {
5967                                         /* Only need to assign a new tuple value */
5968                                         expanded_record_set_tuple(rec->erh, tuptab->vals[i],
5969                                                                                           true, !estate->atomic);
5970                                 }
5971                                 else
5972                                 {
5973                                         /*
5974                                          * First time through, or var's tupdesc changed in loop,
5975                                          * or we have to do it the hard way because type coercion
5976                                          * is needed.
5977                                          */
5978                                         exec_move_row(estate, var,
5979                                                                   tuptab->vals[i], tuptab->tupdesc);
5980
5981                                         /*
5982                                          * Check to see if physical assignment is OK next time.
5983                                          * Once the tupdesc comparison has failed once, we don't
5984                                          * bother rechecking in subsequent loop iterations.
5985                                          */
5986                                         if (tupdescs_match)
5987                                         {
5988                                                 tupdescs_match =
5989                                                         (rec->rectypeid == RECORDOID ||
5990                                                          rec->rectypeid == tuptab->tupdesc->tdtypeid ||
5991                                                          compatible_tupdescs(tuptab->tupdesc,
5992                                                                                                  expanded_record_get_tupdesc(rec->erh)));
5993                                         }
5994                                         previous_id = rec->erh->er_tupdesc_id;
5995                                 }
5996                         }
5997                         else
5998                                 exec_move_row(estate, var, tuptab->vals[i], tuptab->tupdesc);
5999
6000                         exec_eval_cleanup(estate);
6001
6002                         /*
6003                          * Execute the statements
6004                          */
6005                         rc = exec_stmts(estate, stmt->body);
6006
6007                         LOOP_RC_PROCESSING(stmt->label, goto loop_exit);
6008                 }
6009
6010                 SPI_freetuptable(tuptab);
6011
6012                 /*
6013                  * Fetch more tuples.  If prefetching is allowed, grab 50 at a time.
6014                  */
6015                 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
6016                 tuptab = SPI_tuptable;
6017                 n = SPI_processed;
6018         }
6019
6020 loop_exit:
6021
6022         /*
6023          * Release last group of tuples (if any)
6024          */
6025         SPI_freetuptable(tuptab);
6026
6027         UnpinPortal(portal);
6028
6029         /*
6030          * Set the FOUND variable to indicate the result of executing the loop
6031          * (namely, whether we looped one or more times). This must be set last so
6032          * that it does not interfere with the value of the FOUND variable inside
6033          * the loop processing itself.
6034          */
6035         exec_set_found(estate, found);
6036
6037         return rc;
6038 }
6039
6040
6041 /* ----------
6042  * exec_eval_simple_expr -              Evaluate a simple expression returning
6043  *                                                              a Datum by directly calling ExecEvalExpr().
6044  *
6045  * If successful, store results into *result, *isNull, *rettype, *rettypmod
6046  * and return true.  If the expression cannot be handled by simple evaluation,
6047  * return false.
6048  *
6049  * Because we only store one execution tree for a simple expression, we
6050  * can't handle recursion cases.  So, if we see the tree is already busy
6051  * with an evaluation in the current xact, we just return false and let the
6052  * caller run the expression the hard way.  (Other alternatives such as
6053  * creating a new tree for a recursive call either introduce memory leaks,
6054  * or add enough bookkeeping to be doubtful wins anyway.)  Another case that
6055  * is covered by the expr_simple_in_use test is where a previous execution
6056  * of the tree was aborted by an error: the tree may contain bogus state
6057  * so we dare not re-use it.
6058  *
6059  * It is possible that we'd need to replan a simple expression; for example,
6060  * someone might redefine a SQL function that had been inlined into the simple
6061  * expression.  That cannot cause a simple expression to become non-simple (or
6062  * vice versa), but we do have to handle replacing the expression tree.
6063  * Fortunately it's normally inexpensive to call SPI_plan_get_cached_plan for
6064  * a simple expression.
6065  *
6066  * Note: if pass-by-reference, the result is in the eval_mcontext.
6067  * It will be freed when exec_eval_cleanup is done.
6068  * ----------
6069  */
6070 static bool
6071 exec_eval_simple_expr(PLpgSQL_execstate *estate,
6072                                           PLpgSQL_expr *expr,
6073                                           Datum *result,
6074                                           bool *isNull,
6075                                           Oid *rettype,
6076                                           int32 *rettypmod)
6077 {
6078         ExprContext *econtext = estate->eval_econtext;
6079         LocalTransactionId curlxid = MyProc->lxid;
6080         CachedPlan *cplan;
6081         void       *save_setup_arg;
6082         MemoryContext oldcontext;
6083
6084         /*
6085          * Forget it if expression wasn't simple before.
6086          */
6087         if (expr->expr_simple_expr == NULL)
6088                 return false;
6089
6090         /*
6091          * If expression is in use in current xact, don't touch it.
6092          */
6093         if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
6094                 return false;
6095
6096         /*
6097          * Revalidate cached plan, so that we will notice if it became stale. (We
6098          * need to hold a refcount while using the plan, anyway.)  If replanning
6099          * is needed, do that work in the eval_mcontext.
6100          */
6101         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
6102         cplan = SPI_plan_get_cached_plan(expr->plan);
6103         MemoryContextSwitchTo(oldcontext);
6104
6105         /*
6106          * We can't get a failure here, because the number of CachedPlanSources in
6107          * the SPI plan can't change from what exec_simple_check_plan saw; it's a
6108          * property of the raw parsetree generated from the query text.
6109          */
6110         Assert(cplan != NULL);
6111
6112         /* If it got replanned, update our copy of the simple expression */
6113         if (cplan->generation != expr->expr_simple_generation)
6114         {
6115                 exec_save_simple_expr(expr, cplan);
6116                 /* better recheck r/w safety, as it could change due to inlining */
6117                 if (expr->rwparam >= 0)
6118                         exec_check_rw_parameter(expr, expr->rwparam);
6119         }
6120
6121         /*
6122          * Pass back previously-determined result type.
6123          */
6124         *rettype = expr->expr_simple_type;
6125         *rettypmod = expr->expr_simple_typmod;
6126
6127         /*
6128          * Set up ParamListInfo to pass to executor.  For safety, save and restore
6129          * estate->paramLI->parserSetupArg around our use of the param list.
6130          */
6131         save_setup_arg = estate->paramLI->parserSetupArg;
6132
6133         econtext->ecxt_param_list_info = setup_param_list(estate, expr);
6134
6135         /*
6136          * Prepare the expression for execution, if it's not been done already in
6137          * the current transaction.  (This will be forced to happen if we called
6138          * exec_save_simple_expr above.)
6139          */
6140         if (expr->expr_simple_lxid != curlxid)
6141         {
6142                 oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
6143                 expr->expr_simple_state =
6144                         ExecInitExprWithParams(expr->expr_simple_expr,
6145                                                                    econtext->ecxt_param_list_info);
6146                 expr->expr_simple_in_use = false;
6147                 expr->expr_simple_lxid = curlxid;
6148                 MemoryContextSwitchTo(oldcontext);
6149         }
6150
6151         /*
6152          * We have to do some of the things SPI_execute_plan would do, in
6153          * particular advance the snapshot if we are in a non-read-only function.
6154          * Without this, stable functions within the expression would fail to see
6155          * updates made so far by our own function.
6156          */
6157         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
6158         if (!estate->readonly_func)
6159         {
6160                 CommandCounterIncrement();
6161                 PushActiveSnapshot(GetTransactionSnapshot());
6162         }
6163
6164         /*
6165          * Mark expression as busy for the duration of the ExecEvalExpr call.
6166          */
6167         expr->expr_simple_in_use = true;
6168
6169         /*
6170          * Finally we can call the executor to evaluate the expression
6171          */
6172         *result = ExecEvalExpr(expr->expr_simple_state,
6173                                                    econtext,
6174                                                    isNull);
6175
6176         /* Assorted cleanup */
6177         expr->expr_simple_in_use = false;
6178
6179         econtext->ecxt_param_list_info = NULL;
6180
6181         estate->paramLI->parserSetupArg = save_setup_arg;
6182
6183         if (!estate->readonly_func)
6184                 PopActiveSnapshot();
6185
6186         MemoryContextSwitchTo(oldcontext);
6187
6188         /*
6189          * Now we can release our refcount on the cached plan.
6190          */
6191         ReleaseCachedPlan(cplan, true);
6192
6193         /*
6194          * That's it.
6195          */
6196         return true;
6197 }
6198
6199
6200 /*
6201  * Create a ParamListInfo to pass to SPI
6202  *
6203  * We use a single ParamListInfo struct for all SPI calls made from this
6204  * estate; it contains no per-param data, just hook functions, so it's
6205  * effectively read-only for SPI.
6206  *
6207  * An exception from pure read-only-ness is that the parserSetupArg points
6208  * to the specific PLpgSQL_expr being evaluated.  This is not an issue for
6209  * statement-level callers, but lower-level callers must save and restore
6210  * estate->paramLI->parserSetupArg just in case there's an active evaluation
6211  * at an outer call level.  (A plausible alternative design would be to
6212  * create a ParamListInfo struct for each PLpgSQL_expr, but for the moment
6213  * that seems like a waste of memory.)
6214  */
6215 static ParamListInfo
6216 setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
6217 {
6218         ParamListInfo paramLI;
6219
6220         /*
6221          * We must have created the SPIPlan already (hence, query text has been
6222          * parsed/analyzed at least once); else we cannot rely on expr->paramnos.
6223          */
6224         Assert(expr->plan != NULL);
6225
6226         /*
6227          * We only need a ParamListInfo if the expression has parameters.  In
6228          * principle we should test with bms_is_empty(), but we use a not-null
6229          * test because it's faster.  In current usage bits are never removed from
6230          * expr->paramnos, only added, so this test is correct anyway.
6231          */
6232         if (expr->paramnos)
6233         {
6234                 /* Use the common ParamListInfo */
6235                 paramLI = estate->paramLI;
6236
6237                 /*
6238                  * Set up link to active expr where the hook functions can find it.
6239                  * Callers must save and restore parserSetupArg if there is any chance
6240                  * that they are interrupting an active use of parameters.
6241                  */
6242                 paramLI->parserSetupArg = (void *) expr;
6243
6244                 /*
6245                  * Also make sure this is set before parser hooks need it.  There is
6246                  * no need to save and restore, since the value is always correct once
6247                  * set.  (Should be set already, but let's be sure.)
6248                  */
6249                 expr->func = estate->func;
6250         }
6251         else
6252         {
6253                 /*
6254                  * Expression requires no parameters.  Be sure we represent this case
6255                  * as a NULL ParamListInfo, so that plancache.c knows there is no
6256                  * point in a custom plan.
6257                  */
6258                 paramLI = NULL;
6259         }
6260         return paramLI;
6261 }
6262
6263 /*
6264  * plpgsql_param_fetch          paramFetch callback for dynamic parameter fetch
6265  *
6266  * We always use the caller's workspace to construct the returned struct.
6267  *
6268  * Note: this is no longer used during query execution.  It is used during
6269  * planning (with speculative == true) and when the ParamListInfo we supply
6270  * to the executor is copied into a cursor portal or transferred to a
6271  * parallel child process.
6272  */
6273 static ParamExternData *
6274 plpgsql_param_fetch(ParamListInfo params,
6275                                         int paramid, bool speculative,
6276                                         ParamExternData *prm)
6277 {
6278         int                     dno;
6279         PLpgSQL_execstate *estate;
6280         PLpgSQL_expr *expr;
6281         PLpgSQL_datum *datum;
6282         bool            ok = true;
6283         int32           prmtypmod;
6284
6285         /* paramid's are 1-based, but dnos are 0-based */
6286         dno = paramid - 1;
6287         Assert(dno >= 0 && dno < params->numParams);
6288
6289         /* fetch back the hook data */
6290         estate = (PLpgSQL_execstate *) params->paramFetchArg;
6291         expr = (PLpgSQL_expr *) params->parserSetupArg;
6292         Assert(params->numParams == estate->ndatums);
6293
6294         /* now we can access the target datum */
6295         datum = estate->datums[dno];
6296
6297         /*
6298          * Since copyParamList() or SerializeParamList() will try to materialize
6299          * every single parameter slot, it's important to return a dummy param
6300          * when asked for a datum that's not supposed to be used by this SQL
6301          * expression.  Otherwise we risk failures in exec_eval_datum(), or
6302          * copying a lot more data than necessary.
6303          */
6304         if (!bms_is_member(dno, expr->paramnos))
6305                 ok = false;
6306
6307         /*
6308          * If the access is speculative, we prefer to return no data rather than
6309          * to fail in exec_eval_datum().  Check the likely failure cases.
6310          */
6311         else if (speculative)
6312         {
6313                 switch (datum->dtype)
6314                 {
6315                         case PLPGSQL_DTYPE_VAR:
6316                         case PLPGSQL_DTYPE_PROMISE:
6317                                 /* always safe */
6318                                 break;
6319
6320                         case PLPGSQL_DTYPE_ROW:
6321                                 /* should be safe in all interesting cases */
6322                                 break;
6323
6324                         case PLPGSQL_DTYPE_REC:
6325                                 /* always safe (might return NULL, that's fine) */
6326                                 break;
6327
6328                         case PLPGSQL_DTYPE_RECFIELD:
6329                                 {
6330                                         PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
6331                                         PLpgSQL_rec *rec;
6332
6333                                         rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
6334
6335                                         /*
6336                                          * If record variable is NULL, don't risk anything.
6337                                          */
6338                                         if (rec->erh == NULL)
6339                                                 ok = false;
6340
6341                                         /*
6342                                          * Look up the field's properties if we have not already,
6343                                          * or if the tuple descriptor ID changed since last time.
6344                                          */
6345                                         else if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
6346                                         {
6347                                                 if (expanded_record_lookup_field(rec->erh,
6348                                                                                                                  recfield->fieldname,
6349                                                                                                                  &recfield->finfo))
6350                                                         recfield->rectupledescid = rec->erh->er_tupdesc_id;
6351                                                 else
6352                                                         ok = false;
6353                                         }
6354                                         break;
6355                                 }
6356
6357                         default:
6358                                 ok = false;
6359                                 break;
6360                 }
6361         }
6362
6363         /* Return "no such parameter" if not ok */
6364         if (!ok)
6365         {
6366                 prm->value = (Datum) 0;
6367                 prm->isnull = true;
6368                 prm->pflags = 0;
6369                 prm->ptype = InvalidOid;
6370                 return prm;
6371         }
6372
6373         /* OK, evaluate the value and store into the return struct */
6374         exec_eval_datum(estate, datum,
6375                                         &prm->ptype, &prmtypmod,
6376                                         &prm->value, &prm->isnull);
6377         /* We can always mark params as "const" for executor's purposes */
6378         prm->pflags = PARAM_FLAG_CONST;
6379
6380         /*
6381          * If it's a read/write expanded datum, convert reference to read-only,
6382          * unless it's safe to pass as read-write.
6383          */
6384         if (dno != expr->rwparam)
6385         {
6386                 if (datum->dtype == PLPGSQL_DTYPE_VAR)
6387                         prm->value = MakeExpandedObjectReadOnly(prm->value,
6388                                                                                                         prm->isnull,
6389                                                                                                         ((PLpgSQL_var *) datum)->datatype->typlen);
6390                 else if (datum->dtype == PLPGSQL_DTYPE_REC)
6391                         prm->value = MakeExpandedObjectReadOnly(prm->value,
6392                                                                                                         prm->isnull,
6393                                                                                                         -1);
6394         }
6395
6396         return prm;
6397 }
6398
6399 /*
6400  * plpgsql_param_compile                paramCompile callback for plpgsql parameters
6401  */
6402 static void
6403 plpgsql_param_compile(ParamListInfo params, Param *param,
6404                                           ExprState *state,
6405                                           Datum *resv, bool *resnull)
6406 {
6407         PLpgSQL_execstate *estate;
6408         PLpgSQL_expr *expr;
6409         int                     dno;
6410         PLpgSQL_datum *datum;
6411         ExprEvalStep scratch;
6412
6413         /* fetch back the hook data */
6414         estate = (PLpgSQL_execstate *) params->paramFetchArg;
6415         expr = (PLpgSQL_expr *) params->parserSetupArg;
6416
6417         /* paramid's are 1-based, but dnos are 0-based */
6418         dno = param->paramid - 1;
6419         Assert(dno >= 0 && dno < estate->ndatums);
6420
6421         /* now we can access the target datum */
6422         datum = estate->datums[dno];
6423
6424         scratch.opcode = EEOP_PARAM_CALLBACK;
6425         scratch.resvalue = resv;
6426         scratch.resnull = resnull;
6427
6428         /*
6429          * Select appropriate eval function.  It seems worth special-casing
6430          * DTYPE_VAR and DTYPE_RECFIELD for performance.  Also, we can determine
6431          * in advance whether MakeExpandedObjectReadOnly() will be required.
6432          * Currently, only VAR/PROMISE and REC datums could contain read/write
6433          * expanded objects.
6434          */
6435         if (datum->dtype == PLPGSQL_DTYPE_VAR)
6436         {
6437                 if (dno != expr->rwparam &&
6438                         ((PLpgSQL_var *) datum)->datatype->typlen == -1)
6439                         scratch.d.cparam.paramfunc = plpgsql_param_eval_var_ro;
6440                 else
6441                         scratch.d.cparam.paramfunc = plpgsql_param_eval_var;
6442         }
6443         else if (datum->dtype == PLPGSQL_DTYPE_RECFIELD)
6444                 scratch.d.cparam.paramfunc = plpgsql_param_eval_recfield;
6445         else if (datum->dtype == PLPGSQL_DTYPE_PROMISE)
6446         {
6447                 if (dno != expr->rwparam &&
6448                         ((PLpgSQL_var *) datum)->datatype->typlen == -1)
6449                         scratch.d.cparam.paramfunc = plpgsql_param_eval_generic_ro;
6450                 else
6451                         scratch.d.cparam.paramfunc = plpgsql_param_eval_generic;
6452         }
6453         else if (datum->dtype == PLPGSQL_DTYPE_REC &&
6454                          dno != expr->rwparam)
6455                 scratch.d.cparam.paramfunc = plpgsql_param_eval_generic_ro;
6456         else
6457                 scratch.d.cparam.paramfunc = plpgsql_param_eval_generic;
6458
6459         /*
6460          * Note: it's tempting to use paramarg to store the estate pointer and
6461          * thereby save an indirection or two in the eval functions.  But that
6462          * doesn't work because the compiled expression might be used with
6463          * different estates for the same PL/pgSQL function.
6464          */
6465         scratch.d.cparam.paramarg = NULL;
6466         scratch.d.cparam.paramid = param->paramid;
6467         scratch.d.cparam.paramtype = param->paramtype;
6468         ExprEvalPushStep(state, &scratch);
6469 }
6470
6471 /*
6472  * plpgsql_param_eval_var               evaluation of EEOP_PARAM_CALLBACK step
6473  *
6474  * This is specialized to the case of DTYPE_VAR variables for which
6475  * we do not need to invoke MakeExpandedObjectReadOnly.
6476  */
6477 static void
6478 plpgsql_param_eval_var(ExprState *state, ExprEvalStep *op,
6479                                            ExprContext *econtext)
6480 {
6481         ParamListInfo params;
6482         PLpgSQL_execstate *estate;
6483         int                     dno = op->d.cparam.paramid - 1;
6484         PLpgSQL_var *var;
6485
6486         /* fetch back the hook data */
6487         params = econtext->ecxt_param_list_info;
6488         estate = (PLpgSQL_execstate *) params->paramFetchArg;
6489         Assert(dno >= 0 && dno < estate->ndatums);
6490
6491         /* now we can access the target datum */
6492         var = (PLpgSQL_var *) estate->datums[dno];
6493         Assert(var->dtype == PLPGSQL_DTYPE_VAR);
6494
6495         /* inlined version of exec_eval_datum() */
6496         *op->resvalue = var->value;
6497         *op->resnull = var->isnull;
6498
6499         /* safety check -- an assertion should be sufficient */
6500         Assert(var->datatype->typoid == op->d.cparam.paramtype);
6501 }
6502
6503 /*
6504  * plpgsql_param_eval_var_ro            evaluation of EEOP_PARAM_CALLBACK step
6505  *
6506  * This is specialized to the case of DTYPE_VAR variables for which
6507  * we need to invoke MakeExpandedObjectReadOnly.
6508  */
6509 static void
6510 plpgsql_param_eval_var_ro(ExprState *state, ExprEvalStep *op,
6511                                                   ExprContext *econtext)
6512 {
6513         ParamListInfo params;
6514         PLpgSQL_execstate *estate;
6515         int                     dno = op->d.cparam.paramid - 1;
6516         PLpgSQL_var *var;
6517
6518         /* fetch back the hook data */
6519         params = econtext->ecxt_param_list_info;
6520         estate = (PLpgSQL_execstate *) params->paramFetchArg;
6521         Assert(dno >= 0 && dno < estate->ndatums);
6522
6523         /* now we can access the target datum */
6524         var = (PLpgSQL_var *) estate->datums[dno];
6525         Assert(var->dtype == PLPGSQL_DTYPE_VAR);
6526
6527         /*
6528          * Inlined version of exec_eval_datum() ... and while we're at it, force
6529          * expanded datums to read-only.
6530          */
6531         *op->resvalue = MakeExpandedObjectReadOnly(var->value,
6532                                                                                            var->isnull,
6533                                                                                            -1);
6534         *op->resnull = var->isnull;
6535
6536         /* safety check -- an assertion should be sufficient */
6537         Assert(var->datatype->typoid == op->d.cparam.paramtype);
6538 }
6539
6540 /*
6541  * plpgsql_param_eval_recfield          evaluation of EEOP_PARAM_CALLBACK step
6542  *
6543  * This is specialized to the case of DTYPE_RECFIELD variables, for which
6544  * we never need to invoke MakeExpandedObjectReadOnly.
6545  */
6546 static void
6547 plpgsql_param_eval_recfield(ExprState *state, ExprEvalStep *op,
6548                                                         ExprContext *econtext)
6549 {
6550         ParamListInfo params;
6551         PLpgSQL_execstate *estate;
6552         int                     dno = op->d.cparam.paramid - 1;
6553         PLpgSQL_recfield *recfield;
6554         PLpgSQL_rec *rec;
6555         ExpandedRecordHeader *erh;
6556
6557         /* fetch back the hook data */
6558         params = econtext->ecxt_param_list_info;
6559         estate = (PLpgSQL_execstate *) params->paramFetchArg;
6560         Assert(dno >= 0 && dno < estate->ndatums);
6561
6562         /* now we can access the target datum */
6563         recfield = (PLpgSQL_recfield *) estate->datums[dno];
6564         Assert(recfield->dtype == PLPGSQL_DTYPE_RECFIELD);
6565
6566         /* inline the relevant part of exec_eval_datum */
6567         rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
6568         erh = rec->erh;
6569
6570         /*
6571          * If record variable is NULL, instantiate it if it has a named composite
6572          * type, else complain.  (This won't change the logical state of the
6573          * record: it's still NULL.)
6574          */
6575         if (erh == NULL)
6576         {
6577                 instantiate_empty_record_variable(estate, rec);
6578                 erh = rec->erh;
6579         }
6580
6581         /*
6582          * Look up the field's properties if we have not already, or if the tuple
6583          * descriptor ID changed since last time.
6584          */
6585         if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
6586         {
6587                 if (!expanded_record_lookup_field(erh,
6588                                                                                   recfield->fieldname,
6589                                                                                   &recfield->finfo))
6590                         ereport(ERROR,
6591                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
6592                                          errmsg("record \"%s\" has no field \"%s\"",
6593                                                         rec->refname, recfield->fieldname)));
6594                 recfield->rectupledescid = erh->er_tupdesc_id;
6595         }
6596
6597         /* OK to fetch the field value. */
6598         *op->resvalue = expanded_record_get_field(erh,
6599                                                                                           recfield->finfo.fnumber,
6600                                                                                           op->resnull);
6601
6602         /* safety check -- needed for, eg, record fields */
6603         if (unlikely(recfield->finfo.ftypeid != op->d.cparam.paramtype))
6604                 ereport(ERROR,
6605                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
6606                                  errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
6607                                                 op->d.cparam.paramid,
6608                                                 format_type_be(recfield->finfo.ftypeid),
6609                                                 format_type_be(op->d.cparam.paramtype))));
6610 }
6611
6612 /*
6613  * plpgsql_param_eval_generic           evaluation of EEOP_PARAM_CALLBACK step
6614  *
6615  * This handles all variable types, but assumes we do not need to invoke
6616  * MakeExpandedObjectReadOnly.
6617  */
6618 static void
6619 plpgsql_param_eval_generic(ExprState *state, ExprEvalStep *op,
6620                                                    ExprContext *econtext)
6621 {
6622         ParamListInfo params;
6623         PLpgSQL_execstate *estate;
6624         int                     dno = op->d.cparam.paramid - 1;
6625         PLpgSQL_datum *datum;
6626         Oid                     datumtype;
6627         int32           datumtypmod;
6628
6629         /* fetch back the hook data */
6630         params = econtext->ecxt_param_list_info;
6631         estate = (PLpgSQL_execstate *) params->paramFetchArg;
6632         Assert(dno >= 0 && dno < estate->ndatums);
6633
6634         /* now we can access the target datum */
6635         datum = estate->datums[dno];
6636
6637         /* fetch datum's value */
6638         exec_eval_datum(estate, datum,
6639                                         &datumtype, &datumtypmod,
6640                                         op->resvalue, op->resnull);
6641
6642         /* safety check -- needed for, eg, record fields */
6643         if (unlikely(datumtype != op->d.cparam.paramtype))
6644                 ereport(ERROR,
6645                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
6646                                  errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
6647                                                 op->d.cparam.paramid,
6648                                                 format_type_be(datumtype),
6649                                                 format_type_be(op->d.cparam.paramtype))));
6650 }
6651
6652 /*
6653  * plpgsql_param_eval_generic_ro        evaluation of EEOP_PARAM_CALLBACK step
6654  *
6655  * This handles all variable types, but assumes we need to invoke
6656  * MakeExpandedObjectReadOnly (hence, variable must be of a varlena type).
6657  */
6658 static void
6659 plpgsql_param_eval_generic_ro(ExprState *state, ExprEvalStep *op,
6660                                                           ExprContext *econtext)
6661 {
6662         ParamListInfo params;
6663         PLpgSQL_execstate *estate;
6664         int                     dno = op->d.cparam.paramid - 1;
6665         PLpgSQL_datum *datum;
6666         Oid                     datumtype;
6667         int32           datumtypmod;
6668
6669         /* fetch back the hook data */
6670         params = econtext->ecxt_param_list_info;
6671         estate = (PLpgSQL_execstate *) params->paramFetchArg;
6672         Assert(dno >= 0 && dno < estate->ndatums);
6673
6674         /* now we can access the target datum */
6675         datum = estate->datums[dno];
6676
6677         /* fetch datum's value */
6678         exec_eval_datum(estate, datum,
6679                                         &datumtype, &datumtypmod,
6680                                         op->resvalue, op->resnull);
6681
6682         /* safety check -- needed for, eg, record fields */
6683         if (unlikely(datumtype != op->d.cparam.paramtype))
6684                 ereport(ERROR,
6685                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
6686                                  errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
6687                                                 op->d.cparam.paramid,
6688                                                 format_type_be(datumtype),
6689                                                 format_type_be(op->d.cparam.paramtype))));
6690
6691         /* force the value to read-only */
6692         *op->resvalue = MakeExpandedObjectReadOnly(*op->resvalue,
6693                                                                                            *op->resnull,
6694                                                                                            -1);
6695 }
6696
6697
6698 /*
6699  * exec_move_row                        Move one tuple's values into a record or row
6700  *
6701  * tup and tupdesc may both be NULL if we're just assigning an indeterminate
6702  * composite NULL to the target.  Alternatively, can have tup be NULL and
6703  * tupdesc not NULL, in which case we assign a row of NULLs to the target.
6704  *
6705  * Since this uses the mcontext for workspace, caller should eventually call
6706  * exec_eval_cleanup to prevent long-term memory leaks.
6707  */
6708 static void
6709 exec_move_row(PLpgSQL_execstate *estate,
6710                           PLpgSQL_variable *target,
6711                           HeapTuple tup, TupleDesc tupdesc)
6712 {
6713         ExpandedRecordHeader *newerh = NULL;
6714
6715         /*
6716          * If target is RECORD, we may be able to avoid field-by-field processing.
6717          */
6718         if (target->dtype == PLPGSQL_DTYPE_REC)
6719         {
6720                 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
6721
6722                 /*
6723                  * If we have no source tupdesc, just set the record variable to NULL.
6724                  * (If we have a source tupdesc but not a tuple, we'll set the
6725                  * variable to a row of nulls, instead.  This is odd perhaps, but
6726                  * backwards compatible.)
6727                  */
6728                 if (tupdesc == NULL)
6729                 {
6730                         if (rec->datatype &&
6731                                 rec->datatype->typtype == TYPTYPE_DOMAIN)
6732                         {
6733                                 /*
6734                                  * If it's a composite domain, NULL might not be a legal
6735                                  * value, so we instead need to make an empty expanded record
6736                                  * and ensure that domain type checking gets done.  If there
6737                                  * is already an expanded record, piggyback on its lookups.
6738                                  */
6739                                 newerh = make_expanded_record_for_rec(estate, rec,
6740                                                                                                           NULL, rec->erh);
6741                                 expanded_record_set_tuple(newerh, NULL, false, false);
6742                                 assign_record_var(estate, rec, newerh);
6743                         }
6744                         else
6745                         {
6746                                 /* Just clear it to NULL */
6747                                 if (rec->erh)
6748                                         DeleteExpandedObject(ExpandedRecordGetDatum(rec->erh));
6749                                 rec->erh = NULL;
6750                         }
6751                         return;
6752                 }
6753
6754                 /*
6755                  * Build a new expanded record with appropriate tupdesc.
6756                  */
6757                 newerh = make_expanded_record_for_rec(estate, rec, tupdesc, NULL);
6758
6759                 /*
6760                  * If the rowtypes match, or if we have no tuple anyway, we can
6761                  * complete the assignment without field-by-field processing.
6762                  *
6763                  * The tests here are ordered more or less in order of cheapness.  We
6764                  * can easily detect it will work if the target is declared RECORD or
6765                  * has the same typeid as the source.  But when assigning from a query
6766                  * result, it's common to have a source tupdesc that's labeled RECORD
6767                  * but is actually physically compatible with a named-composite-type
6768                  * target, so it's worth spending extra cycles to check for that.
6769                  */
6770                 if (rec->rectypeid == RECORDOID ||
6771                         rec->rectypeid == tupdesc->tdtypeid ||
6772                         !HeapTupleIsValid(tup) ||
6773                         compatible_tupdescs(tupdesc, expanded_record_get_tupdesc(newerh)))
6774                 {
6775                         if (!HeapTupleIsValid(tup))
6776                         {
6777                                 /* No data, so force the record into all-nulls state */
6778                                 deconstruct_expanded_record(newerh);
6779                         }
6780                         else
6781                         {
6782                                 /* No coercion is needed, so just assign the row value */
6783                                 expanded_record_set_tuple(newerh, tup, true, !estate->atomic);
6784                         }
6785
6786                         /* Complete the assignment */
6787                         assign_record_var(estate, rec, newerh);
6788
6789                         return;
6790                 }
6791         }
6792
6793         /*
6794          * Otherwise, deconstruct the tuple and do field-by-field assignment,
6795          * using exec_move_row_from_fields.
6796          */
6797         if (tupdesc && HeapTupleIsValid(tup))
6798         {
6799                 int                     td_natts = tupdesc->natts;
6800                 Datum      *values;
6801                 bool       *nulls;
6802                 Datum           values_local[64];
6803                 bool            nulls_local[64];
6804
6805                 /*
6806                  * Need workspace arrays.  If td_natts is small enough, use local
6807                  * arrays to save doing a palloc.  Even if it's not small, we can
6808                  * allocate both the Datum and isnull arrays in one palloc chunk.
6809                  */
6810                 if (td_natts <= lengthof(values_local))
6811                 {
6812                         values = values_local;
6813                         nulls = nulls_local;
6814                 }
6815                 else
6816                 {
6817                         char       *chunk;
6818
6819                         chunk = eval_mcontext_alloc(estate,
6820                                                                                 td_natts * (sizeof(Datum) + sizeof(bool)));
6821                         values = (Datum *) chunk;
6822                         nulls = (bool *) (chunk + td_natts * sizeof(Datum));
6823                 }
6824
6825                 heap_deform_tuple(tup, tupdesc, values, nulls);
6826
6827                 exec_move_row_from_fields(estate, target, newerh,
6828                                                                   values, nulls, tupdesc);
6829         }
6830         else
6831         {
6832                 /*
6833                  * Assign all-nulls.
6834                  */
6835                 exec_move_row_from_fields(estate, target, newerh,
6836                                                                   NULL, NULL, NULL);
6837         }
6838 }
6839
6840 /*
6841  * Verify that a PLpgSQL_rec's rectypeid is up-to-date.
6842  */
6843 static void
6844 revalidate_rectypeid(PLpgSQL_rec *rec)
6845 {
6846         PLpgSQL_type *typ = rec->datatype;
6847         TypeCacheEntry *typentry;
6848
6849         if (rec->rectypeid == RECORDOID)
6850                 return;                                 /* it's RECORD, so nothing to do */
6851         Assert(typ != NULL);
6852         if (typ->tcache &&
6853                 typ->tcache->tupDesc_identifier == typ->tupdesc_id)
6854                 return;                                 /* known up-to-date */
6855
6856         /*
6857          * typcache entry has suffered invalidation, so re-look-up the type name
6858          * if possible, and then recheck the type OID.  If we don't have a
6859          * TypeName, then we just have to soldier on with the OID we've got.
6860          */
6861         if (typ->origtypname != NULL)
6862         {
6863                 /* this bit should match parse_datatype() in pl_gram.y */
6864                 typenameTypeIdAndMod(NULL, typ->origtypname,
6865                                                          &typ->typoid,
6866                                                          &typ->atttypmod);
6867         }
6868
6869         /* this bit should match build_datatype() in pl_comp.c */
6870         typentry = lookup_type_cache(typ->typoid,
6871                                                                  TYPECACHE_TUPDESC |
6872                                                                  TYPECACHE_DOMAIN_BASE_INFO);
6873         if (typentry->typtype == TYPTYPE_DOMAIN)
6874                 typentry = lookup_type_cache(typentry->domainBaseType,
6875                                                                          TYPECACHE_TUPDESC);
6876         if (typentry->tupDesc == NULL)
6877         {
6878                 /*
6879                  * If we get here, user tried to replace a composite type with a
6880                  * non-composite one.  We're not gonna support that.
6881                  */
6882                 ereport(ERROR,
6883                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6884                                  errmsg("type %s is not composite",
6885                                                 format_type_be(typ->typoid))));
6886         }
6887
6888         /*
6889          * Update tcache and tupdesc_id.  Since we don't support changing to a
6890          * non-composite type, none of the rest of *typ needs to change.
6891          */
6892         typ->tcache = typentry;
6893         typ->tupdesc_id = typentry->tupDesc_identifier;
6894
6895         /*
6896          * Update *rec, too.  (We'll deal with subsidiary RECFIELDs as needed.)
6897          */
6898         rec->rectypeid = typ->typoid;
6899 }
6900
6901 /*
6902  * Build an expanded record object suitable for assignment to "rec".
6903  *
6904  * Caller must supply either a source tuple descriptor or a source expanded
6905  * record (not both).  If the record variable has declared type RECORD,
6906  * it'll adopt the source's rowtype.  Even if it doesn't, we may be able to
6907  * piggyback on a source expanded record to save a typcache lookup.
6908  *
6909  * Caller must fill the object with data, then do assign_record_var().
6910  *
6911  * The new record is initially put into the mcontext, so it will be cleaned up
6912  * if we fail before reaching assign_record_var().
6913  */
6914 static ExpandedRecordHeader *
6915 make_expanded_record_for_rec(PLpgSQL_execstate *estate,
6916                                                          PLpgSQL_rec *rec,
6917                                                          TupleDesc srctupdesc,
6918                                                          ExpandedRecordHeader *srcerh)
6919 {
6920         ExpandedRecordHeader *newerh;
6921         MemoryContext mcontext = get_eval_mcontext(estate);
6922
6923         if (rec->rectypeid != RECORDOID)
6924         {
6925                 /*
6926                  * Make sure rec->rectypeid is up-to-date before using it.
6927                  */
6928                 revalidate_rectypeid(rec);
6929
6930                 /*
6931                  * New record must be of desired type, but maybe srcerh has already
6932                  * done all the same lookups.
6933                  */
6934                 if (srcerh && rec->rectypeid == srcerh->er_decltypeid)
6935                         newerh = make_expanded_record_from_exprecord(srcerh,
6936                                                                                                                  mcontext);
6937                 else
6938                         newerh = make_expanded_record_from_typeid(rec->rectypeid, -1,
6939                                                                                                           mcontext);
6940         }
6941         else
6942         {
6943                 /*
6944                  * We'll adopt the input tupdesc.  We can still use
6945                  * make_expanded_record_from_exprecord, if srcerh isn't a composite
6946                  * domain.  (If it is, we effectively adopt its base type.)
6947                  */
6948                 if (srcerh && !ExpandedRecordIsDomain(srcerh))
6949                         newerh = make_expanded_record_from_exprecord(srcerh,
6950                                                                                                                  mcontext);
6951                 else
6952                 {
6953                         if (!srctupdesc)
6954                                 srctupdesc = expanded_record_get_tupdesc(srcerh);
6955                         newerh = make_expanded_record_from_tupdesc(srctupdesc,
6956                                                                                                            mcontext);
6957                 }
6958         }
6959
6960         return newerh;
6961 }
6962
6963 /*
6964  * exec_move_row_from_fields    Move arrays of field values into a record or row
6965  *
6966  * When assigning to a record, the caller must have already created a suitable
6967  * new expanded record object, newerh.  Pass NULL when assigning to a row.
6968  *
6969  * tupdesc describes the input row, which might have different column
6970  * types and/or different dropped-column positions than the target.
6971  * values/nulls/tupdesc can all be NULL if we just want to assign nulls to
6972  * all fields of the record or row.
6973  *
6974  * Since this uses the mcontext for workspace, caller should eventually call
6975  * exec_eval_cleanup to prevent long-term memory leaks.
6976  */
6977 static void
6978 exec_move_row_from_fields(PLpgSQL_execstate *estate,
6979                                                   PLpgSQL_variable *target,
6980                                                   ExpandedRecordHeader *newerh,
6981                                                   Datum *values, bool *nulls,
6982                                                   TupleDesc tupdesc)
6983 {
6984         int                     td_natts = tupdesc ? tupdesc->natts : 0;
6985         int                     fnum;
6986         int                     anum;
6987         int                     strict_multiassignment_level = 0;
6988
6989         /*
6990          * The extra check strict strict_multi_assignment can be active, only when
6991          * input tupdesc is specified.
6992          */
6993         if (tupdesc != NULL)
6994         {
6995                 if (plpgsql_extra_errors & PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT)
6996                         strict_multiassignment_level = ERROR;
6997                 else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT)
6998                         strict_multiassignment_level = WARNING;
6999         }
7000
7001         /* Handle RECORD-target case */
7002         if (target->dtype == PLPGSQL_DTYPE_REC)
7003         {
7004                 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7005                 TupleDesc       var_tupdesc;
7006                 Datum           newvalues_local[64];
7007                 bool            newnulls_local[64];
7008
7009                 Assert(newerh != NULL); /* caller must have built new object */
7010
7011                 var_tupdesc = expanded_record_get_tupdesc(newerh);
7012
7013                 /*
7014                  * Coerce field values if needed.  This might involve dealing with
7015                  * different sets of dropped columns and/or coercing individual column
7016                  * types.  That's sort of a pain, but historically plpgsql has allowed
7017                  * it, so we preserve the behavior.  However, it's worth a quick check
7018                  * to see if the tupdescs are identical.  (Since expandedrecord.c
7019                  * prefers to use refcounted tupdescs from the typcache, expanded
7020                  * records with the same rowtype will have pointer-equal tupdescs.)
7021                  */
7022                 if (var_tupdesc != tupdesc)
7023                 {
7024                         int                     vtd_natts = var_tupdesc->natts;
7025                         Datum      *newvalues;
7026                         bool       *newnulls;
7027
7028                         /*
7029                          * Need workspace arrays.  If vtd_natts is small enough, use local
7030                          * arrays to save doing a palloc.  Even if it's not small, we can
7031                          * allocate both the Datum and isnull arrays in one palloc chunk.
7032                          */
7033                         if (vtd_natts <= lengthof(newvalues_local))
7034                         {
7035                                 newvalues = newvalues_local;
7036                                 newnulls = newnulls_local;
7037                         }
7038                         else
7039                         {
7040                                 char       *chunk;
7041
7042                                 chunk = eval_mcontext_alloc(estate,
7043                                                                                         vtd_natts * (sizeof(Datum) + sizeof(bool)));
7044                                 newvalues = (Datum *) chunk;
7045                                 newnulls = (bool *) (chunk + vtd_natts * sizeof(Datum));
7046                         }
7047
7048                         /* Walk over destination columns */
7049                         anum = 0;
7050                         for (fnum = 0; fnum < vtd_natts; fnum++)
7051                         {
7052                                 Form_pg_attribute attr = TupleDescAttr(var_tupdesc, fnum);
7053                                 Datum           value;
7054                                 bool            isnull;
7055                                 Oid                     valtype;
7056                                 int32           valtypmod;
7057
7058                                 if (attr->attisdropped)
7059                                 {
7060                                         /* expanded_record_set_fields should ignore this column */
7061                                         continue;       /* skip dropped column in record */
7062                                 }
7063
7064                                 while (anum < td_natts &&
7065                                            TupleDescAttr(tupdesc, anum)->attisdropped)
7066                                         anum++;         /* skip dropped column in tuple */
7067
7068                                 if (anum < td_natts)
7069                                 {
7070                                         value = values[anum];
7071                                         isnull = nulls[anum];
7072                                         valtype = TupleDescAttr(tupdesc, anum)->atttypid;
7073                                         valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
7074                                         anum++;
7075                                 }
7076                                 else
7077                                 {
7078                                         /* no source for destination column */
7079                                         value = (Datum) 0;
7080                                         isnull = true;
7081                                         valtype = UNKNOWNOID;
7082                                         valtypmod = -1;
7083
7084                                         /* When source value is missing */
7085                                         if (strict_multiassignment_level)
7086                                                 ereport(strict_multiassignment_level,
7087                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
7088                                                                  errmsg("number of source and target fields in assignment does not match"),
7089                                                 /* translator: %s represents a name of an extra check */
7090                                                                  errdetail("%s check of %s is active.",
7091                                                                                    "strict_multi_assignment",
7092                                                                                    strict_multiassignment_level == ERROR ? "extra_errors" :
7093                                                                                    "extra_warnings"),
7094                                                                  errhint("Make sure the query returns the exact list of columns.")));
7095                                 }
7096
7097                                 /* Cast the new value to the right type, if needed. */
7098                                 newvalues[fnum] = exec_cast_value(estate,
7099                                                                                                   value,
7100                                                                                                   &isnull,
7101                                                                                                   valtype,
7102                                                                                                   valtypmod,
7103                                                                                                   attr->atttypid,
7104                                                                                                   attr->atttypmod);
7105                                 newnulls[fnum] = isnull;
7106                         }
7107
7108                         /*
7109                          * When strict_multiassignment extra check is active, then ensure
7110                          * there are no unassigned source attributes.
7111                          */
7112                         if (strict_multiassignment_level && anum < td_natts)
7113                         {
7114                                 /* skip dropped columns in the source descriptor */
7115                                 while (anum < td_natts &&
7116                                            TupleDescAttr(tupdesc, anum)->attisdropped)
7117                                         anum++;
7118
7119                                 if (anum < td_natts)
7120                                         ereport(strict_multiassignment_level,
7121                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
7122                                                          errmsg("number of source and target fields in assignment does not match"),
7123                                         /* translator: %s represents a name of an extra check */
7124                                                          errdetail("%s check of %s is active.",
7125                                                                            "strict_multi_assignment",
7126                                                                            strict_multiassignment_level == ERROR ? "extra_errors" :
7127                                                                            "extra_warnings"),
7128                                                          errhint("Make sure the query returns the exact list of columns.")));
7129                         }
7130
7131                         values = newvalues;
7132                         nulls = newnulls;
7133                 }
7134
7135                 /* Insert the coerced field values into the new expanded record */
7136                 expanded_record_set_fields(newerh, values, nulls, !estate->atomic);
7137
7138                 /* Complete the assignment */
7139                 assign_record_var(estate, rec, newerh);
7140
7141                 return;
7142         }
7143
7144         /* newerh should not have been passed in non-RECORD cases */
7145         Assert(newerh == NULL);
7146
7147         /*
7148          * For a row, we assign the individual field values to the variables the
7149          * row points to.
7150          *
7151          * NOTE: both this code and the record code above silently ignore extra
7152          * columns in the source and assume NULL for missing columns.  This is
7153          * pretty dubious but it's the historical behavior.
7154          *
7155          * If we have no input data at all, we'll assign NULL to all columns of
7156          * the row variable.
7157          */
7158         if (target->dtype == PLPGSQL_DTYPE_ROW)
7159         {
7160                 PLpgSQL_row *row = (PLpgSQL_row *) target;
7161
7162                 anum = 0;
7163                 for (fnum = 0; fnum < row->nfields; fnum++)
7164                 {
7165                         PLpgSQL_var *var;
7166                         Datum           value;
7167                         bool            isnull;
7168                         Oid                     valtype;
7169                         int32           valtypmod;
7170
7171                         var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
7172
7173                         while (anum < td_natts &&
7174                                    TupleDescAttr(tupdesc, anum)->attisdropped)
7175                                 anum++;                 /* skip dropped column in tuple */
7176
7177                         if (anum < td_natts)
7178                         {
7179                                 value = values[anum];
7180                                 isnull = nulls[anum];
7181                                 valtype = TupleDescAttr(tupdesc, anum)->atttypid;
7182                                 valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
7183                                 anum++;
7184                         }
7185                         else
7186                         {
7187                                 /* no source for destination column */
7188                                 value = (Datum) 0;
7189                                 isnull = true;
7190                                 valtype = UNKNOWNOID;
7191                                 valtypmod = -1;
7192
7193                                 if (strict_multiassignment_level)
7194                                         ereport(strict_multiassignment_level,
7195                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
7196                                                          errmsg("number of source and target fields in assignment does not match"),
7197                                         /* translator: %s represents a name of an extra check */
7198                                                          errdetail("%s check of %s is active.",
7199                                                                            "strict_multi_assignment",
7200                                                                            strict_multiassignment_level == ERROR ? "extra_errors" :
7201                                                                            "extra_warnings"),
7202                                                          errhint("Make sure the query returns the exact list of columns.")));
7203                         }
7204
7205                         exec_assign_value(estate, (PLpgSQL_datum *) var,
7206                                                           value, isnull, valtype, valtypmod);
7207                 }
7208
7209                 /*
7210                  * When strict_multiassignment extra check is active, ensure there are
7211                  * no unassigned source attributes.
7212                  */
7213                 if (strict_multiassignment_level && anum < td_natts)
7214                 {
7215                         while (anum < td_natts &&
7216                                    TupleDescAttr(tupdesc, anum)->attisdropped)
7217                                 anum++;                 /* skip dropped column in tuple */
7218
7219                         if (anum < td_natts)
7220                                 ereport(strict_multiassignment_level,
7221                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
7222                                                  errmsg("number of source and target fields in assignment does not match"),
7223                                 /* translator: %s represents a name of an extra check */
7224                                                  errdetail("%s check of %s is active.",
7225                                                                    "strict_multi_assignment",
7226                                                                    strict_multiassignment_level == ERROR ? "extra_errors" :
7227                                                                    "extra_warnings"),
7228                                                  errhint("Make sure the query returns the exact list of columns.")));
7229                 }
7230
7231                 return;
7232         }
7233
7234         elog(ERROR, "unsupported target type: %d", target->dtype);
7235 }
7236
7237 /*
7238  * compatible_tupdescs: detect whether two tupdescs are physically compatible
7239  *
7240  * TRUE indicates that a tuple satisfying src_tupdesc can be used directly as
7241  * a value for a composite variable using dst_tupdesc.
7242  */
7243 static bool
7244 compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc)
7245 {
7246         int                     i;
7247
7248         /* Possibly we could allow src_tupdesc to have extra columns? */
7249         if (dst_tupdesc->natts != src_tupdesc->natts)
7250                 return false;
7251
7252         for (i = 0; i < dst_tupdesc->natts; i++)
7253         {
7254                 Form_pg_attribute dattr = TupleDescAttr(dst_tupdesc, i);
7255                 Form_pg_attribute sattr = TupleDescAttr(src_tupdesc, i);
7256
7257                 if (dattr->attisdropped != sattr->attisdropped)
7258                         return false;
7259                 if (!dattr->attisdropped)
7260                 {
7261                         /* Normal columns must match by type and typmod */
7262                         if (dattr->atttypid != sattr->atttypid ||
7263                                 (dattr->atttypmod >= 0 &&
7264                                  dattr->atttypmod != sattr->atttypmod))
7265                                 return false;
7266                 }
7267                 else
7268                 {
7269                         /* Dropped columns are OK as long as length/alignment match */
7270                         if (dattr->attlen != sattr->attlen ||
7271                                 dattr->attalign != sattr->attalign)
7272                                 return false;
7273                 }
7274         }
7275         return true;
7276 }
7277
7278 /* ----------
7279  * make_tuple_from_row          Make a tuple from the values of a row object
7280  *
7281  * A NULL return indicates rowtype mismatch; caller must raise suitable error
7282  *
7283  * The result tuple is freshly palloc'd in caller's context.  Some junk
7284  * may be left behind in eval_mcontext, too.
7285  * ----------
7286  */
7287 static HeapTuple
7288 make_tuple_from_row(PLpgSQL_execstate *estate,
7289                                         PLpgSQL_row *row,
7290                                         TupleDesc tupdesc)
7291 {
7292         int                     natts = tupdesc->natts;
7293         HeapTuple       tuple;
7294         Datum      *dvalues;
7295         bool       *nulls;
7296         int                     i;
7297
7298         if (natts != row->nfields)
7299                 return NULL;
7300
7301         dvalues = (Datum *) eval_mcontext_alloc0(estate, natts * sizeof(Datum));
7302         nulls = (bool *) eval_mcontext_alloc(estate, natts * sizeof(bool));
7303
7304         for (i = 0; i < natts; i++)
7305         {
7306                 Oid                     fieldtypeid;
7307                 int32           fieldtypmod;
7308
7309                 if (TupleDescAttr(tupdesc, i)->attisdropped)
7310                 {
7311                         nulls[i] = true;        /* leave the column as null */
7312                         continue;
7313                 }
7314
7315                 exec_eval_datum(estate, estate->datums[row->varnos[i]],
7316                                                 &fieldtypeid, &fieldtypmod,
7317                                                 &dvalues[i], &nulls[i]);
7318                 if (fieldtypeid != TupleDescAttr(tupdesc, i)->atttypid)
7319                         return NULL;
7320                 /* XXX should we insist on typmod match, too? */
7321         }
7322
7323         tuple = heap_form_tuple(tupdesc, dvalues, nulls);
7324
7325         return tuple;
7326 }
7327
7328 /*
7329  * deconstruct_composite_datum          extract tuple+tupdesc from composite Datum
7330  *
7331  * The caller must supply a HeapTupleData variable, in which we set up a
7332  * tuple header pointing to the composite datum's body.  To make the tuple
7333  * value outlive that variable, caller would need to apply heap_copytuple...
7334  * but current callers only need a short-lived tuple value anyway.
7335  *
7336  * Returns a pointer to the TupleDesc of the datum's rowtype.
7337  * Caller is responsible for calling ReleaseTupleDesc when done with it.
7338  *
7339  * Note: it's caller's responsibility to be sure value is of composite type.
7340  * Also, best to call this in a short-lived context, as it might leak memory.
7341  */
7342 static TupleDesc
7343 deconstruct_composite_datum(Datum value, HeapTupleData *tmptup)
7344 {
7345         HeapTupleHeader td;
7346         Oid                     tupType;
7347         int32           tupTypmod;
7348
7349         /* Get tuple body (note this could involve detoasting) */
7350         td = DatumGetHeapTupleHeader(value);
7351
7352         /* Build a temporary HeapTuple control structure */
7353         tmptup->t_len = HeapTupleHeaderGetDatumLength(td);
7354         ItemPointerSetInvalid(&(tmptup->t_self));
7355         tmptup->t_tableOid = InvalidOid;
7356         tmptup->t_data = td;
7357
7358         /* Extract rowtype info and find a tupdesc */
7359         tupType = HeapTupleHeaderGetTypeId(td);
7360         tupTypmod = HeapTupleHeaderGetTypMod(td);
7361         return lookup_rowtype_tupdesc(tupType, tupTypmod);
7362 }
7363
7364 /*
7365  * exec_move_row_from_datum             Move a composite Datum into a record or row
7366  *
7367  * This is equivalent to deconstruct_composite_datum() followed by
7368  * exec_move_row(), but we can optimize things if the Datum is an
7369  * expanded-record reference.
7370  *
7371  * Note: it's caller's responsibility to be sure value is of composite type.
7372  */
7373 static void
7374 exec_move_row_from_datum(PLpgSQL_execstate *estate,
7375                                                  PLpgSQL_variable *target,
7376                                                  Datum value)
7377 {
7378         /* Check to see if source is an expanded record */
7379         if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(value)))
7380         {
7381                 ExpandedRecordHeader *erh = (ExpandedRecordHeader *) DatumGetEOHP(value);
7382                 ExpandedRecordHeader *newerh = NULL;
7383
7384                 Assert(erh->er_magic == ER_MAGIC);
7385
7386                 /* These cases apply if the target is record not row... */
7387                 if (target->dtype == PLPGSQL_DTYPE_REC)
7388                 {
7389                         PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7390
7391                         /*
7392                          * If it's the same record already stored in the variable, do
7393                          * nothing.  This would happen only in silly cases like "r := r",
7394                          * but we need some check to avoid possibly freeing the variable's
7395                          * live value below.  Note that this applies even if what we have
7396                          * is a R/O pointer.
7397                          */
7398                         if (erh == rec->erh)
7399                                 return;
7400
7401                         /*
7402                          * Make sure rec->rectypeid is up-to-date before using it.
7403                          */
7404                         revalidate_rectypeid(rec);
7405
7406                         /*
7407                          * If we have a R/W pointer, we're allowed to just commandeer
7408                          * ownership of the expanded record.  If it's of the right type to
7409                          * put into the record variable, do that.  (Note we don't accept
7410                          * an expanded record of a composite-domain type as a RECORD
7411                          * value.  We'll treat it as the base composite type instead;
7412                          * compare logic in make_expanded_record_for_rec.)
7413                          */
7414                         if (VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(value)) &&
7415                                 (rec->rectypeid == erh->er_decltypeid ||
7416                                  (rec->rectypeid == RECORDOID &&
7417                                   !ExpandedRecordIsDomain(erh))))
7418                         {
7419                                 assign_record_var(estate, rec, erh);
7420                                 return;
7421                         }
7422
7423                         /*
7424                          * If we already have an expanded record object in the target
7425                          * variable, and the source record contains a valid tuple
7426                          * representation with the right rowtype, then we can skip making
7427                          * a new expanded record and just assign the tuple with
7428                          * expanded_record_set_tuple.  (We can't do the equivalent if we
7429                          * have to do field-by-field assignment, since that wouldn't be
7430                          * atomic if there's an error.)  We consider that there's a
7431                          * rowtype match only if it's the same named composite type or
7432                          * same registered rowtype; checking for matches of anonymous
7433                          * rowtypes would be more expensive than this is worth.
7434                          */
7435                         if (rec->erh &&
7436                                 (erh->flags & ER_FLAG_FVALUE_VALID) &&
7437                                 erh->er_typeid == rec->erh->er_typeid &&
7438                                 (erh->er_typeid != RECORDOID ||
7439                                  (erh->er_typmod == rec->erh->er_typmod &&
7440                                   erh->er_typmod >= 0)))
7441                         {
7442                                 expanded_record_set_tuple(rec->erh, erh->fvalue,
7443                                                                                   true, !estate->atomic);
7444                                 return;
7445                         }
7446
7447                         /*
7448                          * Otherwise we're gonna need a new expanded record object.  Make
7449                          * it here in hopes of piggybacking on the source object's
7450                          * previous typcache lookup.
7451                          */
7452                         newerh = make_expanded_record_for_rec(estate, rec, NULL, erh);
7453
7454                         /*
7455                          * If the expanded record contains a valid tuple representation,
7456                          * and we don't need rowtype conversion, then just copying the
7457                          * tuple is probably faster than field-by-field processing.  (This
7458                          * isn't duplicative of the previous check, since here we will
7459                          * catch the case where the record variable was previously empty.)
7460                          */
7461                         if ((erh->flags & ER_FLAG_FVALUE_VALID) &&
7462                                 (rec->rectypeid == RECORDOID ||
7463                                  rec->rectypeid == erh->er_typeid))
7464                         {
7465                                 expanded_record_set_tuple(newerh, erh->fvalue,
7466                                                                                   true, !estate->atomic);
7467                                 assign_record_var(estate, rec, newerh);
7468                                 return;
7469                         }
7470
7471                         /*
7472                          * Need to special-case empty source record, else code below would
7473                          * leak newerh.
7474                          */
7475                         if (ExpandedRecordIsEmpty(erh))
7476                         {
7477                                 /* Set newerh to a row of NULLs */
7478                                 deconstruct_expanded_record(newerh);
7479                                 assign_record_var(estate, rec, newerh);
7480                                 return;
7481                         }
7482                 }                                               /* end of record-target-only cases */
7483
7484                 /*
7485                  * If the source expanded record is empty, we should treat that like a
7486                  * NULL tuple value.  (We're unlikely to see such a case, but we must
7487                  * check this; deconstruct_expanded_record would cause a change of
7488                  * logical state, which is not OK.)
7489                  */
7490                 if (ExpandedRecordIsEmpty(erh))
7491                 {
7492                         exec_move_row(estate, target, NULL,
7493                                                   expanded_record_get_tupdesc(erh));
7494                         return;
7495                 }
7496
7497                 /*
7498                  * Otherwise, ensure that the source record is deconstructed, and
7499                  * assign from its field values.
7500                  */
7501                 deconstruct_expanded_record(erh);
7502                 exec_move_row_from_fields(estate, target, newerh,
7503                                                                   erh->dvalues, erh->dnulls,
7504                                                                   expanded_record_get_tupdesc(erh));
7505         }
7506         else
7507         {
7508                 /*
7509                  * Nope, we've got a plain composite Datum.  Deconstruct it; but we
7510                  * don't use deconstruct_composite_datum(), because we may be able to
7511                  * skip calling lookup_rowtype_tupdesc().
7512                  */
7513                 HeapTupleHeader td;
7514                 HeapTupleData tmptup;
7515                 Oid                     tupType;
7516                 int32           tupTypmod;
7517                 TupleDesc       tupdesc;
7518                 MemoryContext oldcontext;
7519
7520                 /* Ensure that any detoasted data winds up in the eval_mcontext */
7521                 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7522                 /* Get tuple body (note this could involve detoasting) */
7523                 td = DatumGetHeapTupleHeader(value);
7524                 MemoryContextSwitchTo(oldcontext);
7525
7526                 /* Build a temporary HeapTuple control structure */
7527                 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
7528                 ItemPointerSetInvalid(&(tmptup.t_self));
7529                 tmptup.t_tableOid = InvalidOid;
7530                 tmptup.t_data = td;
7531
7532                 /* Extract rowtype info */
7533                 tupType = HeapTupleHeaderGetTypeId(td);
7534                 tupTypmod = HeapTupleHeaderGetTypMod(td);
7535
7536                 /* Now, if the target is record not row, maybe we can optimize ... */
7537                 if (target->dtype == PLPGSQL_DTYPE_REC)
7538                 {
7539                         PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7540
7541                         /*
7542                          * If we already have an expanded record object in the target
7543                          * variable, and the source datum has a matching rowtype, then we
7544                          * can skip making a new expanded record and just assign the tuple
7545                          * with expanded_record_set_tuple.  We consider that there's a
7546                          * rowtype match only if it's the same named composite type or
7547                          * same registered rowtype.  (Checking to reject an anonymous
7548                          * rowtype here should be redundant, but let's be safe.)
7549                          */
7550                         if (rec->erh &&
7551                                 tupType == rec->erh->er_typeid &&
7552                                 (tupType != RECORDOID ||
7553                                  (tupTypmod == rec->erh->er_typmod &&
7554                                   tupTypmod >= 0)))
7555                         {
7556                                 expanded_record_set_tuple(rec->erh, &tmptup,
7557                                                                                   true, !estate->atomic);
7558                                 return;
7559                         }
7560
7561                         /*
7562                          * If the source datum has a rowtype compatible with the target
7563                          * variable, just build a new expanded record and assign the tuple
7564                          * into it.  Using make_expanded_record_from_typeid() here saves
7565                          * one typcache lookup compared to the code below.
7566                          */
7567                         if (rec->rectypeid == RECORDOID || rec->rectypeid == tupType)
7568                         {
7569                                 ExpandedRecordHeader *newerh;
7570                                 MemoryContext mcontext = get_eval_mcontext(estate);
7571
7572                                 newerh = make_expanded_record_from_typeid(tupType, tupTypmod,
7573                                                                                                                   mcontext);
7574                                 expanded_record_set_tuple(newerh, &tmptup,
7575                                                                                   true, !estate->atomic);
7576                                 assign_record_var(estate, rec, newerh);
7577                                 return;
7578                         }
7579
7580                         /*
7581                          * Otherwise, we're going to need conversion, so fall through to
7582                          * do it the hard way.
7583                          */
7584                 }
7585
7586                 /*
7587                  * ROW target, or unoptimizable RECORD target, so we have to expend a
7588                  * lookup to obtain the source datum's tupdesc.
7589                  */
7590                 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
7591
7592                 /* Do the move */
7593                 exec_move_row(estate, target, &tmptup, tupdesc);
7594
7595                 /* Release tupdesc usage count */
7596                 ReleaseTupleDesc(tupdesc);
7597         }
7598 }
7599
7600 /*
7601  * If we have not created an expanded record to hold the record variable's
7602  * value, do so.  The expanded record will be "empty", so this does not
7603  * change the logical state of the record variable: it's still NULL.
7604  * However, now we'll have a tupdesc with which we can e.g. look up fields.
7605  */
7606 static void
7607 instantiate_empty_record_variable(PLpgSQL_execstate *estate, PLpgSQL_rec *rec)
7608 {
7609         Assert(rec->erh == NULL);       /* else caller error */
7610
7611         /* If declared type is RECORD, we can't instantiate */
7612         if (rec->rectypeid == RECORDOID)
7613                 ereport(ERROR,
7614                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7615                                  errmsg("record \"%s\" is not assigned yet", rec->refname),
7616                                  errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
7617
7618         /* Make sure rec->rectypeid is up-to-date before using it */
7619         revalidate_rectypeid(rec);
7620
7621         /* OK, do it */
7622         rec->erh = make_expanded_record_from_typeid(rec->rectypeid, -1,
7623                                                                                                 estate->datum_context);
7624 }
7625
7626 /* ----------
7627  * convert_value_to_string                      Convert a non-null Datum to C string
7628  *
7629  * Note: the result is in the estate's eval_mcontext, and will be cleared
7630  * by the next exec_eval_cleanup() call.  The invoked output function might
7631  * leave additional cruft there as well, so just pfree'ing the result string
7632  * would not be enough to avoid memory leaks if we did not do it like this.
7633  * In most usages the Datum being passed in is also in that context (if
7634  * pass-by-reference) and so an exec_eval_cleanup() call is needed anyway.
7635  *
7636  * Note: not caching the conversion function lookup is bad for performance.
7637  * However, this function isn't currently used in any places where an extra
7638  * catalog lookup or two seems like a big deal.
7639  * ----------
7640  */
7641 static char *
7642 convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
7643 {
7644         char       *result;
7645         MemoryContext oldcontext;
7646         Oid                     typoutput;
7647         bool            typIsVarlena;
7648
7649         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7650         getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
7651         result = OidOutputFunctionCall(typoutput, value);
7652         MemoryContextSwitchTo(oldcontext);
7653
7654         return result;
7655 }
7656
7657 /* ----------
7658  * exec_cast_value                      Cast a value if required
7659  *
7660  * Note that *isnull is an input and also an output parameter.  While it's
7661  * unlikely that a cast operation would produce null from non-null or vice
7662  * versa, that could happen in principle.
7663  *
7664  * Note: the estate's eval_mcontext is used for temporary storage, and may
7665  * also contain the result Datum if we have to do a conversion to a pass-
7666  * by-reference data type.  Be sure to do an exec_eval_cleanup() call when
7667  * done with the result.
7668  * ----------
7669  */
7670 static Datum
7671 exec_cast_value(PLpgSQL_execstate *estate,
7672                                 Datum value, bool *isnull,
7673                                 Oid valtype, int32 valtypmod,
7674                                 Oid reqtype, int32 reqtypmod)
7675 {
7676         /*
7677          * If the type of the given value isn't what's requested, convert it.
7678          */
7679         if (valtype != reqtype ||
7680                 (valtypmod != reqtypmod && reqtypmod != -1))
7681         {
7682                 plpgsql_CastHashEntry *cast_entry;
7683
7684                 cast_entry = get_cast_hashentry(estate,
7685                                                                                 valtype, valtypmod,
7686                                                                                 reqtype, reqtypmod);
7687                 if (cast_entry)
7688                 {
7689                         ExprContext *econtext = estate->eval_econtext;
7690                         MemoryContext oldcontext;
7691
7692                         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7693
7694                         econtext->caseValue_datum = value;
7695                         econtext->caseValue_isNull = *isnull;
7696
7697                         cast_entry->cast_in_use = true;
7698
7699                         value = ExecEvalExpr(cast_entry->cast_exprstate, econtext,
7700                                                                  isnull);
7701
7702                         cast_entry->cast_in_use = false;
7703
7704                         MemoryContextSwitchTo(oldcontext);
7705                 }
7706         }
7707
7708         return value;
7709 }
7710
7711 /* ----------
7712  * get_cast_hashentry                   Look up how to perform a type cast
7713  *
7714  * Returns a plpgsql_CastHashEntry if an expression has to be evaluated,
7715  * or NULL if the cast is a mere no-op relabeling.  If there's work to be
7716  * done, the cast_exprstate field contains an expression evaluation tree
7717  * based on a CaseTestExpr input, and the cast_in_use field should be set
7718  * true while executing it.
7719  * ----------
7720  */
7721 static plpgsql_CastHashEntry *
7722 get_cast_hashentry(PLpgSQL_execstate *estate,
7723                                    Oid srctype, int32 srctypmod,
7724                                    Oid dsttype, int32 dsttypmod)
7725 {
7726         plpgsql_CastHashKey cast_key;
7727         plpgsql_CastHashEntry *cast_entry;
7728         bool            found;
7729         LocalTransactionId curlxid;
7730         MemoryContext oldcontext;
7731
7732         /* Look for existing entry */
7733         cast_key.srctype = srctype;
7734         cast_key.dsttype = dsttype;
7735         cast_key.srctypmod = srctypmod;
7736         cast_key.dsttypmod = dsttypmod;
7737         cast_entry = (plpgsql_CastHashEntry *) hash_search(estate->cast_hash,
7738                                                                                                            (void *) &cast_key,
7739                                                                                                            HASH_ENTER, &found);
7740         if (!found)                                     /* initialize if new entry */
7741                 cast_entry->cast_cexpr = NULL;
7742
7743         if (cast_entry->cast_cexpr == NULL ||
7744                 !cast_entry->cast_cexpr->is_valid)
7745         {
7746                 /*
7747                  * We've not looked up this coercion before, or we have but the cached
7748                  * expression has been invalidated.
7749                  */
7750                 Node       *cast_expr;
7751                 CachedExpression *cast_cexpr;
7752                 CaseTestExpr *placeholder;
7753
7754                 /*
7755                  * Drop old cached expression if there is one.
7756                  */
7757                 if (cast_entry->cast_cexpr)
7758                 {
7759                         FreeCachedExpression(cast_entry->cast_cexpr);
7760                         cast_entry->cast_cexpr = NULL;
7761                 }
7762
7763                 /*
7764                  * Since we could easily fail (no such coercion), construct a
7765                  * temporary coercion expression tree in the short-lived
7766                  * eval_mcontext, then if successful save it as a CachedExpression.
7767                  */
7768                 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7769
7770                 /*
7771                  * We use a CaseTestExpr as the base of the coercion tree, since it's
7772                  * very cheap to insert the source value for that.
7773                  */
7774                 placeholder = makeNode(CaseTestExpr);
7775                 placeholder->typeId = srctype;
7776                 placeholder->typeMod = srctypmod;
7777                 placeholder->collation = get_typcollation(srctype);
7778
7779                 /*
7780                  * Apply coercion.  We use ASSIGNMENT coercion because that's the
7781                  * closest match to plpgsql's historical behavior; in particular,
7782                  * EXPLICIT coercion would allow silent truncation to a destination
7783                  * varchar/bpchar's length, which we do not want.
7784                  *
7785                  * If source type is UNKNOWN, coerce_to_target_type will fail (it only
7786                  * expects to see that for Const input nodes), so don't call it; we'll
7787                  * apply CoerceViaIO instead.  Likewise, it doesn't currently work for
7788                  * coercing RECORD to some other type, so skip for that too.
7789                  */
7790                 if (srctype == UNKNOWNOID || srctype == RECORDOID)
7791                         cast_expr = NULL;
7792                 else
7793                         cast_expr = coerce_to_target_type(NULL,
7794                                                                                           (Node *) placeholder, srctype,
7795                                                                                           dsttype, dsttypmod,
7796                                                                                           COERCION_ASSIGNMENT,
7797                                                                                           COERCE_IMPLICIT_CAST,
7798                                                                                           -1);
7799
7800                 /*
7801                  * If there's no cast path according to the parser, fall back to using
7802                  * an I/O coercion; this is semantically dubious but matches plpgsql's
7803                  * historical behavior.  We would need something of the sort for
7804                  * UNKNOWN literals in any case.
7805                  */
7806                 if (cast_expr == NULL)
7807                 {
7808                         CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
7809
7810                         iocoerce->arg = (Expr *) placeholder;
7811                         iocoerce->resulttype = dsttype;
7812                         iocoerce->resultcollid = InvalidOid;
7813                         iocoerce->coerceformat = COERCE_IMPLICIT_CAST;
7814                         iocoerce->location = -1;
7815                         cast_expr = (Node *) iocoerce;
7816                         if (dsttypmod != -1)
7817                                 cast_expr = coerce_to_target_type(NULL,
7818                                                                                                   cast_expr, dsttype,
7819                                                                                                   dsttype, dsttypmod,
7820                                                                                                   COERCION_ASSIGNMENT,
7821                                                                                                   COERCE_IMPLICIT_CAST,
7822                                                                                                   -1);
7823                 }
7824
7825                 /* Note: we don't bother labeling the expression tree with collation */
7826
7827                 /* Plan the expression and build a CachedExpression */
7828                 cast_cexpr = GetCachedExpression(cast_expr);
7829                 cast_expr = cast_cexpr->expr;
7830
7831                 /* Detect whether we have a no-op (RelabelType) coercion */
7832                 if (IsA(cast_expr, RelabelType) &&
7833                         ((RelabelType *) cast_expr)->arg == (Expr *) placeholder)
7834                         cast_expr = NULL;
7835
7836                 /* Now we can fill in the hashtable entry. */
7837                 cast_entry->cast_cexpr = cast_cexpr;
7838                 cast_entry->cast_expr = (Expr *) cast_expr;
7839                 cast_entry->cast_exprstate = NULL;
7840                 cast_entry->cast_in_use = false;
7841                 cast_entry->cast_lxid = InvalidLocalTransactionId;
7842
7843                 MemoryContextSwitchTo(oldcontext);
7844         }
7845
7846         /* Done if we have determined that this is a no-op cast. */
7847         if (cast_entry->cast_expr == NULL)
7848                 return NULL;
7849
7850         /*
7851          * Prepare the expression for execution, if it's not been done already in
7852          * the current transaction; also, if it's marked busy in the current
7853          * transaction, abandon that expression tree and build a new one, so as to
7854          * avoid potential problems with recursive cast expressions and failed
7855          * executions.  (We will leak some memory intra-transaction if that
7856          * happens a lot, but we don't expect it to.)  It's okay to update the
7857          * hash table with the new tree because all plpgsql functions within a
7858          * given transaction share the same simple_eval_estate.  (Well, regular
7859          * functions do; DO blocks have private simple_eval_estates, and private
7860          * cast hash tables to go with them.)
7861          */
7862         curlxid = MyProc->lxid;
7863         if (cast_entry->cast_lxid != curlxid || cast_entry->cast_in_use)
7864         {
7865                 oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
7866                 cast_entry->cast_exprstate = ExecInitExpr(cast_entry->cast_expr, NULL);
7867                 cast_entry->cast_in_use = false;
7868                 cast_entry->cast_lxid = curlxid;
7869                 MemoryContextSwitchTo(oldcontext);
7870         }
7871
7872         return cast_entry;
7873 }
7874
7875
7876 /* ----------
7877  * exec_simple_check_plan -             Check if a plan is simple enough to
7878  *                                                              be evaluated by ExecEvalExpr() instead
7879  *                                                              of SPI.
7880  * ----------
7881  */
7882 static void
7883 exec_simple_check_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
7884 {
7885         List       *plansources;
7886         CachedPlanSource *plansource;
7887         Query      *query;
7888         CachedPlan *cplan;
7889         MemoryContext oldcontext;
7890
7891         /*
7892          * Initialize to "not simple".
7893          */
7894         expr->expr_simple_expr = NULL;
7895
7896         /*
7897          * Check the analyzed-and-rewritten form of the query to see if we will be
7898          * able to treat it as a simple expression.  Since this function is only
7899          * called immediately after creating the CachedPlanSource, we need not
7900          * worry about the query being stale.
7901          */
7902
7903         /*
7904          * We can only test queries that resulted in exactly one CachedPlanSource
7905          */
7906         plansources = SPI_plan_get_plan_sources(expr->plan);
7907         if (list_length(plansources) != 1)
7908                 return;
7909         plansource = (CachedPlanSource *) linitial(plansources);
7910
7911         /*
7912          * 1. There must be one single querytree.
7913          */
7914         if (list_length(plansource->query_list) != 1)
7915                 return;
7916         query = (Query *) linitial(plansource->query_list);
7917
7918         /*
7919          * 2. It must be a plain SELECT query without any input tables
7920          */
7921         if (!IsA(query, Query))
7922                 return;
7923         if (query->commandType != CMD_SELECT)
7924                 return;
7925         if (query->rtable != NIL)
7926                 return;
7927
7928         /*
7929          * 3. Can't have any subplans, aggregates, qual clauses either.  (These
7930          * tests should generally match what inline_function() checks before
7931          * inlining a SQL function; otherwise, inlining could change our
7932          * conclusion about whether an expression is simple, which we don't want.)
7933          */
7934         if (query->hasAggs ||
7935                 query->hasWindowFuncs ||
7936                 query->hasTargetSRFs ||
7937                 query->hasSubLinks ||
7938                 query->cteList ||
7939                 query->jointree->fromlist ||
7940                 query->jointree->quals ||
7941                 query->groupClause ||
7942                 query->groupingSets ||
7943                 query->havingQual ||
7944                 query->windowClause ||
7945                 query->distinctClause ||
7946                 query->sortClause ||
7947                 query->limitOffset ||
7948                 query->limitCount ||
7949                 query->setOperations)
7950                 return;
7951
7952         /*
7953          * 4. The query must have a single attribute as result
7954          */
7955         if (list_length(query->targetList) != 1)
7956                 return;
7957
7958         /*
7959          * OK, we can treat it as a simple plan.
7960          *
7961          * Get the generic plan for the query.  If replanning is needed, do that
7962          * work in the eval_mcontext.
7963          */
7964         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7965         cplan = SPI_plan_get_cached_plan(expr->plan);
7966         MemoryContextSwitchTo(oldcontext);
7967
7968         /* Can't fail, because we checked for a single CachedPlanSource above */
7969         Assert(cplan != NULL);
7970
7971         /* Share the remaining work with replan code path */
7972         exec_save_simple_expr(expr, cplan);
7973
7974         /* Release our plan refcount */
7975         ReleaseCachedPlan(cplan, true);
7976 }
7977
7978 /*
7979  * exec_save_simple_expr --- extract simple expression from CachedPlan
7980  */
7981 static void
7982 exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan)
7983 {
7984         PlannedStmt *stmt;
7985         Plan       *plan;
7986         Expr       *tle_expr;
7987
7988         /*
7989          * Given the checks that exec_simple_check_plan did, none of the Asserts
7990          * here should ever fail.
7991          */
7992
7993         /* Extract the single PlannedStmt */
7994         Assert(list_length(cplan->stmt_list) == 1);
7995         stmt = linitial_node(PlannedStmt, cplan->stmt_list);
7996         Assert(stmt->commandType == CMD_SELECT);
7997
7998         /*
7999          * Ordinarily, the plan node should be a simple Result.  However, if
8000          * force_parallel_mode is on, the planner might've stuck a Gather node
8001          * atop that.  The simplest way to deal with this is to look through the
8002          * Gather node.  The Gather node's tlist would normally contain a Var
8003          * referencing the child node's output, but it could also be a Param, or
8004          * it could be a Const that setrefs.c copied as-is.
8005          */
8006         plan = stmt->planTree;
8007         for (;;)
8008         {
8009                 /* Extract the single tlist expression */
8010                 Assert(list_length(plan->targetlist) == 1);
8011                 tle_expr = castNode(TargetEntry, linitial(plan->targetlist))->expr;
8012
8013                 if (IsA(plan, Result))
8014                 {
8015                         Assert(plan->lefttree == NULL &&
8016                                    plan->righttree == NULL &&
8017                                    plan->initPlan == NULL &&
8018                                    plan->qual == NULL &&
8019                                    ((Result *) plan)->resconstantqual == NULL);
8020                         break;
8021                 }
8022                 else if (IsA(plan, Gather))
8023                 {
8024                         Assert(plan->lefttree != NULL &&
8025                                    plan->righttree == NULL &&
8026                                    plan->initPlan == NULL &&
8027                                    plan->qual == NULL);
8028                         /* If setrefs.c copied up a Const, no need to look further */
8029                         if (IsA(tle_expr, Const))
8030                                 break;
8031                         /* Otherwise, it had better be a Param or an outer Var */
8032                         Assert(IsA(tle_expr, Param) ||(IsA(tle_expr, Var) &&
8033                                                                                    ((Var *) tle_expr)->varno == OUTER_VAR));
8034                         /* Descend to the child node */
8035                         plan = plan->lefttree;
8036                 }
8037                 else
8038                         elog(ERROR, "unexpected plan node type: %d",
8039                                  (int) nodeTag(plan));
8040         }
8041
8042         /*
8043          * Save the simple expression, and initialize state to "not valid in
8044          * current transaction".
8045          */
8046         expr->expr_simple_expr = tle_expr;
8047         expr->expr_simple_generation = cplan->generation;
8048         expr->expr_simple_state = NULL;
8049         expr->expr_simple_in_use = false;
8050         expr->expr_simple_lxid = InvalidLocalTransactionId;
8051         /* Also stash away the expression result type */
8052         expr->expr_simple_type = exprType((Node *) tle_expr);
8053         expr->expr_simple_typmod = exprTypmod((Node *) tle_expr);
8054 }
8055
8056 /*
8057  * exec_check_rw_parameter --- can we pass expanded object as read/write param?
8058  *
8059  * If we have an assignment like "x := array_append(x, foo)" in which the
8060  * top-level function is trusted not to corrupt its argument in case of an
8061  * error, then when x has an expanded object as value, it is safe to pass the
8062  * value as a read/write pointer and let the function modify the value
8063  * in-place.
8064  *
8065  * This function checks for a safe expression, and sets expr->rwparam to the
8066  * dno of the target variable (x) if safe, or -1 if not safe.
8067  */
8068 static void
8069 exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno)
8070 {
8071         Oid                     funcid;
8072         List       *fargs;
8073         ListCell   *lc;
8074
8075         /* Assume unsafe */
8076         expr->rwparam = -1;
8077
8078         /*
8079          * If the expression isn't simple, there's no point in trying to optimize
8080          * (because the exec_run_select code path will flatten any expanded result
8081          * anyway).  Even without that, this seems like a good safety restriction.
8082          */
8083         if (expr->expr_simple_expr == NULL)
8084                 return;
8085
8086         /*
8087          * If target variable isn't referenced by expression, no need to look
8088          * further.
8089          */
8090         if (!bms_is_member(target_dno, expr->paramnos))
8091                 return;
8092
8093         /*
8094          * Top level of expression must be a simple FuncExpr or OpExpr.
8095          */
8096         if (IsA(expr->expr_simple_expr, FuncExpr))
8097         {
8098                 FuncExpr   *fexpr = (FuncExpr *) expr->expr_simple_expr;
8099
8100                 funcid = fexpr->funcid;
8101                 fargs = fexpr->args;
8102         }
8103         else if (IsA(expr->expr_simple_expr, OpExpr))
8104         {
8105                 OpExpr     *opexpr = (OpExpr *) expr->expr_simple_expr;
8106
8107                 funcid = opexpr->opfuncid;
8108                 fargs = opexpr->args;
8109         }
8110         else
8111                 return;
8112
8113         /*
8114          * The top-level function must be one that we trust to be "safe".
8115          * Currently we hard-wire the list, but it would be very desirable to
8116          * allow extensions to mark their functions as safe ...
8117          */
8118         if (!(funcid == F_ARRAY_APPEND ||
8119                   funcid == F_ARRAY_PREPEND))
8120                 return;
8121
8122         /*
8123          * The target variable (in the form of a Param) must only appear as a
8124          * direct argument of the top-level function.
8125          */
8126         foreach(lc, fargs)
8127         {
8128                 Node       *arg = (Node *) lfirst(lc);
8129
8130                 /* A Param is OK, whether it's the target variable or not */
8131                 if (arg && IsA(arg, Param))
8132                         continue;
8133                 /* Otherwise, argument expression must not reference target */
8134                 if (contains_target_param(arg, &target_dno))
8135                         return;
8136         }
8137
8138         /* OK, we can pass target as a read-write parameter */
8139         expr->rwparam = target_dno;
8140 }
8141
8142 /*
8143  * Recursively check for a Param referencing the target variable
8144  */
8145 static bool
8146 contains_target_param(Node *node, int *target_dno)
8147 {
8148         if (node == NULL)
8149                 return false;
8150         if (IsA(node, Param))
8151         {
8152                 Param      *param = (Param *) node;
8153
8154                 if (param->paramkind == PARAM_EXTERN &&
8155                         param->paramid == *target_dno + 1)
8156                         return true;
8157                 return false;
8158         }
8159         return expression_tree_walker(node, contains_target_param,
8160                                                                   (void *) target_dno);
8161 }
8162
8163 /* ----------
8164  * exec_set_found                       Set the global found variable to true/false
8165  * ----------
8166  */
8167 static void
8168 exec_set_found(PLpgSQL_execstate *estate, bool state)
8169 {
8170         PLpgSQL_var *var;
8171
8172         var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
8173         assign_simple_var(estate, var, BoolGetDatum(state), false, false);
8174 }
8175
8176 /*
8177  * plpgsql_create_econtext --- create an eval_econtext for the current function
8178  *
8179  * We may need to create a new shared_simple_eval_estate too, if there's not
8180  * one already for the current transaction.  The EState will be cleaned up at
8181  * transaction end.
8182  */
8183 static void
8184 plpgsql_create_econtext(PLpgSQL_execstate *estate)
8185 {
8186         SimpleEcontextStackEntry *entry;
8187
8188         /*
8189          * Create an EState for evaluation of simple expressions, if there's not
8190          * one already in the current transaction.  The EState is made a child of
8191          * TopTransactionContext so it will have the right lifespan.
8192          *
8193          * Note that this path is never taken when executing a DO block; the
8194          * required EState was already made by plpgsql_inline_handler.
8195          */
8196         if (estate->simple_eval_estate == NULL)
8197         {
8198                 MemoryContext oldcontext;
8199
8200                 if (shared_simple_eval_estate == NULL)
8201                 {
8202                         oldcontext = MemoryContextSwitchTo(TopTransactionContext);
8203                         shared_simple_eval_estate = CreateExecutorState();
8204                         MemoryContextSwitchTo(oldcontext);
8205                 }
8206                 estate->simple_eval_estate = shared_simple_eval_estate;
8207         }
8208
8209         /*
8210          * Create a child econtext for the current function.
8211          */
8212         estate->eval_econtext = CreateExprContext(estate->simple_eval_estate);
8213
8214         /*
8215          * Make a stack entry so we can clean up the econtext at subxact end.
8216          * Stack entries are kept in TopTransactionContext for simplicity.
8217          */
8218         entry = (SimpleEcontextStackEntry *)
8219                 MemoryContextAlloc(TopTransactionContext,
8220                                                    sizeof(SimpleEcontextStackEntry));
8221
8222         entry->stack_econtext = estate->eval_econtext;
8223         entry->xact_subxid = GetCurrentSubTransactionId();
8224
8225         entry->next = simple_econtext_stack;
8226         simple_econtext_stack = entry;
8227 }
8228
8229 /*
8230  * plpgsql_destroy_econtext --- destroy function's econtext
8231  *
8232  * We check that it matches the top stack entry, and destroy the stack
8233  * entry along with the context.
8234  */
8235 static void
8236 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
8237 {
8238         SimpleEcontextStackEntry *next;
8239
8240         Assert(simple_econtext_stack != NULL);
8241         Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
8242
8243         next = simple_econtext_stack->next;
8244         pfree(simple_econtext_stack);
8245         simple_econtext_stack = next;
8246
8247         FreeExprContext(estate->eval_econtext, true);
8248         estate->eval_econtext = NULL;
8249 }
8250
8251 /*
8252  * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
8253  *
8254  * If a simple-expression EState was created in the current transaction,
8255  * it has to be cleaned up.
8256  */
8257 void
8258 plpgsql_xact_cb(XactEvent event, void *arg)
8259 {
8260         /*
8261          * If we are doing a clean transaction shutdown, free the EState (so that
8262          * any remaining resources will be released correctly). In an abort, we
8263          * expect the regular abort recovery procedures to release everything of
8264          * interest.
8265          */
8266         if (event == XACT_EVENT_COMMIT || event == XACT_EVENT_PREPARE)
8267         {
8268                 simple_econtext_stack = NULL;
8269
8270                 if (shared_simple_eval_estate)
8271                         FreeExecutorState(shared_simple_eval_estate);
8272                 shared_simple_eval_estate = NULL;
8273         }
8274         else if (event == XACT_EVENT_ABORT)
8275         {
8276                 simple_econtext_stack = NULL;
8277                 shared_simple_eval_estate = NULL;
8278         }
8279 }
8280
8281 /*
8282  * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
8283  *
8284  * Make sure any simple-expression econtexts created in the current
8285  * subtransaction get cleaned up.  We have to do this explicitly because
8286  * no other code knows which econtexts belong to which level of subxact.
8287  */
8288 void
8289 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
8290                                    SubTransactionId parentSubid, void *arg)
8291 {
8292         if (event == SUBXACT_EVENT_COMMIT_SUB || event == SUBXACT_EVENT_ABORT_SUB)
8293         {
8294                 while (simple_econtext_stack != NULL &&
8295                            simple_econtext_stack->xact_subxid == mySubid)
8296                 {
8297                         SimpleEcontextStackEntry *next;
8298
8299                         FreeExprContext(simple_econtext_stack->stack_econtext,
8300                                                         (event == SUBXACT_EVENT_COMMIT_SUB));
8301                         next = simple_econtext_stack->next;
8302                         pfree(simple_econtext_stack);
8303                         simple_econtext_stack = next;
8304                 }
8305         }
8306 }
8307
8308 /*
8309  * assign_simple_var --- assign a new value to any VAR datum.
8310  *
8311  * This should be the only mechanism for assignment to simple variables,
8312  * lest we do the release of the old value incorrectly (not to mention
8313  * the detoasting business).
8314  */
8315 static void
8316 assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
8317                                   Datum newvalue, bool isnull, bool freeable)
8318 {
8319         Assert(var->dtype == PLPGSQL_DTYPE_VAR ||
8320                    var->dtype == PLPGSQL_DTYPE_PROMISE);
8321
8322         /*
8323          * In non-atomic contexts, we do not want to store TOAST pointers in
8324          * variables, because such pointers might become stale after a commit.
8325          * Forcibly detoast in such cases.  We don't want to detoast (flatten)
8326          * expanded objects, however; those should be OK across a transaction
8327          * boundary since they're just memory-resident objects.  (Elsewhere in
8328          * this module, operations on expanded records likewise need to request
8329          * detoasting of record fields when !estate->atomic.  Expanded arrays are
8330          * not a problem since all array entries are always detoasted.)
8331          */
8332         if (!estate->atomic && !isnull && var->datatype->typlen == -1 &&
8333                 VARATT_IS_EXTERNAL_NON_EXPANDED(DatumGetPointer(newvalue)))
8334         {
8335                 MemoryContext oldcxt;
8336                 Datum           detoasted;
8337
8338                 /*
8339                  * Do the detoasting in the eval_mcontext to avoid long-term leakage
8340                  * of whatever memory toast fetching might leak.  Then we have to copy
8341                  * the detoasted datum to the function's main context, which is a
8342                  * pain, but there's little choice.
8343                  */
8344                 oldcxt = MemoryContextSwitchTo(get_eval_mcontext(estate));
8345                 detoasted = PointerGetDatum(detoast_external_attr((struct varlena *) DatumGetPointer(newvalue)));
8346                 MemoryContextSwitchTo(oldcxt);
8347                 /* Now's a good time to not leak the input value if it's freeable */
8348                 if (freeable)
8349                         pfree(DatumGetPointer(newvalue));
8350                 /* Once we copy the value, it's definitely freeable */
8351                 newvalue = datumCopy(detoasted, false, -1);
8352                 freeable = true;
8353                 /* Can't clean up eval_mcontext here, but it'll happen before long */
8354         }
8355
8356         /* Free the old value if needed */
8357         if (var->freeval)
8358         {
8359                 if (DatumIsReadWriteExpandedObject(var->value,
8360                                                                                    var->isnull,
8361                                                                                    var->datatype->typlen))
8362                         DeleteExpandedObject(var->value);
8363                 else
8364                         pfree(DatumGetPointer(var->value));
8365         }
8366         /* Assign new value to datum */
8367         var->value = newvalue;
8368         var->isnull = isnull;
8369         var->freeval = freeable;
8370
8371         /*
8372          * If it's a promise variable, then either we just assigned the promised
8373          * value, or the user explicitly assigned an overriding value.  Either
8374          * way, cancel the promise.
8375          */
8376         var->promise = PLPGSQL_PROMISE_NONE;
8377 }
8378
8379 /*
8380  * free old value of a text variable and assign new value from C string
8381  */
8382 static void
8383 assign_text_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, const char *str)
8384 {
8385         assign_simple_var(estate, var, CStringGetTextDatum(str), false, true);
8386 }
8387
8388 /*
8389  * assign_record_var --- assign a new value to any REC datum.
8390  */
8391 static void
8392 assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec,
8393                                   ExpandedRecordHeader *erh)
8394 {
8395         Assert(rec->dtype == PLPGSQL_DTYPE_REC);
8396
8397         /* Transfer new record object into datum_context */
8398         TransferExpandedRecord(erh, estate->datum_context);
8399
8400         /* Free the old value ... */
8401         if (rec->erh)
8402                 DeleteExpandedObject(ExpandedRecordGetDatum(rec->erh));
8403
8404         /* ... and install the new */
8405         rec->erh = erh;
8406 }
8407
8408 /*
8409  * exec_eval_using_params --- evaluate params of USING clause
8410  *
8411  * The result data structure is created in the stmt_mcontext, and should
8412  * be freed by resetting that context.
8413  */
8414 static PreparedParamsData *
8415 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
8416 {
8417         PreparedParamsData *ppd;
8418         MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
8419         int                     nargs;
8420         int                     i;
8421         ListCell   *lc;
8422
8423         ppd = (PreparedParamsData *)
8424                 MemoryContextAlloc(stmt_mcontext, sizeof(PreparedParamsData));
8425         nargs = list_length(params);
8426
8427         ppd->nargs = nargs;
8428         ppd->types = (Oid *)
8429                 MemoryContextAlloc(stmt_mcontext, nargs * sizeof(Oid));
8430         ppd->values = (Datum *)
8431                 MemoryContextAlloc(stmt_mcontext, nargs * sizeof(Datum));
8432         ppd->nulls = (char *)
8433                 MemoryContextAlloc(stmt_mcontext, nargs * sizeof(char));
8434
8435         i = 0;
8436         foreach(lc, params)
8437         {
8438                 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
8439                 bool            isnull;
8440                 int32           ppdtypmod;
8441                 MemoryContext oldcontext;
8442
8443                 ppd->values[i] = exec_eval_expr(estate, param,
8444                                                                                 &isnull,
8445                                                                                 &ppd->types[i],
8446                                                                                 &ppdtypmod);
8447                 ppd->nulls[i] = isnull ? 'n' : ' ';
8448
8449                 oldcontext = MemoryContextSwitchTo(stmt_mcontext);
8450
8451                 if (ppd->types[i] == UNKNOWNOID)
8452                 {
8453                         /*
8454                          * Treat 'unknown' parameters as text, since that's what most
8455                          * people would expect. SPI_execute_with_args can coerce unknown
8456                          * constants in a more intelligent way, but not unknown Params.
8457                          * This code also takes care of copying into the right context.
8458                          * Note we assume 'unknown' has the representation of C-string.
8459                          */
8460                         ppd->types[i] = TEXTOID;
8461                         if (!isnull)
8462                                 ppd->values[i] = CStringGetTextDatum(DatumGetCString(ppd->values[i]));
8463                 }
8464                 /* pass-by-ref non null values must be copied into stmt_mcontext */
8465                 else if (!isnull)
8466                 {
8467                         int16           typLen;
8468                         bool            typByVal;
8469
8470                         get_typlenbyval(ppd->types[i], &typLen, &typByVal);
8471                         if (!typByVal)
8472                                 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
8473                 }
8474
8475                 MemoryContextSwitchTo(oldcontext);
8476
8477                 exec_eval_cleanup(estate);
8478
8479                 i++;
8480         }
8481
8482         return ppd;
8483 }
8484
8485 /*
8486  * Open portal for dynamic query
8487  *
8488  * Caution: this resets the stmt_mcontext at exit.  We might eventually need
8489  * to move that responsibility to the callers, but currently no caller needs
8490  * to have statement-lifetime temp data that survives past this, so it's
8491  * simpler to do it here.
8492  */
8493 static Portal
8494 exec_dynquery_with_params(PLpgSQL_execstate *estate,
8495                                                   PLpgSQL_expr *dynquery,
8496                                                   List *params,
8497                                                   const char *portalname,
8498                                                   int cursorOptions)
8499 {
8500         Portal          portal;
8501         Datum           query;
8502         bool            isnull;
8503         Oid                     restype;
8504         int32           restypmod;
8505         char       *querystr;
8506         MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
8507
8508         /*
8509          * Evaluate the string expression after the EXECUTE keyword. Its result is
8510          * the querystring we have to execute.
8511          */
8512         query = exec_eval_expr(estate, dynquery, &isnull, &restype, &restypmod);
8513         if (isnull)
8514                 ereport(ERROR,
8515                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
8516                                  errmsg("query string argument of EXECUTE is null")));
8517
8518         /* Get the C-String representation */
8519         querystr = convert_value_to_string(estate, query, restype);
8520
8521         /* copy it into the stmt_mcontext before we clean up */
8522         querystr = MemoryContextStrdup(stmt_mcontext, querystr);
8523
8524         exec_eval_cleanup(estate);
8525
8526         /*
8527          * Open an implicit cursor for the query.  We use
8528          * SPI_cursor_open_with_args even when there are no params, because this
8529          * avoids making and freeing one copy of the plan.
8530          */
8531         if (params)
8532         {
8533                 PreparedParamsData *ppd;
8534
8535                 ppd = exec_eval_using_params(estate, params);
8536                 portal = SPI_cursor_open_with_args(portalname,
8537                                                                                    querystr,
8538                                                                                    ppd->nargs, ppd->types,
8539                                                                                    ppd->values, ppd->nulls,
8540                                                                                    estate->readonly_func,
8541                                                                                    cursorOptions);
8542         }
8543         else
8544         {
8545                 portal = SPI_cursor_open_with_args(portalname,
8546                                                                                    querystr,
8547                                                                                    0, NULL,
8548                                                                                    NULL, NULL,
8549                                                                                    estate->readonly_func,
8550                                                                                    cursorOptions);
8551         }
8552
8553         if (portal == NULL)
8554                 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
8555                          querystr, SPI_result_code_string(SPI_result));
8556
8557         /* Release transient data */
8558         MemoryContextReset(stmt_mcontext);
8559
8560         return portal;
8561 }
8562
8563 /*
8564  * Return a formatted string with information about an expression's parameters,
8565  * or NULL if the expression does not take any parameters.
8566  * The result is in the eval_mcontext.
8567  */
8568 static char *
8569 format_expr_params(PLpgSQL_execstate *estate,
8570                                    const PLpgSQL_expr *expr)
8571 {
8572         int                     paramno;
8573         int                     dno;
8574         StringInfoData paramstr;
8575         MemoryContext oldcontext;
8576
8577         if (!expr->paramnos)
8578                 return NULL;
8579
8580         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
8581
8582         initStringInfo(&paramstr);
8583         paramno = 0;
8584         dno = -1;
8585         while ((dno = bms_next_member(expr->paramnos, dno)) >= 0)
8586         {
8587                 Datum           paramdatum;
8588                 Oid                     paramtypeid;
8589                 bool            paramisnull;
8590                 int32           paramtypmod;
8591                 PLpgSQL_var *curvar;
8592
8593                 curvar = (PLpgSQL_var *) estate->datums[dno];
8594
8595                 exec_eval_datum(estate, (PLpgSQL_datum *) curvar,
8596                                                 &paramtypeid, &paramtypmod,
8597                                                 &paramdatum, &paramisnull);
8598
8599                 appendStringInfo(&paramstr, "%s%s = ",
8600                                                  paramno > 0 ? ", " : "",
8601                                                  curvar->refname);
8602
8603                 if (paramisnull)
8604                         appendStringInfoString(&paramstr, "NULL");
8605                 else
8606                 {
8607                         char       *value = convert_value_to_string(estate, paramdatum, paramtypeid);
8608                         char       *p;
8609
8610                         appendStringInfoCharMacro(&paramstr, '\'');
8611                         for (p = value; *p; p++)
8612                         {
8613                                 if (*p == '\'') /* double single quotes */
8614                                         appendStringInfoCharMacro(&paramstr, *p);
8615                                 appendStringInfoCharMacro(&paramstr, *p);
8616                         }
8617                         appendStringInfoCharMacro(&paramstr, '\'');
8618                 }
8619
8620                 paramno++;
8621         }
8622
8623         MemoryContextSwitchTo(oldcontext);
8624
8625         return paramstr.data;
8626 }
8627
8628 /*
8629  * Return a formatted string with information about PreparedParamsData, or NULL
8630  * if there are no parameters.
8631  * The result is in the eval_mcontext.
8632  */
8633 static char *
8634 format_preparedparamsdata(PLpgSQL_execstate *estate,
8635                                                   const PreparedParamsData *ppd)
8636 {
8637         int                     paramno;
8638         StringInfoData paramstr;
8639         MemoryContext oldcontext;
8640
8641         if (!ppd)
8642                 return NULL;
8643
8644         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
8645
8646         initStringInfo(&paramstr);
8647         for (paramno = 0; paramno < ppd->nargs; paramno++)
8648         {
8649                 appendStringInfo(&paramstr, "%s$%d = ",
8650                                                  paramno > 0 ? ", " : "",
8651                                                  paramno + 1);
8652
8653                 if (ppd->nulls[paramno] == 'n')
8654                         appendStringInfoString(&paramstr, "NULL");
8655                 else
8656                 {
8657                         char       *value = convert_value_to_string(estate, ppd->values[paramno], ppd->types[paramno]);
8658                         char       *p;
8659
8660                         appendStringInfoCharMacro(&paramstr, '\'');
8661                         for (p = value; *p; p++)
8662                         {
8663                                 if (*p == '\'') /* double single quotes */
8664                                         appendStringInfoCharMacro(&paramstr, *p);
8665                                 appendStringInfoCharMacro(&paramstr, *p);
8666                         }
8667                         appendStringInfoCharMacro(&paramstr, '\'');
8668                 }
8669         }
8670
8671         MemoryContextSwitchTo(oldcontext);
8672
8673         return paramstr.data;
8674 }