]> granicus.if.org Git - postgresql/blob - src/pl/plpgsql/src/pl_exec.c
4030b647fb029ab30cb560753f387750c921905d
[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-2015, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/pl/plpgsql/src/pl_exec.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "plpgsql.h"
17
18 #include <ctype.h>
19
20 #include "access/htup_details.h"
21 #include "access/transam.h"
22 #include "access/tupconvert.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "executor/spi.h"
26 #include "funcapi.h"
27 #include "miscadmin.h"
28 #include "nodes/nodeFuncs.h"
29 #include "optimizer/planner.h"
30 #include "parser/parse_coerce.h"
31 #include "parser/scansup.h"
32 #include "storage/proc.h"
33 #include "tcop/tcopprot.h"
34 #include "utils/array.h"
35 #include "utils/builtins.h"
36 #include "utils/datum.h"
37 #include "utils/lsyscache.h"
38 #include "utils/memutils.h"
39 #include "utils/rel.h"
40 #include "utils/snapmgr.h"
41 #include "utils/typcache.h"
42
43
44 static const char *const raise_skip_msg = "RAISE";
45
46 typedef struct
47 {
48         int                     nargs;                  /* number of arguments */
49         Oid                *types;                      /* types of arguments */
50         Datum      *values;                     /* evaluated argument values */
51         char       *nulls;                      /* null markers (' '/'n' style) */
52         bool       *freevals;           /* which arguments are pfree-able */
53 } PreparedParamsData;
54
55 typedef struct
56 {
57         /* NB: we assume this struct contains no padding bytes */
58         Oid                     srctype;                /* source type for cast */
59         Oid                     dsttype;                /* destination type for cast */
60         int32           dsttypmod;              /* destination typmod for cast */
61 } plpgsql_CastHashKey;
62
63 typedef struct
64 {
65         plpgsql_CastHashKey key;        /* hash key --- MUST BE FIRST */
66         ExprState  *cast_exprstate; /* cast expression, or NULL if no-op cast */
67 } plpgsql_CastHashEntry;
68
69 /*
70  * All plpgsql function executions within a single transaction share the same
71  * executor EState for evaluating "simple" expressions.  Each function call
72  * creates its own "eval_econtext" ExprContext within this estate for
73  * per-evaluation workspace.  eval_econtext is freed at normal function exit,
74  * and the EState is freed at transaction end (in case of error, we assume
75  * that the abort mechanisms clean it all up).  Furthermore, any exception
76  * block within a function has to have its own eval_econtext separate from
77  * the containing function's, so that we can clean up ExprContext callbacks
78  * properly at subtransaction exit.  We maintain a stack that tracks the
79  * individual econtexts so that we can clean up correctly at subxact exit.
80  *
81  * This arrangement is a bit tedious to maintain, but it's worth the trouble
82  * so that we don't have to re-prepare simple expressions on each trip through
83  * a function.  (We assume the case to optimize is many repetitions of a
84  * function within a transaction.)
85  *
86  * However, there's no value in trying to amortize simple expression setup
87  * across multiple executions of a DO block (inline code block), since there
88  * can never be any.  If we use the shared EState for a DO block, the expr
89  * state trees are effectively leaked till end of transaction, and that can
90  * add up if the user keeps on submitting DO blocks.  Therefore, each DO block
91  * has its own simple-expression EState, which is cleaned up at exit from
92  * plpgsql_inline_handler().  DO blocks still use the simple_econtext_stack,
93  * though, so that subxact abort cleanup does the right thing.
94  */
95 typedef struct SimpleEcontextStackEntry
96 {
97         ExprContext *stack_econtext;    /* a stacked econtext */
98         SubTransactionId xact_subxid;           /* ID for current subxact */
99         struct SimpleEcontextStackEntry *next;          /* next stack entry up */
100 } SimpleEcontextStackEntry;
101
102 static EState *shared_simple_eval_estate = NULL;
103 static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
104
105 /************************************************************
106  * Local function forward declarations
107  ************************************************************/
108 static void plpgsql_exec_error_callback(void *arg);
109 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
110
111 static int exec_stmt_block(PLpgSQL_execstate *estate,
112                                 PLpgSQL_stmt_block *block);
113 static int exec_stmts(PLpgSQL_execstate *estate,
114                    List *stmts);
115 static int exec_stmt(PLpgSQL_execstate *estate,
116                   PLpgSQL_stmt *stmt);
117 static int exec_stmt_assign(PLpgSQL_execstate *estate,
118                                  PLpgSQL_stmt_assign *stmt);
119 static int exec_stmt_perform(PLpgSQL_execstate *estate,
120                                   PLpgSQL_stmt_perform *stmt);
121 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
122                                   PLpgSQL_stmt_getdiag *stmt);
123 static int exec_stmt_if(PLpgSQL_execstate *estate,
124                          PLpgSQL_stmt_if *stmt);
125 static int exec_stmt_case(PLpgSQL_execstate *estate,
126                            PLpgSQL_stmt_case *stmt);
127 static int exec_stmt_loop(PLpgSQL_execstate *estate,
128                            PLpgSQL_stmt_loop *stmt);
129 static int exec_stmt_while(PLpgSQL_execstate *estate,
130                                 PLpgSQL_stmt_while *stmt);
131 static int exec_stmt_fori(PLpgSQL_execstate *estate,
132                            PLpgSQL_stmt_fori *stmt);
133 static int exec_stmt_fors(PLpgSQL_execstate *estate,
134                            PLpgSQL_stmt_fors *stmt);
135 static int exec_stmt_forc(PLpgSQL_execstate *estate,
136                            PLpgSQL_stmt_forc *stmt);
137 static int exec_stmt_foreach_a(PLpgSQL_execstate *estate,
138                                         PLpgSQL_stmt_foreach_a *stmt);
139 static int exec_stmt_open(PLpgSQL_execstate *estate,
140                            PLpgSQL_stmt_open *stmt);
141 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
142                                 PLpgSQL_stmt_fetch *stmt);
143 static int exec_stmt_close(PLpgSQL_execstate *estate,
144                                 PLpgSQL_stmt_close *stmt);
145 static int exec_stmt_exit(PLpgSQL_execstate *estate,
146                            PLpgSQL_stmt_exit *stmt);
147 static int exec_stmt_return(PLpgSQL_execstate *estate,
148                                  PLpgSQL_stmt_return *stmt);
149 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
150                                           PLpgSQL_stmt_return_next *stmt);
151 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
152                                            PLpgSQL_stmt_return_query *stmt);
153 static int exec_stmt_raise(PLpgSQL_execstate *estate,
154                                 PLpgSQL_stmt_raise *stmt);
155 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
156                                   PLpgSQL_stmt_execsql *stmt);
157 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
158                                          PLpgSQL_stmt_dynexecute *stmt);
159 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
160                                   PLpgSQL_stmt_dynfors *stmt);
161
162 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
163                                          PLpgSQL_function *func,
164                                          ReturnSetInfo *rsi,
165                                          EState *simple_eval_estate);
166 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
167
168 static void exec_prepare_plan(PLpgSQL_execstate *estate,
169                                   PLpgSQL_expr *expr, int cursorOptions);
170 static bool exec_simple_check_node(Node *node);
171 static void exec_simple_check_plan(PLpgSQL_expr *expr);
172 static void exec_simple_recheck_plan(PLpgSQL_expr *expr, CachedPlan *cplan);
173 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
174                                           PLpgSQL_expr *expr,
175                                           Datum *result,
176                                           bool *isNull,
177                                           Oid *rettype,
178                                           int32 *rettypmod);
179
180 static void exec_assign_expr(PLpgSQL_execstate *estate,
181                                  PLpgSQL_datum *target,
182                                  PLpgSQL_expr *expr);
183 static void exec_assign_c_string(PLpgSQL_execstate *estate,
184                                          PLpgSQL_datum *target,
185                                          const char *str);
186 static void exec_assign_value(PLpgSQL_execstate *estate,
187                                   PLpgSQL_datum *target,
188                                   Datum value, bool isNull,
189                                   Oid valtype, int32 valtypmod);
190 static void exec_eval_datum(PLpgSQL_execstate *estate,
191                                 PLpgSQL_datum *datum,
192                                 Oid *typeid,
193                                 int32 *typetypmod,
194                                 Datum *value,
195                                 bool *isnull);
196 static int exec_eval_integer(PLpgSQL_execstate *estate,
197                                   PLpgSQL_expr *expr,
198                                   bool *isNull);
199 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
200                                   PLpgSQL_expr *expr,
201                                   bool *isNull);
202 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
203                            PLpgSQL_expr *expr,
204                            bool *isNull,
205                            Oid *rettype,
206                            int32 *rettypmod);
207 static int exec_run_select(PLpgSQL_execstate *estate,
208                                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
209 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
210                            Portal portal, bool prefetch_ok);
211 static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
212                                  PLpgSQL_expr *expr);
213 static void plpgsql_param_fetch(ParamListInfo params, int paramid);
214 static void exec_move_row(PLpgSQL_execstate *estate,
215                           PLpgSQL_rec *rec,
216                           PLpgSQL_row *row,
217                           HeapTuple tup, TupleDesc tupdesc);
218 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
219                                         PLpgSQL_row *row,
220                                         TupleDesc tupdesc);
221 static HeapTuple get_tuple_from_datum(Datum value);
222 static TupleDesc get_tupdesc_from_datum(Datum value);
223 static void exec_move_row_from_datum(PLpgSQL_execstate *estate,
224                                                  PLpgSQL_rec *rec,
225                                                  PLpgSQL_row *row,
226                                                  Datum value);
227 static char *convert_value_to_string(PLpgSQL_execstate *estate,
228                                                 Datum value, Oid valtype);
229 static Datum exec_cast_value(PLpgSQL_execstate *estate,
230                                 Datum value, bool *isnull,
231                                 Oid valtype, int32 valtypmod,
232                                 Oid reqtype, int32 reqtypmod);
233 static ExprState *get_cast_expression(PLpgSQL_execstate *estate,
234                                         Oid srctype, Oid dsttype, int32 dsttypmod);
235 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
236 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
237 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
238 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
239 static void free_var(PLpgSQL_var *var);
240 static void assign_text_var(PLpgSQL_var *var, const char *str);
241 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
242                                            List *params);
243 static void free_params_data(PreparedParamsData *ppd);
244 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
245                                                   PLpgSQL_expr *dynquery, List *params,
246                                                   const char *portalname, int cursorOptions);
247
248 static char *format_expr_params(PLpgSQL_execstate *estate,
249                                    const PLpgSQL_expr *expr);
250 static char *format_preparedparamsdata(PLpgSQL_execstate *estate,
251                                                   const PreparedParamsData *ppd);
252
253
254 /* ----------
255  * plpgsql_exec_function        Called by the call handler for
256  *                              function execution.
257  *
258  * This is also used to execute inline code blocks (DO blocks).  The only
259  * difference that this code is aware of is that for a DO block, we want
260  * to use a private simple_eval_estate, which is created and passed in by
261  * the caller.  For regular functions, pass NULL, which implies using
262  * shared_simple_eval_estate.
263  * ----------
264  */
265 Datum
266 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
267                                           EState *simple_eval_estate)
268 {
269         PLpgSQL_execstate estate;
270         ErrorContextCallback plerrcontext;
271         int                     i;
272         int                     rc;
273
274         /*
275          * Setup the execution state
276          */
277         plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo,
278                                                  simple_eval_estate);
279
280         /*
281          * Setup error traceback support for ereport()
282          */
283         plerrcontext.callback = plpgsql_exec_error_callback;
284         plerrcontext.arg = &estate;
285         plerrcontext.previous = error_context_stack;
286         error_context_stack = &plerrcontext;
287
288         /*
289          * Make local execution copies of all the datums
290          */
291         estate.err_text = gettext_noop("during initialization of execution state");
292         for (i = 0; i < estate.ndatums; i++)
293                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
294
295         /*
296          * Store the actual call argument values into the appropriate variables
297          */
298         estate.err_text = gettext_noop("while storing call arguments into local variables");
299         for (i = 0; i < func->fn_nargs; i++)
300         {
301                 int                     n = func->fn_argvarnos[i];
302
303                 switch (estate.datums[n]->dtype)
304                 {
305                         case PLPGSQL_DTYPE_VAR:
306                                 {
307                                         PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
308
309                                         var->value = fcinfo->arg[i];
310                                         var->isnull = fcinfo->argnull[i];
311                                         var->freeval = false;
312                                 }
313                                 break;
314
315                         case PLPGSQL_DTYPE_ROW:
316                                 {
317                                         PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
318
319                                         if (!fcinfo->argnull[i])
320                                         {
321                                                 /* Assign row value from composite datum */
322                                                 exec_move_row_from_datum(&estate, NULL, row,
323                                                                                                  fcinfo->arg[i]);
324                                         }
325                                         else
326                                         {
327                                                 /* If arg is null, treat it as an empty row */
328                                                 exec_move_row(&estate, NULL, row, NULL, NULL);
329                                         }
330                                         /* clean up after exec_move_row() */
331                                         exec_eval_cleanup(&estate);
332                                 }
333                                 break;
334
335                         default:
336                                 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
337                 }
338         }
339
340         estate.err_text = gettext_noop("during function entry");
341
342         /*
343          * Set the magic variable FOUND to false
344          */
345         exec_set_found(&estate, false);
346
347         /*
348          * Let the instrumentation plugin peek at this function
349          */
350         if (*plugin_ptr && (*plugin_ptr)->func_beg)
351                 ((*plugin_ptr)->func_beg) (&estate, func);
352
353         /*
354          * Now call the toplevel block of statements
355          */
356         estate.err_text = NULL;
357         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
358         rc = exec_stmt_block(&estate, func->action);
359         if (rc != PLPGSQL_RC_RETURN)
360         {
361                 estate.err_stmt = NULL;
362                 estate.err_text = NULL;
363
364                 /*
365                  * Provide a more helpful message if a CONTINUE or RAISE has been used
366                  * outside the context it can work in.
367                  */
368                 if (rc == PLPGSQL_RC_CONTINUE)
369                         ereport(ERROR,
370                                         (errcode(ERRCODE_SYNTAX_ERROR),
371                                          errmsg("CONTINUE cannot be used outside a loop")));
372                 else
373                         ereport(ERROR,
374                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
375                                 errmsg("control reached end of function without RETURN")));
376         }
377
378         /*
379          * We got a return value - process it
380          */
381         estate.err_stmt = NULL;
382         estate.err_text = gettext_noop("while casting return value to function's return type");
383
384         fcinfo->isnull = estate.retisnull;
385
386         if (estate.retisset)
387         {
388                 ReturnSetInfo *rsi = estate.rsi;
389
390                 /* Check caller can handle a set result */
391                 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
392                         (rsi->allowedModes & SFRM_Materialize) == 0)
393                         ereport(ERROR,
394                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
395                                          errmsg("set-valued function called in context that cannot accept a set")));
396                 rsi->returnMode = SFRM_Materialize;
397
398                 /* If we produced any tuples, send back the result */
399                 if (estate.tuple_store)
400                 {
401                         rsi->setResult = estate.tuple_store;
402                         if (estate.rettupdesc)
403                         {
404                                 MemoryContext oldcxt;
405
406                                 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
407                                 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
408                                 MemoryContextSwitchTo(oldcxt);
409                         }
410                 }
411                 estate.retval = (Datum) 0;
412                 fcinfo->isnull = true;
413         }
414         else if (!estate.retisnull)
415         {
416                 if (estate.retistuple)
417                 {
418                         /*
419                          * We have to check that the returned tuple actually matches the
420                          * expected result type.  XXX would be better to cache the tupdesc
421                          * instead of repeating get_call_result_type()
422                          */
423                         HeapTuple       rettup = (HeapTuple) DatumGetPointer(estate.retval);
424                         TupleDesc       tupdesc;
425                         TupleConversionMap *tupmap;
426
427                         switch (get_call_result_type(fcinfo, NULL, &tupdesc))
428                         {
429                                 case TYPEFUNC_COMPOSITE:
430                                         /* got the expected result rowtype, now check it */
431                                         tupmap = convert_tuples_by_position(estate.rettupdesc,
432                                                                                                                 tupdesc,
433                                                                                                                 gettext_noop("returned record type does not match expected record type"));
434                                         /* it might need conversion */
435                                         if (tupmap)
436                                                 rettup = do_convert_tuple(rettup, tupmap);
437                                         /* no need to free map, we're about to return anyway */
438                                         break;
439                                 case TYPEFUNC_RECORD:
440
441                                         /*
442                                          * Failed to determine actual type of RECORD.  We could
443                                          * raise an error here, but what this means in practice is
444                                          * that the caller is expecting any old generic rowtype,
445                                          * so we don't really need to be restrictive. Pass back
446                                          * the generated result type, instead.
447                                          */
448                                         tupdesc = estate.rettupdesc;
449                                         if (tupdesc == NULL)            /* shouldn't happen */
450                                                 elog(ERROR, "return type must be a row type");
451                                         break;
452                                 default:
453                                         /* shouldn't get here if retistuple is true ... */
454                                         elog(ERROR, "return type must be a row type");
455                                         break;
456                         }
457
458                         /*
459                          * Copy tuple to upper executor memory, as a tuple Datum. Make
460                          * sure it is labeled with the caller-supplied tuple type.
461                          */
462                         estate.retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
463                 }
464                 else
465                 {
466                         /* Cast value to proper type */
467                         estate.retval = exec_cast_value(&estate,
468                                                                                         estate.retval,
469                                                                                         &fcinfo->isnull,
470                                                                                         estate.rettype,
471                                                                                         -1,
472                                                                                         func->fn_rettype,
473                                                                                         -1);
474
475                         /*
476                          * If the function's return type isn't by value, copy the value
477                          * into upper executor memory context.
478                          */
479                         if (!fcinfo->isnull && !func->fn_retbyval)
480                         {
481                                 Size            len;
482                                 void       *tmp;
483
484                                 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
485                                 tmp = SPI_palloc(len);
486                                 memcpy(tmp, DatumGetPointer(estate.retval), len);
487                                 estate.retval = PointerGetDatum(tmp);
488                         }
489                 }
490         }
491
492         estate.err_text = gettext_noop("during function exit");
493
494         /*
495          * Let the instrumentation plugin peek at this function
496          */
497         if (*plugin_ptr && (*plugin_ptr)->func_end)
498                 ((*plugin_ptr)->func_end) (&estate, func);
499
500         /* Clean up any leftover temporary memory */
501         plpgsql_destroy_econtext(&estate);
502         exec_eval_cleanup(&estate);
503
504         /*
505          * Pop the error context stack
506          */
507         error_context_stack = plerrcontext.previous;
508
509         /*
510          * Return the function's result
511          */
512         return estate.retval;
513 }
514
515
516 /* ----------
517  * plpgsql_exec_trigger         Called by the call handler for
518  *                              trigger execution.
519  * ----------
520  */
521 HeapTuple
522 plpgsql_exec_trigger(PLpgSQL_function *func,
523                                          TriggerData *trigdata)
524 {
525         PLpgSQL_execstate estate;
526         ErrorContextCallback plerrcontext;
527         int                     i;
528         int                     rc;
529         PLpgSQL_var *var;
530         PLpgSQL_rec *rec_new,
531                            *rec_old;
532         HeapTuple       rettup;
533
534         /*
535          * Setup the execution state
536          */
537         plpgsql_estate_setup(&estate, func, NULL, NULL);
538
539         /*
540          * Setup error traceback support for ereport()
541          */
542         plerrcontext.callback = plpgsql_exec_error_callback;
543         plerrcontext.arg = &estate;
544         plerrcontext.previous = error_context_stack;
545         error_context_stack = &plerrcontext;
546
547         /*
548          * Make local execution copies of all the datums
549          */
550         estate.err_text = gettext_noop("during initialization of execution state");
551         for (i = 0; i < estate.ndatums; i++)
552                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
553
554         /*
555          * Put the OLD and NEW tuples into record variables
556          *
557          * We make the tupdescs available in both records even though only one may
558          * have a value.  This allows parsing of record references to succeed in
559          * functions that are used for multiple trigger types.  For example, we
560          * might have a test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')",
561          * which should parse regardless of the current trigger type.
562          */
563         rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
564         rec_new->freetup = false;
565         rec_new->tupdesc = trigdata->tg_relation->rd_att;
566         rec_new->freetupdesc = false;
567         rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
568         rec_old->freetup = false;
569         rec_old->tupdesc = trigdata->tg_relation->rd_att;
570         rec_old->freetupdesc = false;
571
572         if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
573         {
574                 /*
575                  * Per-statement triggers don't use OLD/NEW variables
576                  */
577                 rec_new->tup = NULL;
578                 rec_old->tup = NULL;
579         }
580         else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
581         {
582                 rec_new->tup = trigdata->tg_trigtuple;
583                 rec_old->tup = NULL;
584         }
585         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
586         {
587                 rec_new->tup = trigdata->tg_newtuple;
588                 rec_old->tup = trigdata->tg_trigtuple;
589         }
590         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
591         {
592                 rec_new->tup = NULL;
593                 rec_old->tup = trigdata->tg_trigtuple;
594         }
595         else
596                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
597
598         /*
599          * Assign the special tg_ variables
600          */
601
602         var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
603         if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
604                 var->value = CStringGetTextDatum("INSERT");
605         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
606                 var->value = CStringGetTextDatum("UPDATE");
607         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
608                 var->value = CStringGetTextDatum("DELETE");
609         else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
610                 var->value = CStringGetTextDatum("TRUNCATE");
611         else
612                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
613         var->isnull = false;
614         var->freeval = true;
615
616         var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
617         var->value = DirectFunctionCall1(namein,
618                                                           CStringGetDatum(trigdata->tg_trigger->tgname));
619         var->isnull = false;
620         var->freeval = true;
621
622         var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
623         if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
624                 var->value = CStringGetTextDatum("BEFORE");
625         else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
626                 var->value = CStringGetTextDatum("AFTER");
627         else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
628                 var->value = CStringGetTextDatum("INSTEAD OF");
629         else
630                 elog(ERROR, "unrecognized trigger execution time: not BEFORE, AFTER, or INSTEAD OF");
631         var->isnull = false;
632         var->freeval = true;
633
634         var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
635         if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
636                 var->value = CStringGetTextDatum("ROW");
637         else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
638                 var->value = CStringGetTextDatum("STATEMENT");
639         else
640                 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
641         var->isnull = false;
642         var->freeval = true;
643
644         var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
645         var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
646         var->isnull = false;
647         var->freeval = false;
648
649         var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
650         var->value = DirectFunctionCall1(namein,
651                         CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
652         var->isnull = false;
653         var->freeval = true;
654
655         var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
656         var->value = DirectFunctionCall1(namein,
657                         CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
658         var->isnull = false;
659         var->freeval = true;
660
661         var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
662         var->value = DirectFunctionCall1(namein,
663                                                                          CStringGetDatum(
664                                                                                                          get_namespace_name(
665                                                                                                                 RelationGetNamespace(
666                                                                                                    trigdata->tg_relation))));
667         var->isnull = false;
668         var->freeval = true;
669
670         var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
671         var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
672         var->isnull = false;
673         var->freeval = false;
674
675         var = (PLpgSQL_var *) (estate.datums[func->tg_argv_varno]);
676         if (trigdata->tg_trigger->tgnargs > 0)
677         {
678                 /*
679                  * For historical reasons, tg_argv[] subscripts start at zero not one.
680                  * So we can't use construct_array().
681                  */
682                 int                     nelems = trigdata->tg_trigger->tgnargs;
683                 Datum      *elems;
684                 int                     dims[1];
685                 int                     lbs[1];
686
687                 elems = palloc(sizeof(Datum) * nelems);
688                 for (i = 0; i < nelems; i++)
689                         elems[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
690                 dims[0] = nelems;
691                 lbs[0] = 0;
692
693                 var->value = PointerGetDatum(construct_md_array(elems, NULL,
694                                                                                                                 1, dims, lbs,
695                                                                                                                 TEXTOID,
696                                                                                                                 -1, false, 'i'));
697                 var->isnull = false;
698                 var->freeval = true;
699         }
700         else
701         {
702                 var->value = (Datum) 0;
703                 var->isnull = true;
704                 var->freeval = false;
705         }
706
707         estate.err_text = gettext_noop("during function entry");
708
709         /*
710          * Set the magic variable FOUND to false
711          */
712         exec_set_found(&estate, false);
713
714         /*
715          * Let the instrumentation plugin peek at this function
716          */
717         if (*plugin_ptr && (*plugin_ptr)->func_beg)
718                 ((*plugin_ptr)->func_beg) (&estate, func);
719
720         /*
721          * Now call the toplevel block of statements
722          */
723         estate.err_text = NULL;
724         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
725         rc = exec_stmt_block(&estate, func->action);
726         if (rc != PLPGSQL_RC_RETURN)
727         {
728                 estate.err_stmt = NULL;
729                 estate.err_text = NULL;
730
731                 /*
732                  * Provide a more helpful message if a CONTINUE or RAISE has been used
733                  * outside the context it can work in.
734                  */
735                 if (rc == PLPGSQL_RC_CONTINUE)
736                         ereport(ERROR,
737                                         (errcode(ERRCODE_SYNTAX_ERROR),
738                                          errmsg("CONTINUE cannot be used outside a loop")));
739                 else
740                         ereport(ERROR,
741                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
742                                 errmsg("control reached end of trigger procedure without RETURN")));
743         }
744
745         estate.err_stmt = NULL;
746         estate.err_text = gettext_noop("during function exit");
747
748         if (estate.retisset)
749                 ereport(ERROR,
750                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
751                                  errmsg("trigger procedure cannot return a set")));
752
753         /*
754          * Check that the returned tuple structure has the same attributes, the
755          * relation that fired the trigger has. A per-statement trigger always
756          * needs to return NULL, so we ignore any return value the function itself
757          * produces (XXX: is this a good idea?)
758          *
759          * XXX This way it is possible, that the trigger returns a tuple where
760          * attributes don't have the correct atttypmod's length. It's up to the
761          * trigger's programmer to ensure that this doesn't happen. Jan
762          */
763         if (estate.retisnull || !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
764                 rettup = NULL;
765         else
766         {
767                 TupleConversionMap *tupmap;
768
769                 rettup = (HeapTuple) DatumGetPointer(estate.retval);
770                 /* check rowtype compatibility */
771                 tupmap = convert_tuples_by_position(estate.rettupdesc,
772                                                                                         trigdata->tg_relation->rd_att,
773                                                                                         gettext_noop("returned row structure does not match the structure of the triggering table"));
774                 /* it might need conversion */
775                 if (tupmap)
776                         rettup = do_convert_tuple(rettup, tupmap);
777                 /* no need to free map, we're about to return anyway */
778
779                 /* Copy tuple to upper executor memory */
780                 rettup = SPI_copytuple(rettup);
781         }
782
783         /*
784          * Let the instrumentation plugin peek at this function
785          */
786         if (*plugin_ptr && (*plugin_ptr)->func_end)
787                 ((*plugin_ptr)->func_end) (&estate, func);
788
789         /* Clean up any leftover temporary memory */
790         plpgsql_destroy_econtext(&estate);
791         exec_eval_cleanup(&estate);
792
793         /*
794          * Pop the error context stack
795          */
796         error_context_stack = plerrcontext.previous;
797
798         /*
799          * Return the trigger's result
800          */
801         return rettup;
802 }
803
804 void
805 plpgsql_exec_event_trigger(PLpgSQL_function *func, EventTriggerData *trigdata)
806 {
807         PLpgSQL_execstate estate;
808         ErrorContextCallback plerrcontext;
809         int                     i;
810         int                     rc;
811         PLpgSQL_var *var;
812
813         /*
814          * Setup the execution state
815          */
816         plpgsql_estate_setup(&estate, func, NULL, NULL);
817
818         /*
819          * Setup error traceback support for ereport()
820          */
821         plerrcontext.callback = plpgsql_exec_error_callback;
822         plerrcontext.arg = &estate;
823         plerrcontext.previous = error_context_stack;
824         error_context_stack = &plerrcontext;
825
826         /*
827          * Make local execution copies of all the datums
828          */
829         estate.err_text = gettext_noop("during initialization of execution state");
830         for (i = 0; i < estate.ndatums; i++)
831                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
832
833         /*
834          * Assign the special tg_ variables
835          */
836         var = (PLpgSQL_var *) (estate.datums[func->tg_event_varno]);
837         var->value = CStringGetTextDatum(trigdata->event);
838         var->isnull = false;
839         var->freeval = true;
840
841         var = (PLpgSQL_var *) (estate.datums[func->tg_tag_varno]);
842         var->value = CStringGetTextDatum(trigdata->tag);
843         var->isnull = false;
844         var->freeval = true;
845
846         /*
847          * Let the instrumentation plugin peek at this function
848          */
849         if (*plugin_ptr && (*plugin_ptr)->func_beg)
850                 ((*plugin_ptr)->func_beg) (&estate, func);
851
852         /*
853          * Now call the toplevel block of statements
854          */
855         estate.err_text = NULL;
856         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
857         rc = exec_stmt_block(&estate, func->action);
858         if (rc != PLPGSQL_RC_RETURN)
859         {
860                 estate.err_stmt = NULL;
861                 estate.err_text = NULL;
862
863                 /*
864                  * Provide a more helpful message if a CONTINUE or RAISE has been used
865                  * outside the context it can work in.
866                  */
867                 if (rc == PLPGSQL_RC_CONTINUE)
868                         ereport(ERROR,
869                                         (errcode(ERRCODE_SYNTAX_ERROR),
870                                          errmsg("CONTINUE cannot be used outside a loop")));
871                 else
872                         ereport(ERROR,
873                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
874                                 errmsg("control reached end of trigger procedure without RETURN")));
875         }
876
877         estate.err_stmt = NULL;
878         estate.err_text = gettext_noop("during function exit");
879
880         /*
881          * Let the instrumentation plugin peek at this function
882          */
883         if (*plugin_ptr && (*plugin_ptr)->func_end)
884                 ((*plugin_ptr)->func_end) (&estate, func);
885
886         /* Clean up any leftover temporary memory */
887         plpgsql_destroy_econtext(&estate);
888         exec_eval_cleanup(&estate);
889
890         /*
891          * Pop the error context stack
892          */
893         error_context_stack = plerrcontext.previous;
894
895         return;
896 }
897
898 /*
899  * error context callback to let us supply a call-stack traceback
900  */
901 static void
902 plpgsql_exec_error_callback(void *arg)
903 {
904         PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
905
906         /* if we are doing RAISE, don't report its location */
907         if (estate->err_text == raise_skip_msg)
908                 return;
909
910         if (estate->err_text != NULL)
911         {
912                 /*
913                  * We don't expend the cycles to run gettext() on err_text unless we
914                  * actually need it.  Therefore, places that set up err_text should
915                  * use gettext_noop() to ensure the strings get recorded in the
916                  * message dictionary.
917                  *
918                  * If both err_text and err_stmt are set, use the err_text as
919                  * description, but report the err_stmt's line number.  When err_stmt
920                  * is not set, we're in function entry/exit, or some such place not
921                  * attached to a specific line number.
922                  */
923                 if (estate->err_stmt != NULL)
924                 {
925                         /*
926                          * translator: last %s is a phrase such as "during statement block
927                          * local variable initialization"
928                          */
929                         errcontext("PL/pgSQL function %s line %d %s",
930                                            estate->func->fn_signature,
931                                            estate->err_stmt->lineno,
932                                            _(estate->err_text));
933                 }
934                 else
935                 {
936                         /*
937                          * translator: last %s is a phrase such as "while storing call
938                          * arguments into local variables"
939                          */
940                         errcontext("PL/pgSQL function %s %s",
941                                            estate->func->fn_signature,
942                                            _(estate->err_text));
943                 }
944         }
945         else if (estate->err_stmt != NULL)
946         {
947                 /* translator: last %s is a plpgsql statement type name */
948                 errcontext("PL/pgSQL function %s line %d at %s",
949                                    estate->func->fn_signature,
950                                    estate->err_stmt->lineno,
951                                    plpgsql_stmt_typename(estate->err_stmt));
952         }
953         else
954                 errcontext("PL/pgSQL function %s",
955                                    estate->func->fn_signature);
956 }
957
958
959 /* ----------
960  * Support function for initializing local execution variables
961  * ----------
962  */
963 static PLpgSQL_datum *
964 copy_plpgsql_datum(PLpgSQL_datum *datum)
965 {
966         PLpgSQL_datum *result;
967
968         switch (datum->dtype)
969         {
970                 case PLPGSQL_DTYPE_VAR:
971                         {
972                                 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
973
974                                 memcpy(new, datum, sizeof(PLpgSQL_var));
975                                 /* Ensure the value is null (possibly not needed?) */
976                                 new->value = 0;
977                                 new->isnull = true;
978                                 new->freeval = false;
979
980                                 result = (PLpgSQL_datum *) new;
981                         }
982                         break;
983
984                 case PLPGSQL_DTYPE_REC:
985                         {
986                                 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
987
988                                 memcpy(new, datum, sizeof(PLpgSQL_rec));
989                                 /* Ensure the value is null (possibly not needed?) */
990                                 new->tup = NULL;
991                                 new->tupdesc = NULL;
992                                 new->freetup = false;
993                                 new->freetupdesc = false;
994
995                                 result = (PLpgSQL_datum *) new;
996                         }
997                         break;
998
999                 case PLPGSQL_DTYPE_ROW:
1000                 case PLPGSQL_DTYPE_RECFIELD:
1001                 case PLPGSQL_DTYPE_ARRAYELEM:
1002
1003                         /*
1004                          * These datum records are read-only at runtime, so no need to
1005                          * copy them (well, ARRAYELEM contains some cached type data, but
1006                          * we'd just as soon centralize the caching anyway)
1007                          */
1008                         result = datum;
1009                         break;
1010
1011                 default:
1012                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
1013                         result = NULL;          /* keep compiler quiet */
1014                         break;
1015         }
1016
1017         return result;
1018 }
1019
1020
1021 static bool
1022 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
1023 {
1024         for (; cond != NULL; cond = cond->next)
1025         {
1026                 int                     sqlerrstate = cond->sqlerrstate;
1027
1028                 /*
1029                  * OTHERS matches everything *except* query-canceled; if you're
1030                  * foolish enough, you can match that explicitly.
1031                  */
1032                 if (sqlerrstate == 0)
1033                 {
1034                         if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
1035                                 return true;
1036                 }
1037                 /* Exact match? */
1038                 else if (edata->sqlerrcode == sqlerrstate)
1039                         return true;
1040                 /* Category match? */
1041                 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
1042                                  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
1043                         return true;
1044         }
1045         return false;
1046 }
1047
1048
1049 /* ----------
1050  * exec_stmt_block                      Execute a block of statements
1051  * ----------
1052  */
1053 static int
1054 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
1055 {
1056         volatile int rc = -1;
1057         int                     i;
1058         int                     n;
1059
1060         /*
1061          * First initialize all variables declared in this block
1062          */
1063         estate->err_text = gettext_noop("during statement block local variable initialization");
1064
1065         for (i = 0; i < block->n_initvars; i++)
1066         {
1067                 n = block->initvarnos[i];
1068
1069                 switch (estate->datums[n]->dtype)
1070                 {
1071                         case PLPGSQL_DTYPE_VAR:
1072                                 {
1073                                         PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
1074
1075                                         /* free any old value, in case re-entering block */
1076                                         free_var(var);
1077
1078                                         /* Initially it contains a NULL */
1079                                         var->value = (Datum) 0;
1080                                         var->isnull = true;
1081
1082                                         if (var->default_val == NULL)
1083                                         {
1084                                                 /*
1085                                                  * If needed, give the datatype a chance to reject
1086                                                  * NULLs, by assigning a NULL to the variable. We
1087                                                  * claim the value is of type UNKNOWN, not the var's
1088                                                  * datatype, else coercion will be skipped. (Do this
1089                                                  * before the notnull check to be consistent with
1090                                                  * exec_assign_value.)
1091                                                  */
1092                                                 if (var->datatype->typtype == TYPTYPE_DOMAIN)
1093                                                         exec_assign_value(estate,
1094                                                                                           (PLpgSQL_datum *) var,
1095                                                                                           (Datum) 0,
1096                                                                                           true,
1097                                                                                           UNKNOWNOID,
1098                                                                                           -1);
1099
1100                                                 if (var->notnull)
1101                                                         ereport(ERROR,
1102                                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1103                                                                          errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
1104                                                                                         var->refname)));
1105                                         }
1106                                         else
1107                                         {
1108                                                 exec_assign_expr(estate, (PLpgSQL_datum *) var,
1109                                                                                  var->default_val);
1110                                         }
1111                                 }
1112                                 break;
1113
1114                         case PLPGSQL_DTYPE_REC:
1115                                 {
1116                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
1117
1118                                         if (rec->freetup)
1119                                         {
1120                                                 heap_freetuple(rec->tup);
1121                                                 rec->freetup = false;
1122                                         }
1123                                         if (rec->freetupdesc)
1124                                         {
1125                                                 FreeTupleDesc(rec->tupdesc);
1126                                                 rec->freetupdesc = false;
1127                                         }
1128                                         rec->tup = NULL;
1129                                         rec->tupdesc = NULL;
1130                                 }
1131                                 break;
1132
1133                         case PLPGSQL_DTYPE_RECFIELD:
1134                         case PLPGSQL_DTYPE_ARRAYELEM:
1135                                 break;
1136
1137                         default:
1138                                 elog(ERROR, "unrecognized dtype: %d",
1139                                          estate->datums[n]->dtype);
1140                 }
1141         }
1142
1143         if (block->exceptions)
1144         {
1145                 /*
1146                  * Execute the statements in the block's body inside a sub-transaction
1147                  */
1148                 MemoryContext oldcontext = CurrentMemoryContext;
1149                 ResourceOwner oldowner = CurrentResourceOwner;
1150                 ExprContext *old_eval_econtext = estate->eval_econtext;
1151                 ErrorData  *save_cur_error = estate->cur_error;
1152
1153                 estate->err_text = gettext_noop("during statement block entry");
1154
1155                 BeginInternalSubTransaction(NULL);
1156                 /* Want to run statements inside function's memory context */
1157                 MemoryContextSwitchTo(oldcontext);
1158
1159                 PG_TRY();
1160                 {
1161                         /*
1162                          * We need to run the block's statements with a new eval_econtext
1163                          * that belongs to the current subtransaction; if we try to use
1164                          * the outer econtext then ExprContext shutdown callbacks will be
1165                          * called at the wrong times.
1166                          */
1167                         plpgsql_create_econtext(estate);
1168
1169                         estate->err_text = NULL;
1170
1171                         /* Run the block's statements */
1172                         rc = exec_stmts(estate, block->body);
1173
1174                         estate->err_text = gettext_noop("during statement block exit");
1175
1176                         /*
1177                          * If the block ended with RETURN, we may need to copy the return
1178                          * value out of the subtransaction eval_context.  This is
1179                          * currently only needed for scalar result types --- rowtype
1180                          * values will always exist in the function's own memory context.
1181                          */
1182                         if (rc == PLPGSQL_RC_RETURN &&
1183                                 !estate->retisset &&
1184                                 !estate->retisnull &&
1185                                 estate->rettupdesc == NULL)
1186                         {
1187                                 int16           resTypLen;
1188                                 bool            resTypByVal;
1189
1190                                 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1191                                 estate->retval = datumCopy(estate->retval,
1192                                                                                    resTypByVal, resTypLen);
1193                         }
1194
1195                         /* Commit the inner transaction, return to outer xact context */
1196                         ReleaseCurrentSubTransaction();
1197                         MemoryContextSwitchTo(oldcontext);
1198                         CurrentResourceOwner = oldowner;
1199
1200                         /*
1201                          * Revert to outer eval_econtext.  (The inner one was
1202                          * automatically cleaned up during subxact exit.)
1203                          */
1204                         estate->eval_econtext = old_eval_econtext;
1205
1206                         /*
1207                          * AtEOSubXact_SPI() should not have popped any SPI context, but
1208                          * just in case it did, make sure we remain connected.
1209                          */
1210                         SPI_restore_connection();
1211                 }
1212                 PG_CATCH();
1213                 {
1214                         ErrorData  *edata;
1215                         ListCell   *e;
1216
1217                         estate->err_text = gettext_noop("during exception cleanup");
1218
1219                         /* Save error info */
1220                         MemoryContextSwitchTo(oldcontext);
1221                         edata = CopyErrorData();
1222                         FlushErrorState();
1223
1224                         /* Abort the inner transaction */
1225                         RollbackAndReleaseCurrentSubTransaction();
1226                         MemoryContextSwitchTo(oldcontext);
1227                         CurrentResourceOwner = oldowner;
1228
1229                         /* Revert to outer eval_econtext */
1230                         estate->eval_econtext = old_eval_econtext;
1231
1232                         /*
1233                          * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1234                          * will have left us in a disconnected state.  We need this hack
1235                          * to return to connected state.
1236                          */
1237                         SPI_restore_connection();
1238
1239                         /*
1240                          * Must clean up the econtext too.  However, any tuple table made
1241                          * in the subxact will have been thrown away by SPI during subxact
1242                          * abort, so we don't need to (and mustn't try to) free the
1243                          * eval_tuptable.
1244                          */
1245                         estate->eval_tuptable = NULL;
1246                         exec_eval_cleanup(estate);
1247
1248                         /* Look for a matching exception handler */
1249                         foreach(e, block->exceptions->exc_list)
1250                         {
1251                                 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1252
1253                                 if (exception_matches_conditions(edata, exception->conditions))
1254                                 {
1255                                         /*
1256                                          * Initialize the magic SQLSTATE and SQLERRM variables for
1257                                          * the exception block; this also frees values from any
1258                                          * prior use of the same exception. We needn't do this
1259                                          * until we have found a matching exception.
1260                                          */
1261                                         PLpgSQL_var *state_var;
1262                                         PLpgSQL_var *errm_var;
1263
1264                                         state_var = (PLpgSQL_var *)
1265                                                 estate->datums[block->exceptions->sqlstate_varno];
1266                                         errm_var = (PLpgSQL_var *)
1267                                                 estate->datums[block->exceptions->sqlerrm_varno];
1268
1269                                         assign_text_var(state_var,
1270                                                                         unpack_sql_state(edata->sqlerrcode));
1271                                         assign_text_var(errm_var, edata->message);
1272
1273                                         /*
1274                                          * Also set up cur_error so the error data is accessible
1275                                          * inside the handler.
1276                                          */
1277                                         estate->cur_error = edata;
1278
1279                                         estate->err_text = NULL;
1280
1281                                         rc = exec_stmts(estate, exception->action);
1282
1283                                         break;
1284                                 }
1285                         }
1286
1287                         /*
1288                          * Restore previous state of cur_error, whether or not we executed
1289                          * a handler.  This is needed in case an error got thrown from
1290                          * some inner block's exception handler.
1291                          */
1292                         estate->cur_error = save_cur_error;
1293
1294                         /* If no match found, re-throw the error */
1295                         if (e == NULL)
1296                                 ReThrowError(edata);
1297                         else
1298                                 FreeErrorData(edata);
1299                 }
1300                 PG_END_TRY();
1301
1302                 Assert(save_cur_error == estate->cur_error);
1303         }
1304         else
1305         {
1306                 /*
1307                  * Just execute the statements in the block's body
1308                  */
1309                 estate->err_text = NULL;
1310
1311                 rc = exec_stmts(estate, block->body);
1312         }
1313
1314         estate->err_text = NULL;
1315
1316         /*
1317          * Handle the return code.
1318          */
1319         switch (rc)
1320         {
1321                 case PLPGSQL_RC_OK:
1322                 case PLPGSQL_RC_RETURN:
1323                 case PLPGSQL_RC_CONTINUE:
1324                         return rc;
1325
1326                 case PLPGSQL_RC_EXIT:
1327
1328                         /*
1329                          * This is intentionally different from the handling of RC_EXIT
1330                          * for loops: to match a block, we require a match by label.
1331                          */
1332                         if (estate->exitlabel == NULL)
1333                                 return PLPGSQL_RC_EXIT;
1334                         if (block->label == NULL)
1335                                 return PLPGSQL_RC_EXIT;
1336                         if (strcmp(block->label, estate->exitlabel) != 0)
1337                                 return PLPGSQL_RC_EXIT;
1338                         estate->exitlabel = NULL;
1339                         return PLPGSQL_RC_OK;
1340
1341                 default:
1342                         elog(ERROR, "unrecognized rc: %d", rc);
1343         }
1344
1345         return PLPGSQL_RC_OK;
1346 }
1347
1348
1349 /* ----------
1350  * exec_stmts                   Iterate over a list of statements
1351  *                              as long as their return code is OK
1352  * ----------
1353  */
1354 static int
1355 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1356 {
1357         ListCell   *s;
1358
1359         if (stmts == NIL)
1360         {
1361                 /*
1362                  * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1363                  * statement.  This prevents hangup in a tight loop if, for instance,
1364                  * there is a LOOP construct with an empty body.
1365                  */
1366                 CHECK_FOR_INTERRUPTS();
1367                 return PLPGSQL_RC_OK;
1368         }
1369
1370         foreach(s, stmts)
1371         {
1372                 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1373                 int                     rc = exec_stmt(estate, stmt);
1374
1375                 if (rc != PLPGSQL_RC_OK)
1376                         return rc;
1377         }
1378
1379         return PLPGSQL_RC_OK;
1380 }
1381
1382
1383 /* ----------
1384  * exec_stmt                    Distribute one statement to the statements
1385  *                              type specific execution function.
1386  * ----------
1387  */
1388 static int
1389 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1390 {
1391         PLpgSQL_stmt *save_estmt;
1392         int                     rc = -1;
1393
1394         save_estmt = estate->err_stmt;
1395         estate->err_stmt = stmt;
1396
1397         /* Let the plugin know that we are about to execute this statement */
1398         if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1399                 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1400
1401         CHECK_FOR_INTERRUPTS();
1402
1403         switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1404         {
1405                 case PLPGSQL_STMT_BLOCK:
1406                         rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1407                         break;
1408
1409                 case PLPGSQL_STMT_ASSIGN:
1410                         rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1411                         break;
1412
1413                 case PLPGSQL_STMT_PERFORM:
1414                         rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1415                         break;
1416
1417                 case PLPGSQL_STMT_GETDIAG:
1418                         rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1419                         break;
1420
1421                 case PLPGSQL_STMT_IF:
1422                         rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1423                         break;
1424
1425                 case PLPGSQL_STMT_CASE:
1426                         rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1427                         break;
1428
1429                 case PLPGSQL_STMT_LOOP:
1430                         rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1431                         break;
1432
1433                 case PLPGSQL_STMT_WHILE:
1434                         rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1435                         break;
1436
1437                 case PLPGSQL_STMT_FORI:
1438                         rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1439                         break;
1440
1441                 case PLPGSQL_STMT_FORS:
1442                         rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1443                         break;
1444
1445                 case PLPGSQL_STMT_FORC:
1446                         rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1447                         break;
1448
1449                 case PLPGSQL_STMT_FOREACH_A:
1450                         rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
1451                         break;
1452
1453                 case PLPGSQL_STMT_EXIT:
1454                         rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1455                         break;
1456
1457                 case PLPGSQL_STMT_RETURN:
1458                         rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1459                         break;
1460
1461                 case PLPGSQL_STMT_RETURN_NEXT:
1462                         rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1463                         break;
1464
1465                 case PLPGSQL_STMT_RETURN_QUERY:
1466                         rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1467                         break;
1468
1469                 case PLPGSQL_STMT_RAISE:
1470                         rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1471                         break;
1472
1473                 case PLPGSQL_STMT_EXECSQL:
1474                         rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1475                         break;
1476
1477                 case PLPGSQL_STMT_DYNEXECUTE:
1478                         rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1479                         break;
1480
1481                 case PLPGSQL_STMT_DYNFORS:
1482                         rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1483                         break;
1484
1485                 case PLPGSQL_STMT_OPEN:
1486                         rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1487                         break;
1488
1489                 case PLPGSQL_STMT_FETCH:
1490                         rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1491                         break;
1492
1493                 case PLPGSQL_STMT_CLOSE:
1494                         rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1495                         break;
1496
1497                 default:
1498                         estate->err_stmt = save_estmt;
1499                         elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1500         }
1501
1502         /* Let the plugin know that we have finished executing this statement */
1503         if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1504                 ((*plugin_ptr)->stmt_end) (estate, stmt);
1505
1506         estate->err_stmt = save_estmt;
1507
1508         return rc;
1509 }
1510
1511
1512 /* ----------
1513  * exec_stmt_assign                     Evaluate an expression and
1514  *                                      put the result into a variable.
1515  * ----------
1516  */
1517 static int
1518 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1519 {
1520         Assert(stmt->varno >= 0);
1521
1522         exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1523
1524         return PLPGSQL_RC_OK;
1525 }
1526
1527 /* ----------
1528  * exec_stmt_perform            Evaluate query and discard result (but set
1529  *                                                      FOUND depending on whether at least one row
1530  *                                                      was returned).
1531  * ----------
1532  */
1533 static int
1534 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1535 {
1536         PLpgSQL_expr *expr = stmt->expr;
1537
1538         (void) exec_run_select(estate, expr, 0, NULL);
1539         exec_set_found(estate, (estate->eval_processed != 0));
1540         exec_eval_cleanup(estate);
1541
1542         return PLPGSQL_RC_OK;
1543 }
1544
1545 /* ----------
1546  * exec_stmt_getdiag                                    Put internal PG information into
1547  *                                                                              specified variables.
1548  * ----------
1549  */
1550 static int
1551 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1552 {
1553         ListCell   *lc;
1554
1555         /*
1556          * GET STACKED DIAGNOSTICS is only valid inside an exception handler.
1557          *
1558          * Note: we trust the grammar to have disallowed the relevant item kinds
1559          * if not is_stacked, otherwise we'd dump core below.
1560          */
1561         if (stmt->is_stacked && estate->cur_error == NULL)
1562                 ereport(ERROR,
1563                 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
1564                  errmsg("GET STACKED DIAGNOSTICS cannot be used outside an exception handler")));
1565
1566         foreach(lc, stmt->diag_items)
1567         {
1568                 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1569                 PLpgSQL_datum *var = estate->datums[diag_item->target];
1570
1571                 switch (diag_item->kind)
1572                 {
1573                         case PLPGSQL_GETDIAG_ROW_COUNT:
1574                                 exec_assign_value(estate, var,
1575                                                                   UInt32GetDatum(estate->eval_processed),
1576                                                                   false, INT4OID, -1);
1577                                 break;
1578
1579                         case PLPGSQL_GETDIAG_RESULT_OID:
1580                                 exec_assign_value(estate, var,
1581                                                                   ObjectIdGetDatum(estate->eval_lastoid),
1582                                                                   false, OIDOID, -1);
1583                                 break;
1584
1585                         case PLPGSQL_GETDIAG_ERROR_CONTEXT:
1586                                 exec_assign_c_string(estate, var,
1587                                                                          estate->cur_error->context);
1588                                 break;
1589
1590                         case PLPGSQL_GETDIAG_ERROR_DETAIL:
1591                                 exec_assign_c_string(estate, var,
1592                                                                          estate->cur_error->detail);
1593                                 break;
1594
1595                         case PLPGSQL_GETDIAG_ERROR_HINT:
1596                                 exec_assign_c_string(estate, var,
1597                                                                          estate->cur_error->hint);
1598                                 break;
1599
1600                         case PLPGSQL_GETDIAG_RETURNED_SQLSTATE:
1601                                 exec_assign_c_string(estate, var,
1602                                                         unpack_sql_state(estate->cur_error->sqlerrcode));
1603                                 break;
1604
1605                         case PLPGSQL_GETDIAG_COLUMN_NAME:
1606                                 exec_assign_c_string(estate, var,
1607                                                                          estate->cur_error->column_name);
1608                                 break;
1609
1610                         case PLPGSQL_GETDIAG_CONSTRAINT_NAME:
1611                                 exec_assign_c_string(estate, var,
1612                                                                          estate->cur_error->constraint_name);
1613                                 break;
1614
1615                         case PLPGSQL_GETDIAG_DATATYPE_NAME:
1616                                 exec_assign_c_string(estate, var,
1617                                                                          estate->cur_error->datatype_name);
1618                                 break;
1619
1620                         case PLPGSQL_GETDIAG_MESSAGE_TEXT:
1621                                 exec_assign_c_string(estate, var,
1622                                                                          estate->cur_error->message);
1623                                 break;
1624
1625                         case PLPGSQL_GETDIAG_TABLE_NAME:
1626                                 exec_assign_c_string(estate, var,
1627                                                                          estate->cur_error->table_name);
1628                                 break;
1629
1630                         case PLPGSQL_GETDIAG_SCHEMA_NAME:
1631                                 exec_assign_c_string(estate, var,
1632                                                                          estate->cur_error->schema_name);
1633                                 break;
1634
1635                         case PLPGSQL_GETDIAG_CONTEXT:
1636                                 {
1637                                         char       *contextstackstr = GetErrorContextStack();
1638
1639                                         exec_assign_c_string(estate, var, contextstackstr);
1640
1641                                         pfree(contextstackstr);
1642                                 }
1643                                 break;
1644
1645                         default:
1646                                 elog(ERROR, "unrecognized diagnostic item kind: %d",
1647                                          diag_item->kind);
1648                 }
1649         }
1650
1651         return PLPGSQL_RC_OK;
1652 }
1653
1654 /* ----------
1655  * exec_stmt_if                         Evaluate a bool expression and
1656  *                                      execute the true or false body
1657  *                                      conditionally.
1658  * ----------
1659  */
1660 static int
1661 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1662 {
1663         bool            value;
1664         bool            isnull;
1665         ListCell   *lc;
1666
1667         value = exec_eval_boolean(estate, stmt->cond, &isnull);
1668         exec_eval_cleanup(estate);
1669         if (!isnull && value)
1670                 return exec_stmts(estate, stmt->then_body);
1671
1672         foreach(lc, stmt->elsif_list)
1673         {
1674                 PLpgSQL_if_elsif *elif = (PLpgSQL_if_elsif *) lfirst(lc);
1675
1676                 value = exec_eval_boolean(estate, elif->cond, &isnull);
1677                 exec_eval_cleanup(estate);
1678                 if (!isnull && value)
1679                         return exec_stmts(estate, elif->stmts);
1680         }
1681
1682         return exec_stmts(estate, stmt->else_body);
1683 }
1684
1685
1686 /*-----------
1687  * exec_stmt_case
1688  *-----------
1689  */
1690 static int
1691 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1692 {
1693         PLpgSQL_var *t_var = NULL;
1694         bool            isnull;
1695         ListCell   *l;
1696
1697         if (stmt->t_expr != NULL)
1698         {
1699                 /* simple case */
1700                 Datum           t_val;
1701                 Oid                     t_typoid;
1702                 int32           t_typmod;
1703
1704                 t_val = exec_eval_expr(estate, stmt->t_expr,
1705                                                            &isnull, &t_typoid, &t_typmod);
1706
1707                 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1708
1709                 /*
1710                  * When expected datatype is different from real, change it. Note that
1711                  * what we're modifying here is an execution copy of the datum, so
1712                  * this doesn't affect the originally stored function parse tree.
1713                  */
1714                 if (t_var->datatype->typoid != t_typoid ||
1715                         t_var->datatype->atttypmod != t_typmod)
1716                         t_var->datatype = plpgsql_build_datatype(t_typoid,
1717                                                                                                          t_typmod,
1718                                                                                    estate->func->fn_input_collation);
1719
1720                 /* now we can assign to the variable */
1721                 exec_assign_value(estate,
1722                                                   (PLpgSQL_datum *) t_var,
1723                                                   t_val,
1724                                                   isnull,
1725                                                   t_typoid,
1726                                                   t_typmod);
1727
1728                 exec_eval_cleanup(estate);
1729         }
1730
1731         /* Now search for a successful WHEN clause */
1732         foreach(l, stmt->case_when_list)
1733         {
1734                 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1735                 bool            value;
1736
1737                 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1738                 exec_eval_cleanup(estate);
1739                 if (!isnull && value)
1740                 {
1741                         /* Found it */
1742
1743                         /* We can now discard any value we had for the temp variable */
1744                         if (t_var != NULL)
1745                         {
1746                                 free_var(t_var);
1747                                 t_var->value = (Datum) 0;
1748                                 t_var->isnull = true;
1749                         }
1750
1751                         /* Evaluate the statement(s), and we're done */
1752                         return exec_stmts(estate, cwt->stmts);
1753                 }
1754         }
1755
1756         /* We can now discard any value we had for the temp variable */
1757         if (t_var != NULL)
1758         {
1759                 free_var(t_var);
1760                 t_var->value = (Datum) 0;
1761                 t_var->isnull = true;
1762         }
1763
1764         /* SQL2003 mandates this error if there was no ELSE clause */
1765         if (!stmt->have_else)
1766                 ereport(ERROR,
1767                                 (errcode(ERRCODE_CASE_NOT_FOUND),
1768                                  errmsg("case not found"),
1769                                  errhint("CASE statement is missing ELSE part.")));
1770
1771         /* Evaluate the ELSE statements, and we're done */
1772         return exec_stmts(estate, stmt->else_stmts);
1773 }
1774
1775
1776 /* ----------
1777  * exec_stmt_loop                       Loop over statements until
1778  *                                      an exit occurs.
1779  * ----------
1780  */
1781 static int
1782 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1783 {
1784         for (;;)
1785         {
1786                 int                     rc = exec_stmts(estate, stmt->body);
1787
1788                 switch (rc)
1789                 {
1790                         case PLPGSQL_RC_OK:
1791                                 break;
1792
1793                         case PLPGSQL_RC_EXIT:
1794                                 if (estate->exitlabel == NULL)
1795                                         return PLPGSQL_RC_OK;
1796                                 if (stmt->label == NULL)
1797                                         return PLPGSQL_RC_EXIT;
1798                                 if (strcmp(stmt->label, estate->exitlabel) != 0)
1799                                         return PLPGSQL_RC_EXIT;
1800                                 estate->exitlabel = NULL;
1801                                 return PLPGSQL_RC_OK;
1802
1803                         case PLPGSQL_RC_CONTINUE:
1804                                 if (estate->exitlabel == NULL)
1805                                         /* anonymous continue, so re-run the loop */
1806                                         break;
1807                                 else if (stmt->label != NULL &&
1808                                                  strcmp(stmt->label, estate->exitlabel) == 0)
1809                                         /* label matches named continue, so re-run loop */
1810                                         estate->exitlabel = NULL;
1811                                 else
1812                                         /* label doesn't match named continue, so propagate upward */
1813                                         return PLPGSQL_RC_CONTINUE;
1814                                 break;
1815
1816                         case PLPGSQL_RC_RETURN:
1817                                 return rc;
1818
1819                         default:
1820                                 elog(ERROR, "unrecognized rc: %d", rc);
1821                 }
1822         }
1823 }
1824
1825
1826 /* ----------
1827  * exec_stmt_while                      Loop over statements as long
1828  *                                      as an expression evaluates to
1829  *                                      true or an exit occurs.
1830  * ----------
1831  */
1832 static int
1833 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1834 {
1835         for (;;)
1836         {
1837                 int                     rc;
1838                 bool            value;
1839                 bool            isnull;
1840
1841                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1842                 exec_eval_cleanup(estate);
1843
1844                 if (isnull || !value)
1845                         break;
1846
1847                 rc = exec_stmts(estate, stmt->body);
1848
1849                 switch (rc)
1850                 {
1851                         case PLPGSQL_RC_OK:
1852                                 break;
1853
1854                         case PLPGSQL_RC_EXIT:
1855                                 if (estate->exitlabel == NULL)
1856                                         return PLPGSQL_RC_OK;
1857                                 if (stmt->label == NULL)
1858                                         return PLPGSQL_RC_EXIT;
1859                                 if (strcmp(stmt->label, estate->exitlabel) != 0)
1860                                         return PLPGSQL_RC_EXIT;
1861                                 estate->exitlabel = NULL;
1862                                 return PLPGSQL_RC_OK;
1863
1864                         case PLPGSQL_RC_CONTINUE:
1865                                 if (estate->exitlabel == NULL)
1866                                         /* anonymous continue, so re-run loop */
1867                                         break;
1868                                 else if (stmt->label != NULL &&
1869                                                  strcmp(stmt->label, estate->exitlabel) == 0)
1870                                         /* label matches named continue, so re-run loop */
1871                                         estate->exitlabel = NULL;
1872                                 else
1873                                         /* label doesn't match named continue, propagate upward */
1874                                         return PLPGSQL_RC_CONTINUE;
1875                                 break;
1876
1877                         case PLPGSQL_RC_RETURN:
1878                                 return rc;
1879
1880                         default:
1881                                 elog(ERROR, "unrecognized rc: %d", rc);
1882                 }
1883         }
1884
1885         return PLPGSQL_RC_OK;
1886 }
1887
1888
1889 /* ----------
1890  * exec_stmt_fori                       Iterate an integer variable
1891  *                                      from a lower to an upper value
1892  *                                      incrementing or decrementing by the BY value
1893  * ----------
1894  */
1895 static int
1896 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1897 {
1898         PLpgSQL_var *var;
1899         Datum           value;
1900         bool            isnull;
1901         Oid                     valtype;
1902         int32           valtypmod;
1903         int32           loop_value;
1904         int32           end_value;
1905         int32           step_value;
1906         bool            found = false;
1907         int                     rc = PLPGSQL_RC_OK;
1908
1909         var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
1910
1911         /*
1912          * Get the value of the lower bound
1913          */
1914         value = exec_eval_expr(estate, stmt->lower,
1915                                                    &isnull, &valtype, &valtypmod);
1916         value = exec_cast_value(estate, value, &isnull,
1917                                                         valtype, valtypmod,
1918                                                         var->datatype->typoid,
1919                                                         var->datatype->atttypmod);
1920         if (isnull)
1921                 ereport(ERROR,
1922                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1923                                  errmsg("lower bound of FOR loop cannot be null")));
1924         loop_value = DatumGetInt32(value);
1925         exec_eval_cleanup(estate);
1926
1927         /*
1928          * Get the value of the upper bound
1929          */
1930         value = exec_eval_expr(estate, stmt->upper,
1931                                                    &isnull, &valtype, &valtypmod);
1932         value = exec_cast_value(estate, value, &isnull,
1933                                                         valtype, valtypmod,
1934                                                         var->datatype->typoid,
1935                                                         var->datatype->atttypmod);
1936         if (isnull)
1937                 ereport(ERROR,
1938                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1939                                  errmsg("upper bound of FOR loop cannot be null")));
1940         end_value = DatumGetInt32(value);
1941         exec_eval_cleanup(estate);
1942
1943         /*
1944          * Get the step value
1945          */
1946         if (stmt->step)
1947         {
1948                 value = exec_eval_expr(estate, stmt->step,
1949                                                            &isnull, &valtype, &valtypmod);
1950                 value = exec_cast_value(estate, value, &isnull,
1951                                                                 valtype, valtypmod,
1952                                                                 var->datatype->typoid,
1953                                                                 var->datatype->atttypmod);
1954                 if (isnull)
1955                         ereport(ERROR,
1956                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1957                                          errmsg("BY value of FOR loop cannot be null")));
1958                 step_value = DatumGetInt32(value);
1959                 exec_eval_cleanup(estate);
1960                 if (step_value <= 0)
1961                         ereport(ERROR,
1962                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1963                                   errmsg("BY value of FOR loop must be greater than zero")));
1964         }
1965         else
1966                 step_value = 1;
1967
1968         /*
1969          * Now do the loop
1970          */
1971         for (;;)
1972         {
1973                 /*
1974                  * Check against upper bound
1975                  */
1976                 if (stmt->reverse)
1977                 {
1978                         if (loop_value < end_value)
1979                                 break;
1980                 }
1981                 else
1982                 {
1983                         if (loop_value > end_value)
1984                                 break;
1985                 }
1986
1987                 found = true;                   /* looped at least once */
1988
1989                 /*
1990                  * Assign current value to loop var
1991                  */
1992                 var->value = Int32GetDatum(loop_value);
1993                 var->isnull = false;
1994
1995                 /*
1996                  * Execute the statements
1997                  */
1998                 rc = exec_stmts(estate, stmt->body);
1999
2000                 if (rc == PLPGSQL_RC_RETURN)
2001                         break;                          /* break out of the loop */
2002                 else if (rc == PLPGSQL_RC_EXIT)
2003                 {
2004                         if (estate->exitlabel == NULL)
2005                                 /* unlabelled exit, finish the current loop */
2006                                 rc = PLPGSQL_RC_OK;
2007                         else if (stmt->label != NULL &&
2008                                          strcmp(stmt->label, estate->exitlabel) == 0)
2009                         {
2010                                 /* labelled exit, matches the current stmt's label */
2011                                 estate->exitlabel = NULL;
2012                                 rc = PLPGSQL_RC_OK;
2013                         }
2014
2015                         /*
2016                          * otherwise, this is a labelled exit that does not match the
2017                          * current statement's label, if any: return RC_EXIT so that the
2018                          * EXIT continues to propagate up the stack.
2019                          */
2020                         break;
2021                 }
2022                 else if (rc == PLPGSQL_RC_CONTINUE)
2023                 {
2024                         if (estate->exitlabel == NULL)
2025                                 /* unlabelled continue, so re-run the current loop */
2026                                 rc = PLPGSQL_RC_OK;
2027                         else if (stmt->label != NULL &&
2028                                          strcmp(stmt->label, estate->exitlabel) == 0)
2029                         {
2030                                 /* label matches named continue, so re-run loop */
2031                                 estate->exitlabel = NULL;
2032                                 rc = PLPGSQL_RC_OK;
2033                         }
2034                         else
2035                         {
2036                                 /*
2037                                  * otherwise, this is a named continue that does not match the
2038                                  * current statement's label, if any: return RC_CONTINUE so
2039                                  * that the CONTINUE will propagate up the stack.
2040                                  */
2041                                 break;
2042                         }
2043                 }
2044
2045                 /*
2046                  * Increase/decrease loop value, unless it would overflow, in which
2047                  * case exit the loop.
2048                  */
2049                 if (stmt->reverse)
2050                 {
2051                         if ((int32) (loop_value - step_value) > loop_value)
2052                                 break;
2053                         loop_value -= step_value;
2054                 }
2055                 else
2056                 {
2057                         if ((int32) (loop_value + step_value) < loop_value)
2058                                 break;
2059                         loop_value += step_value;
2060                 }
2061         }
2062
2063         /*
2064          * Set the FOUND variable to indicate the result of executing the loop
2065          * (namely, whether we looped one or more times). This must be set here so
2066          * that it does not interfere with the value of the FOUND variable inside
2067          * the loop processing itself.
2068          */
2069         exec_set_found(estate, found);
2070
2071         return rc;
2072 }
2073
2074
2075 /* ----------
2076  * exec_stmt_fors                       Execute a query, assign each
2077  *                                      tuple to a record or row and
2078  *                                      execute a group of statements
2079  *                                      for it.
2080  * ----------
2081  */
2082 static int
2083 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
2084 {
2085         Portal          portal;
2086         int                     rc;
2087
2088         /*
2089          * Open the implicit cursor for the statement using exec_run_select
2090          */
2091         exec_run_select(estate, stmt->query, 0, &portal);
2092
2093         /*
2094          * Execute the loop
2095          */
2096         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
2097
2098         /*
2099          * Close the implicit cursor
2100          */
2101         SPI_cursor_close(portal);
2102
2103         return rc;
2104 }
2105
2106
2107 /* ----------
2108  * exec_stmt_forc                       Execute a loop for each row from a cursor.
2109  * ----------
2110  */
2111 static int
2112 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
2113 {
2114         PLpgSQL_var *curvar;
2115         char       *curname = NULL;
2116         PLpgSQL_expr *query;
2117         ParamListInfo paramLI;
2118         Portal          portal;
2119         int                     rc;
2120
2121         /* ----------
2122          * Get the cursor variable and if it has an assigned name, check
2123          * that it's not in use currently.
2124          * ----------
2125          */
2126         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2127         if (!curvar->isnull)
2128         {
2129                 curname = TextDatumGetCString(curvar->value);
2130                 if (SPI_cursor_find(curname) != NULL)
2131                         ereport(ERROR,
2132                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
2133                                          errmsg("cursor \"%s\" already in use", curname)));
2134         }
2135
2136         /* ----------
2137          * Open the cursor just like an OPEN command
2138          *
2139          * Note: parser should already have checked that statement supplies
2140          * args iff cursor needs them, but we check again to be safe.
2141          * ----------
2142          */
2143         if (stmt->argquery != NULL)
2144         {
2145                 /* ----------
2146                  * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
2147                  * statement to evaluate the args and put 'em into the
2148                  * internal row.
2149                  * ----------
2150                  */
2151                 PLpgSQL_stmt_execsql set_args;
2152
2153                 if (curvar->cursor_explicit_argrow < 0)
2154                         ereport(ERROR,
2155                                         (errcode(ERRCODE_SYNTAX_ERROR),
2156                                          errmsg("arguments given for cursor without arguments")));
2157
2158                 memset(&set_args, 0, sizeof(set_args));
2159                 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
2160                 set_args.lineno = stmt->lineno;
2161                 set_args.sqlstmt = stmt->argquery;
2162                 set_args.into = true;
2163                 /* XXX historically this has not been STRICT */
2164                 set_args.row = (PLpgSQL_row *)
2165                         (estate->datums[curvar->cursor_explicit_argrow]);
2166
2167                 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
2168                         elog(ERROR, "open cursor failed during argument processing");
2169         }
2170         else
2171         {
2172                 if (curvar->cursor_explicit_argrow >= 0)
2173                         ereport(ERROR,
2174                                         (errcode(ERRCODE_SYNTAX_ERROR),
2175                                          errmsg("arguments required for cursor")));
2176         }
2177
2178         query = curvar->cursor_explicit_expr;
2179         Assert(query);
2180
2181         if (query->plan == NULL)
2182                 exec_prepare_plan(estate, query, curvar->cursor_options);
2183
2184         /*
2185          * Set up ParamListInfo (hook function and possibly data values)
2186          */
2187         paramLI = setup_param_list(estate, query);
2188
2189         /*
2190          * Open the cursor (the paramlist will get copied into the portal)
2191          */
2192         portal = SPI_cursor_open_with_paramlist(curname, query->plan,
2193                                                                                         paramLI,
2194                                                                                         estate->readonly_func);
2195         if (portal == NULL)
2196                 elog(ERROR, "could not open cursor: %s",
2197                          SPI_result_code_string(SPI_result));
2198
2199         /* don't need paramlist any more */
2200         if (paramLI)
2201                 pfree(paramLI);
2202
2203         /*
2204          * If cursor variable was NULL, store the generated portal name in it
2205          */
2206         if (curname == NULL)
2207                 assign_text_var(curvar, portal->name);
2208
2209         /*
2210          * Execute the loop.  We can't prefetch because the cursor is accessible
2211          * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2212          */
2213         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2214
2215         /* ----------
2216          * Close portal, and restore cursor variable if it was initially NULL.
2217          * ----------
2218          */
2219         SPI_cursor_close(portal);
2220
2221         if (curname == NULL)
2222         {
2223                 free_var(curvar);
2224                 curvar->value = (Datum) 0;
2225                 curvar->isnull = true;
2226         }
2227
2228         if (curname)
2229                 pfree(curname);
2230
2231         return rc;
2232 }
2233
2234
2235 /* ----------
2236  * exec_stmt_foreach_a                  Loop over elements or slices of an array
2237  *
2238  * When looping over elements, the loop variable is the same type that the
2239  * array stores (eg: integer), when looping through slices, the loop variable
2240  * is an array of size and dimensions to match the size of the slice.
2241  * ----------
2242  */
2243 static int
2244 exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
2245 {
2246         ArrayType  *arr;
2247         Oid                     arrtype;
2248         int32           arrtypmod;
2249         PLpgSQL_datum *loop_var;
2250         Oid                     loop_var_elem_type;
2251         bool            found = false;
2252         int                     rc = PLPGSQL_RC_OK;
2253         ArrayIterator array_iterator;
2254         Oid                     iterator_result_type;
2255         int32           iterator_result_typmod;
2256         Datum           value;
2257         bool            isnull;
2258
2259         /* get the value of the array expression */
2260         value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype, &arrtypmod);
2261         if (isnull)
2262                 ereport(ERROR,
2263                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2264                                  errmsg("FOREACH expression must not be null")));
2265
2266         /* check the type of the expression - must be an array */
2267         if (!OidIsValid(get_element_type(arrtype)))
2268                 ereport(ERROR,
2269                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2270                                  errmsg("FOREACH expression must yield an array, not type %s",
2271                                                 format_type_be(arrtype))));
2272
2273         /*
2274          * We must copy the array, else it will disappear in exec_eval_cleanup.
2275          * This is annoying, but cleanup will certainly happen while running the
2276          * loop body, so we have little choice.
2277          */
2278         arr = DatumGetArrayTypePCopy(value);
2279
2280         /* Clean up any leftover temporary memory */
2281         exec_eval_cleanup(estate);
2282
2283         /* Slice dimension must be less than or equal to array dimension */
2284         if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
2285                 ereport(ERROR,
2286                                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2287                            errmsg("slice dimension (%d) is out of the valid range 0..%d",
2288                                           stmt->slice, ARR_NDIM(arr))));
2289
2290         /* Set up the loop variable and see if it is of an array type */
2291         loop_var = estate->datums[stmt->varno];
2292         if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
2293                 loop_var->dtype == PLPGSQL_DTYPE_ROW)
2294         {
2295                 /*
2296                  * Record/row variable is certainly not of array type, and might not
2297                  * be initialized at all yet, so don't try to get its type
2298                  */
2299                 loop_var_elem_type = InvalidOid;
2300         }
2301         else
2302                 loop_var_elem_type = get_element_type(exec_get_datum_type(estate,
2303                                                                                                                                   loop_var));
2304
2305         /*
2306          * Sanity-check the loop variable type.  We don't try very hard here, and
2307          * should not be too picky since it's possible that exec_assign_value can
2308          * coerce values of different types.  But it seems worthwhile to complain
2309          * if the array-ness of the loop variable is not right.
2310          */
2311         if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
2312                 ereport(ERROR,
2313                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2314                 errmsg("FOREACH ... SLICE loop variable must be of an array type")));
2315         if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
2316                 ereport(ERROR,
2317                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2318                           errmsg("FOREACH loop variable must not be of an array type")));
2319
2320         /* Create an iterator to step through the array */
2321         array_iterator = array_create_iterator(arr, stmt->slice);
2322
2323         /* Identify iterator result type */
2324         if (stmt->slice > 0)
2325         {
2326                 /* When slicing, nominal type of result is same as array type */
2327                 iterator_result_type = arrtype;
2328                 iterator_result_typmod = arrtypmod;
2329         }
2330         else
2331         {
2332                 /* Without slicing, results are individual array elements */
2333                 iterator_result_type = ARR_ELEMTYPE(arr);
2334                 iterator_result_typmod = arrtypmod;
2335         }
2336
2337         /* Iterate over the array elements or slices */
2338         while (array_iterate(array_iterator, &value, &isnull))
2339         {
2340                 found = true;                   /* looped at least once */
2341
2342                 /* Assign current element/slice to the loop variable */
2343                 exec_assign_value(estate, loop_var, value, isnull,
2344                                                   iterator_result_type, iterator_result_typmod);
2345
2346                 /* In slice case, value is temporary; must free it to avoid leakage */
2347                 if (stmt->slice > 0)
2348                         pfree(DatumGetPointer(value));
2349
2350                 /*
2351                  * Execute the statements
2352                  */
2353                 rc = exec_stmts(estate, stmt->body);
2354
2355                 /* Handle the return code */
2356                 if (rc == PLPGSQL_RC_RETURN)
2357                         break;                          /* break out of the loop */
2358                 else if (rc == PLPGSQL_RC_EXIT)
2359                 {
2360                         if (estate->exitlabel == NULL)
2361                                 /* unlabelled exit, finish the current loop */
2362                                 rc = PLPGSQL_RC_OK;
2363                         else if (stmt->label != NULL &&
2364                                          strcmp(stmt->label, estate->exitlabel) == 0)
2365                         {
2366                                 /* labelled exit, matches the current stmt's label */
2367                                 estate->exitlabel = NULL;
2368                                 rc = PLPGSQL_RC_OK;
2369                         }
2370
2371                         /*
2372                          * otherwise, this is a labelled exit that does not match the
2373                          * current statement's label, if any: return RC_EXIT so that the
2374                          * EXIT continues to propagate up the stack.
2375                          */
2376                         break;
2377                 }
2378                 else if (rc == PLPGSQL_RC_CONTINUE)
2379                 {
2380                         if (estate->exitlabel == NULL)
2381                                 /* unlabelled continue, so re-run the current loop */
2382                                 rc = PLPGSQL_RC_OK;
2383                         else if (stmt->label != NULL &&
2384                                          strcmp(stmt->label, estate->exitlabel) == 0)
2385                         {
2386                                 /* label matches named continue, so re-run loop */
2387                                 estate->exitlabel = NULL;
2388                                 rc = PLPGSQL_RC_OK;
2389                         }
2390                         else
2391                         {
2392                                 /*
2393                                  * otherwise, this is a named continue that does not match the
2394                                  * current statement's label, if any: return RC_CONTINUE so
2395                                  * that the CONTINUE will propagate up the stack.
2396                                  */
2397                                 break;
2398                         }
2399                 }
2400         }
2401
2402         /* Release temporary memory, including the array value */
2403         array_free_iterator(array_iterator);
2404         pfree(arr);
2405
2406         /*
2407          * Set the FOUND variable to indicate the result of executing the loop
2408          * (namely, whether we looped one or more times). This must be set here so
2409          * that it does not interfere with the value of the FOUND variable inside
2410          * the loop processing itself.
2411          */
2412         exec_set_found(estate, found);
2413
2414         return rc;
2415 }
2416
2417
2418 /* ----------
2419  * exec_stmt_exit                       Implements EXIT and CONTINUE
2420  *
2421  * This begins the process of exiting / restarting a loop.
2422  * ----------
2423  */
2424 static int
2425 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
2426 {
2427         /*
2428          * If the exit / continue has a condition, evaluate it
2429          */
2430         if (stmt->cond != NULL)
2431         {
2432                 bool            value;
2433                 bool            isnull;
2434
2435                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2436                 exec_eval_cleanup(estate);
2437                 if (isnull || value == false)
2438                         return PLPGSQL_RC_OK;
2439         }
2440
2441         estate->exitlabel = stmt->label;
2442         if (stmt->is_exit)
2443                 return PLPGSQL_RC_EXIT;
2444         else
2445                 return PLPGSQL_RC_CONTINUE;
2446 }
2447
2448
2449 /* ----------
2450  * exec_stmt_return                     Evaluate an expression and start
2451  *                                      returning from the function.
2452  * ----------
2453  */
2454 static int
2455 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
2456 {
2457         /*
2458          * If processing a set-returning PL/pgSQL function, the final RETURN
2459          * indicates that the function is finished producing tuples.  The rest of
2460          * the work will be done at the top level.
2461          */
2462         if (estate->retisset)
2463                 return PLPGSQL_RC_RETURN;
2464
2465         /* initialize for null result (possibly a tuple) */
2466         estate->retval = (Datum) 0;
2467         estate->rettupdesc = NULL;
2468         estate->retisnull = true;
2469
2470         /*
2471          * Special case path when the RETURN expression is a simple variable
2472          * reference; in particular, this path is always taken in functions with
2473          * one or more OUT parameters.
2474          */
2475         if (stmt->retvarno >= 0)
2476         {
2477                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2478
2479                 switch (retvar->dtype)
2480                 {
2481                         case PLPGSQL_DTYPE_VAR:
2482                                 {
2483                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2484
2485                                         estate->retval = var->value;
2486                                         estate->retisnull = var->isnull;
2487                                         estate->rettype = var->datatype->typoid;
2488                                 }
2489                                 break;
2490
2491                         case PLPGSQL_DTYPE_REC:
2492                                 {
2493                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2494
2495                                         if (HeapTupleIsValid(rec->tup))
2496                                         {
2497                                                 estate->retval = PointerGetDatum(rec->tup);
2498                                                 estate->rettupdesc = rec->tupdesc;
2499                                                 estate->retisnull = false;
2500                                         }
2501                                 }
2502                                 break;
2503
2504                         case PLPGSQL_DTYPE_ROW:
2505                                 {
2506                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2507
2508                                         Assert(row->rowtupdesc);
2509                                         estate->retval =
2510                                                 PointerGetDatum(make_tuple_from_row(estate, row,
2511                                                                                                                         row->rowtupdesc));
2512                                         if (DatumGetPointer(estate->retval) == NULL)            /* should not happen */
2513                                                 elog(ERROR, "row not compatible with its own tupdesc");
2514                                         estate->rettupdesc = row->rowtupdesc;
2515                                         estate->retisnull = false;
2516                                 }
2517                                 break;
2518
2519                         default:
2520                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2521                 }
2522
2523                 return PLPGSQL_RC_RETURN;
2524         }
2525
2526         if (stmt->expr != NULL)
2527         {
2528                 int32           rettypmod;
2529
2530                 estate->retval = exec_eval_expr(estate, stmt->expr,
2531                                                                                 &(estate->retisnull),
2532                                                                                 &(estate->rettype),
2533                                                                                 &rettypmod);
2534
2535                 if (estate->retistuple && !estate->retisnull)
2536                 {
2537                         /* Convert composite datum to a HeapTuple and TupleDesc */
2538                         HeapTuple       tuple;
2539                         TupleDesc       tupdesc;
2540
2541                         /* Source must be of RECORD or composite type */
2542                         if (!type_is_rowtype(estate->rettype))
2543                                 ereport(ERROR,
2544                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2545                                                  errmsg("cannot return non-composite value from function returning composite type")));
2546                         tuple = get_tuple_from_datum(estate->retval);
2547                         tupdesc = get_tupdesc_from_datum(estate->retval);
2548                         estate->retval = PointerGetDatum(tuple);
2549                         estate->rettupdesc = CreateTupleDescCopy(tupdesc);
2550                         ReleaseTupleDesc(tupdesc);
2551                 }
2552
2553                 return PLPGSQL_RC_RETURN;
2554         }
2555
2556         /*
2557          * Special hack for function returning VOID: instead of NULL, return a
2558          * non-null VOID value.  This is of dubious importance but is kept for
2559          * backwards compatibility.
2560          */
2561         if (estate->fn_rettype == VOIDOID)
2562         {
2563                 estate->retval = (Datum) 0;
2564                 estate->retisnull = false;
2565                 estate->rettype = VOIDOID;
2566         }
2567
2568         return PLPGSQL_RC_RETURN;
2569 }
2570
2571 /* ----------
2572  * exec_stmt_return_next                Evaluate an expression and add it to the
2573  *                                                              list of tuples returned by the current
2574  *                                                              SRF.
2575  * ----------
2576  */
2577 static int
2578 exec_stmt_return_next(PLpgSQL_execstate *estate,
2579                                           PLpgSQL_stmt_return_next *stmt)
2580 {
2581         TupleDesc       tupdesc;
2582         int                     natts;
2583         HeapTuple       tuple = NULL;
2584         bool            free_tuple = false;
2585
2586         if (!estate->retisset)
2587                 ereport(ERROR,
2588                                 (errcode(ERRCODE_SYNTAX_ERROR),
2589                                  errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2590
2591         if (estate->tuple_store == NULL)
2592                 exec_init_tuple_store(estate);
2593
2594         /* rettupdesc will be filled by exec_init_tuple_store */
2595         tupdesc = estate->rettupdesc;
2596         natts = tupdesc->natts;
2597
2598         /*
2599          * Special case path when the RETURN NEXT expression is a simple variable
2600          * reference; in particular, this path is always taken in functions with
2601          * one or more OUT parameters.
2602          */
2603         if (stmt->retvarno >= 0)
2604         {
2605                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2606
2607                 switch (retvar->dtype)
2608                 {
2609                         case PLPGSQL_DTYPE_VAR:
2610                                 {
2611                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2612                                         Datum           retval = var->value;
2613                                         bool            isNull = var->isnull;
2614
2615                                         if (natts != 1)
2616                                                 ereport(ERROR,
2617                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2618                                                 errmsg("wrong result type supplied in RETURN NEXT")));
2619
2620                                         /* coerce type if needed */
2621                                         retval = exec_cast_value(estate,
2622                                                                                          retval,
2623                                                                                          &isNull,
2624                                                                                          var->datatype->typoid,
2625                                                                                          var->datatype->atttypmod,
2626                                                                                          tupdesc->attrs[0]->atttypid,
2627                                                                                          tupdesc->attrs[0]->atttypmod);
2628
2629                                         tuplestore_putvalues(estate->tuple_store, tupdesc,
2630                                                                                  &retval, &isNull);
2631                                 }
2632                                 break;
2633
2634                         case PLPGSQL_DTYPE_REC:
2635                                 {
2636                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2637                                         TupleConversionMap *tupmap;
2638
2639                                         if (!HeapTupleIsValid(rec->tup))
2640                                                 ereport(ERROR,
2641                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2642                                                    errmsg("record \"%s\" is not assigned yet",
2643                                                                   rec->refname),
2644                                                 errdetail("The tuple structure of a not-yet-assigned"
2645                                                                   " record is indeterminate.")));
2646                                         tupmap = convert_tuples_by_position(rec->tupdesc,
2647                                                                                                                 tupdesc,
2648                                                                                                                 gettext_noop("wrong record type supplied in RETURN NEXT"));
2649                                         tuple = rec->tup;
2650                                         /* it might need conversion */
2651                                         if (tupmap)
2652                                         {
2653                                                 tuple = do_convert_tuple(tuple, tupmap);
2654                                                 free_conversion_map(tupmap);
2655                                                 free_tuple = true;
2656                                         }
2657                                 }
2658                                 break;
2659
2660                         case PLPGSQL_DTYPE_ROW:
2661                                 {
2662                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2663
2664                                         tuple = make_tuple_from_row(estate, row, tupdesc);
2665                                         if (tuple == NULL)
2666                                                 ereport(ERROR,
2667                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2668                                                 errmsg("wrong record type supplied in RETURN NEXT")));
2669                                         free_tuple = true;
2670                                 }
2671                                 break;
2672
2673                         default:
2674                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2675                                 break;
2676                 }
2677         }
2678         else if (stmt->expr)
2679         {
2680                 Datum           retval;
2681                 bool            isNull;
2682                 Oid                     rettype;
2683                 int32           rettypmod;
2684
2685                 retval = exec_eval_expr(estate,
2686                                                                 stmt->expr,
2687                                                                 &isNull,
2688                                                                 &rettype,
2689                                                                 &rettypmod);
2690
2691                 if (estate->retistuple)
2692                 {
2693                         /* Expression should be of RECORD or composite type */
2694                         if (!isNull)
2695                         {
2696                                 TupleDesc       retvaldesc;
2697                                 TupleConversionMap *tupmap;
2698
2699                                 if (!type_is_rowtype(rettype))
2700                                         ereport(ERROR,
2701                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
2702                                                          errmsg("cannot return non-composite value from function returning composite type")));
2703
2704                                 tuple = get_tuple_from_datum(retval);
2705                                 free_tuple = true;              /* tuple is always freshly palloc'd */
2706
2707                                 /* it might need conversion */
2708                                 retvaldesc = get_tupdesc_from_datum(retval);
2709                                 tupmap = convert_tuples_by_position(retvaldesc, tupdesc,
2710                                                                                                         gettext_noop("returned record type does not match expected record type"));
2711                                 if (tupmap)
2712                                 {
2713                                         HeapTuple       newtuple;
2714
2715                                         newtuple = do_convert_tuple(tuple, tupmap);
2716                                         free_conversion_map(tupmap);
2717                                         heap_freetuple(tuple);
2718                                         tuple = newtuple;
2719                                 }
2720                                 ReleaseTupleDesc(retvaldesc);
2721                                 /* tuple will be stored into tuplestore below */
2722                         }
2723                         else
2724                         {
2725                                 /* Composite NULL --- store a row of nulls */
2726                                 Datum      *nulldatums;
2727                                 bool       *nullflags;
2728
2729                                 nulldatums = (Datum *) palloc0(natts * sizeof(Datum));
2730                                 nullflags = (bool *) palloc(natts * sizeof(bool));
2731                                 memset(nullflags, true, natts * sizeof(bool));
2732                                 tuplestore_putvalues(estate->tuple_store, tupdesc,
2733                                                                          nulldatums, nullflags);
2734                                 pfree(nulldatums);
2735                                 pfree(nullflags);
2736                         }
2737                 }
2738                 else
2739                 {
2740                         /* Simple scalar result */
2741                         if (natts != 1)
2742                                 ereport(ERROR,
2743                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2744                                            errmsg("wrong result type supplied in RETURN NEXT")));
2745
2746                         /* coerce type if needed */
2747                         retval = exec_cast_value(estate,
2748                                                                          retval,
2749                                                                          &isNull,
2750                                                                          rettype,
2751                                                                          rettypmod,
2752                                                                          tupdesc->attrs[0]->atttypid,
2753                                                                          tupdesc->attrs[0]->atttypmod);
2754
2755                         tuplestore_putvalues(estate->tuple_store, tupdesc,
2756                                                                  &retval, &isNull);
2757                 }
2758         }
2759         else
2760         {
2761                 ereport(ERROR,
2762                                 (errcode(ERRCODE_SYNTAX_ERROR),
2763                                  errmsg("RETURN NEXT must have a parameter")));
2764         }
2765
2766         if (HeapTupleIsValid(tuple))
2767         {
2768                 tuplestore_puttuple(estate->tuple_store, tuple);
2769
2770                 if (free_tuple)
2771                         heap_freetuple(tuple);
2772         }
2773
2774         exec_eval_cleanup(estate);
2775
2776         return PLPGSQL_RC_OK;
2777 }
2778
2779 /* ----------
2780  * exec_stmt_return_query               Evaluate a query and add it to the
2781  *                                                              list of tuples returned by the current
2782  *                                                              SRF.
2783  * ----------
2784  */
2785 static int
2786 exec_stmt_return_query(PLpgSQL_execstate *estate,
2787                                            PLpgSQL_stmt_return_query *stmt)
2788 {
2789         Portal          portal;
2790         uint32          processed = 0;
2791         TupleConversionMap *tupmap;
2792
2793         if (!estate->retisset)
2794                 ereport(ERROR,
2795                                 (errcode(ERRCODE_SYNTAX_ERROR),
2796                                  errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2797
2798         if (estate->tuple_store == NULL)
2799                 exec_init_tuple_store(estate);
2800
2801         if (stmt->query != NULL)
2802         {
2803                 /* static query */
2804                 exec_run_select(estate, stmt->query, 0, &portal);
2805         }
2806         else
2807         {
2808                 /* RETURN QUERY EXECUTE */
2809                 Assert(stmt->dynquery != NULL);
2810                 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2811                                                                                    stmt->params, NULL, 0);
2812         }
2813
2814         tupmap = convert_tuples_by_position(portal->tupDesc,
2815                                                                                 estate->rettupdesc,
2816          gettext_noop("structure of query does not match function result type"));
2817
2818         while (true)
2819         {
2820                 int                     i;
2821
2822                 SPI_cursor_fetch(portal, true, 50);
2823                 if (SPI_processed == 0)
2824                         break;
2825
2826                 for (i = 0; i < SPI_processed; i++)
2827                 {
2828                         HeapTuple       tuple = SPI_tuptable->vals[i];
2829
2830                         if (tupmap)
2831                                 tuple = do_convert_tuple(tuple, tupmap);
2832                         tuplestore_puttuple(estate->tuple_store, tuple);
2833                         if (tupmap)
2834                                 heap_freetuple(tuple);
2835                         processed++;
2836                 }
2837
2838                 SPI_freetuptable(SPI_tuptable);
2839         }
2840
2841         if (tupmap)
2842                 free_conversion_map(tupmap);
2843
2844         SPI_freetuptable(SPI_tuptable);
2845         SPI_cursor_close(portal);
2846
2847         estate->eval_processed = processed;
2848         exec_set_found(estate, processed != 0);
2849
2850         return PLPGSQL_RC_OK;
2851 }
2852
2853 static void
2854 exec_init_tuple_store(PLpgSQL_execstate *estate)
2855 {
2856         ReturnSetInfo *rsi = estate->rsi;
2857         MemoryContext oldcxt;
2858         ResourceOwner oldowner;
2859
2860         /*
2861          * Check caller can handle a set result in the way we want
2862          */
2863         if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2864                 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2865                 rsi->expectedDesc == NULL)
2866                 ereport(ERROR,
2867                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2868                                  errmsg("set-valued function called in context that cannot accept a set")));
2869
2870         /*
2871          * Switch to the right memory context and resource owner for storing the
2872          * tuplestore for return set. If we're within a subtransaction opened for
2873          * an exception-block, for example, we must still create the tuplestore in
2874          * the resource owner that was active when this function was entered, and
2875          * not in the subtransaction resource owner.
2876          */
2877         oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2878         oldowner = CurrentResourceOwner;
2879         CurrentResourceOwner = estate->tuple_store_owner;
2880
2881         estate->tuple_store =
2882                 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
2883                                                           false, work_mem);
2884
2885         CurrentResourceOwner = oldowner;
2886         MemoryContextSwitchTo(oldcxt);
2887
2888         estate->rettupdesc = rsi->expectedDesc;
2889 }
2890
2891 #define SET_RAISE_OPTION_TEXT(opt, name) \
2892 do { \
2893         if (opt) \
2894                 ereport(ERROR, \
2895                                 (errcode(ERRCODE_SYNTAX_ERROR), \
2896                                  errmsg("RAISE option already specified: %s", \
2897                                                 name))); \
2898         opt = pstrdup(extval); \
2899 } while (0)
2900
2901 /* ----------
2902  * exec_stmt_raise                      Build a message and throw it with elog()
2903  * ----------
2904  */
2905 static int
2906 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2907 {
2908         int                     err_code = 0;
2909         char       *condname = NULL;
2910         char       *err_message = NULL;
2911         char       *err_detail = NULL;
2912         char       *err_hint = NULL;
2913         char       *err_column = NULL;
2914         char       *err_constraint = NULL;
2915         char       *err_datatype = NULL;
2916         char       *err_table = NULL;
2917         char       *err_schema = NULL;
2918         ListCell   *lc;
2919
2920         /* RAISE with no parameters: re-throw current exception */
2921         if (stmt->condname == NULL && stmt->message == NULL &&
2922                 stmt->options == NIL)
2923         {
2924                 if (estate->cur_error != NULL)
2925                         ReThrowError(estate->cur_error);
2926                 /* oops, we're not inside a handler */
2927                 ereport(ERROR,
2928                 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
2929                  errmsg("RAISE without parameters cannot be used outside an exception handler")));
2930         }
2931
2932         if (stmt->condname)
2933         {
2934                 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2935                 condname = pstrdup(stmt->condname);
2936         }
2937
2938         if (stmt->message)
2939         {
2940                 StringInfoData ds;
2941                 ListCell   *current_param;
2942                 char       *cp;
2943
2944                 initStringInfo(&ds);
2945                 current_param = list_head(stmt->params);
2946
2947                 for (cp = stmt->message; *cp; cp++)
2948                 {
2949                         /*
2950                          * Occurrences of a single % are replaced by the next parameter's
2951                          * external representation. Double %'s are converted to one %.
2952                          */
2953                         if (cp[0] == '%')
2954                         {
2955                                 Oid                     paramtypeid;
2956                                 int32           paramtypmod;
2957                                 Datum           paramvalue;
2958                                 bool            paramisnull;
2959                                 char       *extval;
2960
2961                                 if (cp[1] == '%')
2962                                 {
2963                                         appendStringInfoChar(&ds, '%');
2964                                         cp++;
2965                                         continue;
2966                                 }
2967
2968                                 /* should have been checked at compile time */
2969                                 if (current_param == NULL)
2970                                         elog(ERROR, "unexpected RAISE parameter list length");
2971
2972                                 paramvalue = exec_eval_expr(estate,
2973                                                                           (PLpgSQL_expr *) lfirst(current_param),
2974                                                                                         &paramisnull,
2975                                                                                         &paramtypeid,
2976                                                                                         &paramtypmod);
2977
2978                                 if (paramisnull)
2979                                         extval = "<NULL>";
2980                                 else
2981                                         extval = convert_value_to_string(estate,
2982                                                                                                          paramvalue,
2983                                                                                                          paramtypeid);
2984                                 appendStringInfoString(&ds, extval);
2985                                 current_param = lnext(current_param);
2986                                 exec_eval_cleanup(estate);
2987                         }
2988                         else
2989                                 appendStringInfoChar(&ds, cp[0]);
2990                 }
2991
2992                 /* should have been checked at compile time */
2993                 if (current_param != NULL)
2994                         elog(ERROR, "unexpected RAISE parameter list length");
2995
2996                 err_message = ds.data;
2997                 /* No pfree(ds.data), the pfree(err_message) does it */
2998         }
2999
3000         foreach(lc, stmt->options)
3001         {
3002                 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
3003                 Datum           optionvalue;
3004                 bool            optionisnull;
3005                 Oid                     optiontypeid;
3006                 int32           optiontypmod;
3007                 char       *extval;
3008
3009                 optionvalue = exec_eval_expr(estate, opt->expr,
3010                                                                          &optionisnull,
3011                                                                          &optiontypeid,
3012                                                                          &optiontypmod);
3013                 if (optionisnull)
3014                         ereport(ERROR,
3015                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3016                                          errmsg("RAISE statement option cannot be null")));
3017
3018                 extval = convert_value_to_string(estate, optionvalue, optiontypeid);
3019
3020                 switch (opt->opt_type)
3021                 {
3022                         case PLPGSQL_RAISEOPTION_ERRCODE:
3023                                 if (err_code)
3024                                         ereport(ERROR,
3025                                                         (errcode(ERRCODE_SYNTAX_ERROR),
3026                                                          errmsg("RAISE option already specified: %s",
3027                                                                         "ERRCODE")));
3028                                 err_code = plpgsql_recognize_err_condition(extval, true);
3029                                 condname = pstrdup(extval);
3030                                 break;
3031                         case PLPGSQL_RAISEOPTION_MESSAGE:
3032                                 SET_RAISE_OPTION_TEXT(err_message, "MESSAGE");
3033                                 break;
3034                         case PLPGSQL_RAISEOPTION_DETAIL:
3035                                 SET_RAISE_OPTION_TEXT(err_detail, "DETAIL");
3036                                 break;
3037                         case PLPGSQL_RAISEOPTION_HINT:
3038                                 SET_RAISE_OPTION_TEXT(err_hint, "HINT");
3039                                 break;
3040                         case PLPGSQL_RAISEOPTION_COLUMN:
3041                                 SET_RAISE_OPTION_TEXT(err_column, "COLUMN");
3042                                 break;
3043                         case PLPGSQL_RAISEOPTION_CONSTRAINT:
3044                                 SET_RAISE_OPTION_TEXT(err_constraint, "CONSTRAINT");
3045                                 break;
3046                         case PLPGSQL_RAISEOPTION_DATATYPE:
3047                                 SET_RAISE_OPTION_TEXT(err_datatype, "DATATYPE");
3048                                 break;
3049                         case PLPGSQL_RAISEOPTION_TABLE:
3050                                 SET_RAISE_OPTION_TEXT(err_table, "TABLE");
3051                                 break;
3052                         case PLPGSQL_RAISEOPTION_SCHEMA:
3053                                 SET_RAISE_OPTION_TEXT(err_schema, "SCHEMA");
3054                                 break;
3055                         default:
3056                                 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
3057                 }
3058
3059                 exec_eval_cleanup(estate);
3060         }
3061
3062         /* Default code if nothing specified */
3063         if (err_code == 0 && stmt->elog_level >= ERROR)
3064                 err_code = ERRCODE_RAISE_EXCEPTION;
3065
3066         /* Default error message if nothing specified */
3067         if (err_message == NULL)
3068         {
3069                 if (condname)
3070                 {
3071                         err_message = condname;
3072                         condname = NULL;
3073                 }
3074                 else
3075                         err_message = pstrdup(unpack_sql_state(err_code));
3076         }
3077
3078         /*
3079          * Throw the error (may or may not come back)
3080          */
3081         estate->err_text = raise_skip_msg;      /* suppress traceback of raise */
3082
3083         ereport(stmt->elog_level,
3084                         (err_code ? errcode(err_code) : 0,
3085                          errmsg_internal("%s", err_message),
3086                          (err_detail != NULL) ? errdetail_internal("%s", err_detail) : 0,
3087                          (err_hint != NULL) ? errhint("%s", err_hint) : 0,
3088                          (err_column != NULL) ?
3089                          err_generic_string(PG_DIAG_COLUMN_NAME, err_column) : 0,
3090                          (err_constraint != NULL) ?
3091                          err_generic_string(PG_DIAG_CONSTRAINT_NAME, err_constraint) : 0,
3092                          (err_datatype != NULL) ?
3093                          err_generic_string(PG_DIAG_DATATYPE_NAME, err_datatype) : 0,
3094                          (err_table != NULL) ?
3095                          err_generic_string(PG_DIAG_TABLE_NAME, err_table) : 0,
3096                          (err_schema != NULL) ?
3097                          err_generic_string(PG_DIAG_SCHEMA_NAME, err_schema) : 0));
3098
3099         estate->err_text = NULL;        /* un-suppress... */
3100
3101         if (condname != NULL)
3102                 pfree(condname);
3103         if (err_message != NULL)
3104                 pfree(err_message);
3105         if (err_detail != NULL)
3106                 pfree(err_detail);
3107         if (err_hint != NULL)
3108                 pfree(err_hint);
3109         if (err_column != NULL)
3110                 pfree(err_column);
3111         if (err_constraint != NULL)
3112                 pfree(err_constraint);
3113         if (err_datatype != NULL)
3114                 pfree(err_datatype);
3115         if (err_table != NULL)
3116                 pfree(err_table);
3117         if (err_schema != NULL)
3118                 pfree(err_schema);
3119
3120         return PLPGSQL_RC_OK;
3121 }
3122
3123
3124 /* ----------
3125  * Initialize a mostly empty execution state
3126  * ----------
3127  */
3128 static void
3129 plpgsql_estate_setup(PLpgSQL_execstate *estate,
3130                                          PLpgSQL_function *func,
3131                                          ReturnSetInfo *rsi,
3132                                          EState *simple_eval_estate)
3133 {
3134         /* this link will be restored at exit from plpgsql_call_handler */
3135         func->cur_estate = estate;
3136
3137         estate->func = func;
3138
3139         estate->retval = (Datum) 0;
3140         estate->retisnull = true;
3141         estate->rettype = InvalidOid;
3142
3143         estate->fn_rettype = func->fn_rettype;
3144         estate->retistuple = func->fn_retistuple;
3145         estate->retisset = func->fn_retset;
3146
3147         estate->readonly_func = func->fn_readonly;
3148
3149         estate->rettupdesc = NULL;
3150         estate->exitlabel = NULL;
3151         estate->cur_error = NULL;
3152
3153         estate->tuple_store = NULL;
3154         if (rsi)
3155         {
3156                 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
3157                 estate->tuple_store_owner = CurrentResourceOwner;
3158         }
3159         else
3160         {
3161                 estate->tuple_store_cxt = NULL;
3162                 estate->tuple_store_owner = NULL;
3163         }
3164         estate->rsi = rsi;
3165
3166         estate->found_varno = func->found_varno;
3167         estate->ndatums = func->ndatums;
3168         estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
3169         /* caller is expected to fill the datums array */
3170
3171         /* set up for use of appropriate simple-expression EState */
3172         if (simple_eval_estate)
3173                 estate->simple_eval_estate = simple_eval_estate;
3174         else
3175                 estate->simple_eval_estate = shared_simple_eval_estate;
3176
3177         estate->eval_tuptable = NULL;
3178         estate->eval_processed = 0;
3179         estate->eval_lastoid = InvalidOid;
3180         estate->eval_econtext = NULL;
3181         estate->cur_expr = NULL;
3182
3183         estate->err_stmt = NULL;
3184         estate->err_text = NULL;
3185
3186         estate->plugin_info = NULL;
3187
3188         /*
3189          * Create an EState and ExprContext for evaluation of simple expressions.
3190          */
3191         plpgsql_create_econtext(estate);
3192
3193         /*
3194          * Let the plugin see this function before we initialize any local
3195          * PL/pgSQL variables - note that we also give the plugin a few function
3196          * pointers so it can call back into PL/pgSQL for doing things like
3197          * variable assignments and stack traces
3198          */
3199         if (*plugin_ptr)
3200         {
3201                 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
3202                 (*plugin_ptr)->assign_expr = exec_assign_expr;
3203
3204                 if ((*plugin_ptr)->func_setup)
3205                         ((*plugin_ptr)->func_setup) (estate, func);
3206         }
3207 }
3208
3209 /* ----------
3210  * Release temporary memory used by expression/subselect evaluation
3211  *
3212  * NB: the result of the evaluation is no longer valid after this is done,
3213  * unless it is a pass-by-value datatype.
3214  *
3215  * NB: if you change this code, see also the hacks in exec_assign_value's
3216  * PLPGSQL_DTYPE_ARRAYELEM case.
3217  * ----------
3218  */
3219 static void
3220 exec_eval_cleanup(PLpgSQL_execstate *estate)
3221 {
3222         /* Clear result of a full SPI_execute */
3223         if (estate->eval_tuptable != NULL)
3224                 SPI_freetuptable(estate->eval_tuptable);
3225         estate->eval_tuptable = NULL;
3226
3227         /* Clear result of exec_eval_simple_expr (but keep the econtext) */
3228         if (estate->eval_econtext != NULL)
3229                 ResetExprContext(estate->eval_econtext);
3230 }
3231
3232
3233 /* ----------
3234  * Generate a prepared plan
3235  * ----------
3236  */
3237 static void
3238 exec_prepare_plan(PLpgSQL_execstate *estate,
3239                                   PLpgSQL_expr *expr, int cursorOptions)
3240 {
3241         SPIPlanPtr      plan;
3242
3243         /*
3244          * The grammar can't conveniently set expr->func while building the parse
3245          * tree, so make sure it's set before parser hooks need it.
3246          */
3247         expr->func = estate->func;
3248
3249         /*
3250          * Generate and save the plan
3251          */
3252         plan = SPI_prepare_params(expr->query,
3253                                                           (ParserSetupHook) plpgsql_parser_setup,
3254                                                           (void *) expr,
3255                                                           cursorOptions);
3256         if (plan == NULL)
3257         {
3258                 /* Some SPI errors deserve specific error messages */
3259                 switch (SPI_result)
3260                 {
3261                         case SPI_ERROR_COPY:
3262                                 ereport(ERROR,
3263                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3264                                                  errmsg("cannot COPY to/from client in PL/pgSQL")));
3265                         case SPI_ERROR_TRANSACTION:
3266                                 ereport(ERROR,
3267                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3268                                                  errmsg("cannot begin/end transactions in PL/pgSQL"),
3269                                                  errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3270                         default:
3271                                 elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
3272                                          expr->query, SPI_result_code_string(SPI_result));
3273                 }
3274         }
3275         SPI_keepplan(plan);
3276         expr->plan = plan;
3277
3278         /* Check to see if it's a simple expression */
3279         exec_simple_check_plan(expr);
3280 }
3281
3282
3283 /* ----------
3284  * exec_stmt_execsql                    Execute an SQL statement (possibly with INTO).
3285  * ----------
3286  */
3287 static int
3288 exec_stmt_execsql(PLpgSQL_execstate *estate,
3289                                   PLpgSQL_stmt_execsql *stmt)
3290 {
3291         ParamListInfo paramLI;
3292         long            tcount;
3293         int                     rc;
3294         PLpgSQL_expr *expr = stmt->sqlstmt;
3295
3296         /*
3297          * On the first call for this statement generate the plan, and detect
3298          * whether the statement is INSERT/UPDATE/DELETE
3299          */
3300         if (expr->plan == NULL)
3301         {
3302                 ListCell   *l;
3303
3304                 exec_prepare_plan(estate, expr, 0);
3305                 stmt->mod_stmt = false;
3306                 foreach(l, SPI_plan_get_plan_sources(expr->plan))
3307                 {
3308                         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
3309                         ListCell   *l2;
3310
3311                         foreach(l2, plansource->query_list)
3312                         {
3313                                 Query      *q = (Query *) lfirst(l2);
3314
3315                                 Assert(IsA(q, Query));
3316                                 if (q->canSetTag)
3317                                 {
3318                                         if (q->commandType == CMD_INSERT ||
3319                                                 q->commandType == CMD_UPDATE ||
3320                                                 q->commandType == CMD_DELETE)
3321                                                 stmt->mod_stmt = true;
3322                                 }
3323                         }
3324                 }
3325         }
3326
3327         /*
3328          * Set up ParamListInfo (hook function and possibly data values)
3329          */
3330         paramLI = setup_param_list(estate, expr);
3331
3332         /*
3333          * If we have INTO, then we only need one row back ... but if we have INTO
3334          * STRICT, ask for two rows, so that we can verify the statement returns
3335          * only one.  INSERT/UPDATE/DELETE are always treated strictly. Without
3336          * INTO, just run the statement to completion (tcount = 0).
3337          *
3338          * We could just ask for two rows always when using INTO, but there are
3339          * some cases where demanding the extra row costs significant time, eg by
3340          * forcing completion of a sequential scan.  So don't do it unless we need
3341          * to enforce strictness.
3342          */
3343         if (stmt->into)
3344         {
3345                 if (stmt->strict || stmt->mod_stmt)
3346                         tcount = 2;
3347                 else
3348                         tcount = 1;
3349         }
3350         else
3351                 tcount = 0;
3352
3353         /*
3354          * Execute the plan
3355          */
3356         rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
3357                                                                                  estate->readonly_func, tcount);
3358
3359         /*
3360          * Check for error, and set FOUND if appropriate (for historical reasons
3361          * we set FOUND only for certain query types).  Also Assert that we
3362          * identified the statement type the same as SPI did.
3363          */
3364         switch (rc)
3365         {
3366                 case SPI_OK_SELECT:
3367                         Assert(!stmt->mod_stmt);
3368                         exec_set_found(estate, (SPI_processed != 0));
3369                         break;
3370
3371                 case SPI_OK_INSERT:
3372                 case SPI_OK_UPDATE:
3373                 case SPI_OK_DELETE:
3374                 case SPI_OK_INSERT_RETURNING:
3375                 case SPI_OK_UPDATE_RETURNING:
3376                 case SPI_OK_DELETE_RETURNING:
3377                         Assert(stmt->mod_stmt);
3378                         exec_set_found(estate, (SPI_processed != 0));
3379                         break;
3380
3381                 case SPI_OK_SELINTO:
3382                 case SPI_OK_UTILITY:
3383                         Assert(!stmt->mod_stmt);
3384                         break;
3385
3386                 case SPI_OK_REWRITTEN:
3387                         Assert(!stmt->mod_stmt);
3388
3389                         /*
3390                          * The command was rewritten into another kind of command. It's
3391                          * not clear what FOUND would mean in that case (and SPI doesn't
3392                          * return the row count either), so just set it to false.
3393                          */
3394                         exec_set_found(estate, false);
3395                         break;
3396
3397                         /* Some SPI errors deserve specific error messages */
3398                 case SPI_ERROR_COPY:
3399                         ereport(ERROR,
3400                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3401                                          errmsg("cannot COPY to/from client in PL/pgSQL")));
3402                 case SPI_ERROR_TRANSACTION:
3403                         ereport(ERROR,
3404                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3405                                          errmsg("cannot begin/end transactions in PL/pgSQL"),
3406                         errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3407
3408                 default:
3409                         elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
3410                                  expr->query, SPI_result_code_string(rc));
3411         }
3412
3413         /* All variants should save result info for GET DIAGNOSTICS */
3414         estate->eval_processed = SPI_processed;
3415         estate->eval_lastoid = SPI_lastoid;
3416
3417         /* Process INTO if present */
3418         if (stmt->into)
3419         {
3420                 SPITupleTable *tuptab = SPI_tuptable;
3421                 uint32          n = SPI_processed;
3422                 PLpgSQL_rec *rec = NULL;
3423                 PLpgSQL_row *row = NULL;
3424
3425                 /* If the statement did not return a tuple table, complain */
3426                 if (tuptab == NULL)
3427                         ereport(ERROR,
3428                                         (errcode(ERRCODE_SYNTAX_ERROR),
3429                                 errmsg("INTO used with a command that cannot return data")));
3430
3431                 /* Determine if we assign to a record or a row */
3432                 if (stmt->rec != NULL)
3433                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3434                 else if (stmt->row != NULL)
3435                         row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3436                 else
3437                         elog(ERROR, "unsupported target");
3438
3439                 /*
3440                  * If SELECT ... INTO specified STRICT, and the query didn't find
3441                  * exactly one row, throw an error.  If STRICT was not specified, then
3442                  * allow the query to find any number of rows.
3443                  */
3444                 if (n == 0)
3445                 {
3446                         if (stmt->strict)
3447                         {
3448                                 char       *errdetail;
3449
3450                                 if (estate->func->print_strict_params)
3451                                         errdetail = format_expr_params(estate, expr);
3452                                 else
3453                                         errdetail = NULL;
3454
3455                                 ereport(ERROR,
3456                                                 (errcode(ERRCODE_NO_DATA_FOUND),
3457                                                  errmsg("query returned no rows"),
3458                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3459                         }
3460                         /* set the target to NULL(s) */
3461                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3462                 }
3463                 else
3464                 {
3465                         if (n > 1 && (stmt->strict || stmt->mod_stmt))
3466                         {
3467                                 char       *errdetail;
3468
3469                                 if (estate->func->print_strict_params)
3470                                         errdetail = format_expr_params(estate, expr);
3471                                 else
3472                                         errdetail = NULL;
3473
3474                                 ereport(ERROR,
3475                                                 (errcode(ERRCODE_TOO_MANY_ROWS),
3476                                                  errmsg("query returned more than one row"),
3477                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3478                         }
3479                         /* Put the first result row into the target */
3480                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3481                 }
3482
3483                 /* Clean up */
3484                 exec_eval_cleanup(estate);
3485                 SPI_freetuptable(SPI_tuptable);
3486         }
3487         else
3488         {
3489                 /* If the statement returned a tuple table, complain */
3490                 if (SPI_tuptable != NULL)
3491                         ereport(ERROR,
3492                                         (errcode(ERRCODE_SYNTAX_ERROR),
3493                                          errmsg("query has no destination for result data"),
3494                                          (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
3495         }
3496
3497         if (paramLI)
3498                 pfree(paramLI);
3499
3500         return PLPGSQL_RC_OK;
3501 }
3502
3503
3504 /* ----------
3505  * exec_stmt_dynexecute                 Execute a dynamic SQL query
3506  *                                      (possibly with INTO).
3507  * ----------
3508  */
3509 static int
3510 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
3511                                          PLpgSQL_stmt_dynexecute *stmt)
3512 {
3513         Datum           query;
3514         bool            isnull;
3515         Oid                     restype;
3516         int32           restypmod;
3517         char       *querystr;
3518         int                     exec_res;
3519         PreparedParamsData *ppd = NULL;
3520
3521         /*
3522          * First we evaluate the string expression after the EXECUTE keyword. Its
3523          * result is the querystring we have to execute.
3524          */
3525         query = exec_eval_expr(estate, stmt->query, &isnull, &restype, &restypmod);
3526         if (isnull)
3527                 ereport(ERROR,
3528                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3529                                  errmsg("query string argument of EXECUTE is null")));
3530
3531         /* Get the C-String representation */
3532         querystr = convert_value_to_string(estate, query, restype);
3533
3534         /* copy it out of the temporary context before we clean up */
3535         querystr = pstrdup(querystr);
3536
3537         exec_eval_cleanup(estate);
3538
3539         /*
3540          * Execute the query without preparing a saved plan.
3541          */
3542         if (stmt->params)
3543         {
3544                 ppd = exec_eval_using_params(estate, stmt->params);
3545                 exec_res = SPI_execute_with_args(querystr,
3546                                                                                  ppd->nargs, ppd->types,
3547                                                                                  ppd->values, ppd->nulls,
3548                                                                                  estate->readonly_func, 0);
3549         }
3550         else
3551                 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
3552
3553         switch (exec_res)
3554         {
3555                 case SPI_OK_SELECT:
3556                 case SPI_OK_INSERT:
3557                 case SPI_OK_UPDATE:
3558                 case SPI_OK_DELETE:
3559                 case SPI_OK_INSERT_RETURNING:
3560                 case SPI_OK_UPDATE_RETURNING:
3561                 case SPI_OK_DELETE_RETURNING:
3562                 case SPI_OK_UTILITY:
3563                 case SPI_OK_REWRITTEN:
3564                         break;
3565
3566                 case 0:
3567
3568                         /*
3569                          * Also allow a zero return, which implies the querystring
3570                          * contained no commands.
3571                          */
3572                         break;
3573
3574                 case SPI_OK_SELINTO:
3575
3576                         /*
3577                          * We want to disallow SELECT INTO for now, because its behavior
3578                          * is not consistent with SELECT INTO in a normal plpgsql context.
3579                          * (We need to reimplement EXECUTE to parse the string as a
3580                          * plpgsql command, not just feed it to SPI_execute.)  This is not
3581                          * a functional limitation because CREATE TABLE AS is allowed.
3582                          */
3583                         ereport(ERROR,
3584                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3585                                          errmsg("EXECUTE of SELECT ... INTO is not implemented"),
3586                                          errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
3587                         break;
3588
3589                         /* Some SPI errors deserve specific error messages */
3590                 case SPI_ERROR_COPY:
3591                         ereport(ERROR,
3592                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3593                                          errmsg("cannot COPY to/from client in PL/pgSQL")));
3594                 case SPI_ERROR_TRANSACTION:
3595                         ereport(ERROR,
3596                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3597                                          errmsg("cannot begin/end transactions in PL/pgSQL"),
3598                         errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3599
3600                 default:
3601                         elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
3602                                  querystr, SPI_result_code_string(exec_res));
3603                         break;
3604         }
3605
3606         /* Save result info for GET DIAGNOSTICS */
3607         estate->eval_processed = SPI_processed;
3608         estate->eval_lastoid = SPI_lastoid;
3609
3610         /* Process INTO if present */
3611         if (stmt->into)
3612         {
3613                 SPITupleTable *tuptab = SPI_tuptable;
3614                 uint32          n = SPI_processed;
3615                 PLpgSQL_rec *rec = NULL;
3616                 PLpgSQL_row *row = NULL;
3617
3618                 /* If the statement did not return a tuple table, complain */
3619                 if (tuptab == NULL)
3620                         ereport(ERROR,
3621                                         (errcode(ERRCODE_SYNTAX_ERROR),
3622                                 errmsg("INTO used with a command that cannot return data")));
3623
3624                 /* Determine if we assign to a record or a row */
3625                 if (stmt->rec != NULL)
3626                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3627                 else if (stmt->row != NULL)
3628                         row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3629                 else
3630                         elog(ERROR, "unsupported target");
3631
3632                 /*
3633                  * If SELECT ... INTO specified STRICT, and the query didn't find
3634                  * exactly one row, throw an error.  If STRICT was not specified, then
3635                  * allow the query to find any number of rows.
3636                  */
3637                 if (n == 0)
3638                 {
3639                         if (stmt->strict)
3640                         {
3641                                 char       *errdetail;
3642
3643                                 if (estate->func->print_strict_params)
3644                                         errdetail = format_preparedparamsdata(estate, ppd);
3645                                 else
3646                                         errdetail = NULL;
3647
3648                                 ereport(ERROR,
3649                                                 (errcode(ERRCODE_NO_DATA_FOUND),
3650                                                  errmsg("query returned no rows"),
3651                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3652                         }
3653                         /* set the target to NULL(s) */
3654                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3655                 }
3656                 else
3657                 {
3658                         if (n > 1 && stmt->strict)
3659                         {
3660                                 char       *errdetail;
3661
3662                                 if (estate->func->print_strict_params)
3663                                         errdetail = format_preparedparamsdata(estate, ppd);
3664                                 else
3665                                         errdetail = NULL;
3666
3667                                 ereport(ERROR,
3668                                                 (errcode(ERRCODE_TOO_MANY_ROWS),
3669                                                  errmsg("query returned more than one row"),
3670                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3671                         }
3672
3673                         /* Put the first result row into the target */
3674                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3675                 }
3676                 /* clean up after exec_move_row() */
3677                 exec_eval_cleanup(estate);
3678         }
3679         else
3680         {
3681                 /*
3682                  * It might be a good idea to raise an error if the query returned
3683                  * tuples that are being ignored, but historically we have not done
3684                  * that.
3685                  */
3686         }
3687
3688         if (ppd)
3689                 free_params_data(ppd);
3690
3691         /* Release any result from SPI_execute, as well as the querystring */
3692         SPI_freetuptable(SPI_tuptable);
3693         pfree(querystr);
3694
3695         return PLPGSQL_RC_OK;
3696 }
3697
3698
3699 /* ----------
3700  * exec_stmt_dynfors                    Execute a dynamic query, assign each
3701  *                                      tuple to a record or row and
3702  *                                      execute a group of statements
3703  *                                      for it.
3704  * ----------
3705  */
3706 static int
3707 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3708 {
3709         Portal          portal;
3710         int                     rc;
3711
3712         portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
3713                                                                            NULL, 0);
3714
3715         /*
3716          * Execute the loop
3717          */
3718         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3719
3720         /*
3721          * Close the implicit cursor
3722          */
3723         SPI_cursor_close(portal);
3724
3725         return rc;
3726 }
3727
3728
3729 /* ----------
3730  * exec_stmt_open                       Execute an OPEN cursor statement
3731  * ----------
3732  */
3733 static int
3734 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3735 {
3736         PLpgSQL_var *curvar;
3737         char       *curname = NULL;
3738         PLpgSQL_expr *query;
3739         Portal          portal;
3740         ParamListInfo paramLI;
3741
3742         /* ----------
3743          * Get the cursor variable and if it has an assigned name, check
3744          * that it's not in use currently.
3745          * ----------
3746          */
3747         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3748         if (!curvar->isnull)
3749         {
3750                 curname = TextDatumGetCString(curvar->value);
3751                 if (SPI_cursor_find(curname) != NULL)
3752                         ereport(ERROR,
3753                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
3754                                          errmsg("cursor \"%s\" already in use", curname)));
3755         }
3756
3757         /* ----------
3758          * Process the OPEN according to it's type.
3759          * ----------
3760          */
3761         if (stmt->query != NULL)
3762         {
3763                 /* ----------
3764                  * This is an OPEN refcursor FOR SELECT ...
3765                  *
3766                  * We just make sure the query is planned. The real work is
3767                  * done downstairs.
3768                  * ----------
3769                  */
3770                 query = stmt->query;
3771                 if (query->plan == NULL)
3772                         exec_prepare_plan(estate, query, stmt->cursor_options);
3773         }
3774         else if (stmt->dynquery != NULL)
3775         {
3776                 /* ----------
3777                  * This is an OPEN refcursor FOR EXECUTE ...
3778                  * ----------
3779                  */
3780                 portal = exec_dynquery_with_params(estate,
3781                                                                                    stmt->dynquery,
3782                                                                                    stmt->params,
3783                                                                                    curname,
3784                                                                                    stmt->cursor_options);
3785
3786                 /*
3787                  * If cursor variable was NULL, store the generated portal name in it
3788                  */
3789                 if (curname == NULL)
3790                         assign_text_var(curvar, portal->name);
3791
3792                 return PLPGSQL_RC_OK;
3793         }
3794         else
3795         {
3796                 /* ----------
3797                  * This is an OPEN cursor
3798                  *
3799                  * Note: parser should already have checked that statement supplies
3800                  * args iff cursor needs them, but we check again to be safe.
3801                  * ----------
3802                  */
3803                 if (stmt->argquery != NULL)
3804                 {
3805                         /* ----------
3806                          * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
3807                          * statement to evaluate the args and put 'em into the
3808                          * internal row.
3809                          * ----------
3810                          */
3811                         PLpgSQL_stmt_execsql set_args;
3812
3813                         if (curvar->cursor_explicit_argrow < 0)
3814                                 ereport(ERROR,
3815                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3816                                         errmsg("arguments given for cursor without arguments")));
3817
3818                         memset(&set_args, 0, sizeof(set_args));
3819                         set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3820                         set_args.lineno = stmt->lineno;
3821                         set_args.sqlstmt = stmt->argquery;
3822                         set_args.into = true;
3823                         /* XXX historically this has not been STRICT */
3824                         set_args.row = (PLpgSQL_row *)
3825                                 (estate->datums[curvar->cursor_explicit_argrow]);
3826
3827                         if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3828                                 elog(ERROR, "open cursor failed during argument processing");
3829                 }
3830                 else
3831                 {
3832                         if (curvar->cursor_explicit_argrow >= 0)
3833                                 ereport(ERROR,
3834                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3835                                                  errmsg("arguments required for cursor")));
3836                 }
3837
3838                 query = curvar->cursor_explicit_expr;
3839                 if (query->plan == NULL)
3840                         exec_prepare_plan(estate, query, curvar->cursor_options);
3841         }
3842
3843         /*
3844          * Set up ParamListInfo (hook function and possibly data values)
3845          */
3846         paramLI = setup_param_list(estate, query);
3847
3848         /*
3849          * Open the cursor
3850          */
3851         portal = SPI_cursor_open_with_paramlist(curname, query->plan,
3852                                                                                         paramLI,
3853                                                                                         estate->readonly_func);
3854         if (portal == NULL)
3855                 elog(ERROR, "could not open cursor: %s",
3856                          SPI_result_code_string(SPI_result));
3857
3858         /*
3859          * If cursor variable was NULL, store the generated portal name in it
3860          */
3861         if (curname == NULL)
3862                 assign_text_var(curvar, portal->name);
3863
3864         if (curname)
3865                 pfree(curname);
3866         if (paramLI)
3867                 pfree(paramLI);
3868
3869         return PLPGSQL_RC_OK;
3870 }
3871
3872
3873 /* ----------
3874  * exec_stmt_fetch                      Fetch from a cursor into a target, or just
3875  *                                                      move the current position of the cursor
3876  * ----------
3877  */
3878 static int
3879 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3880 {
3881         PLpgSQL_var *curvar = NULL;
3882         PLpgSQL_rec *rec = NULL;
3883         PLpgSQL_row *row = NULL;
3884         long            how_many = stmt->how_many;
3885         SPITupleTable *tuptab;
3886         Portal          portal;
3887         char       *curname;
3888         uint32          n;
3889
3890         /* ----------
3891          * Get the portal of the cursor by name
3892          * ----------
3893          */
3894         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3895         if (curvar->isnull)
3896                 ereport(ERROR,
3897                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3898                                  errmsg("cursor variable \"%s\" is null", curvar->refname)));
3899         curname = TextDatumGetCString(curvar->value);
3900
3901         portal = SPI_cursor_find(curname);
3902         if (portal == NULL)
3903                 ereport(ERROR,
3904                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
3905                                  errmsg("cursor \"%s\" does not exist", curname)));
3906         pfree(curname);
3907
3908         /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3909         if (stmt->expr)
3910         {
3911                 bool            isnull;
3912
3913                 /* XXX should be doing this in LONG not INT width */
3914                 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3915
3916                 if (isnull)
3917                         ereport(ERROR,
3918                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3919                                          errmsg("relative or absolute cursor position is null")));
3920
3921                 exec_eval_cleanup(estate);
3922         }
3923
3924         if (!stmt->is_move)
3925         {
3926                 /* ----------
3927                  * Determine if we fetch into a record or a row
3928                  * ----------
3929                  */
3930                 if (stmt->rec != NULL)
3931                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3932                 else if (stmt->row != NULL)
3933                         row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3934                 else
3935                         elog(ERROR, "unsupported target");
3936
3937                 /* ----------
3938                  * Fetch 1 tuple from the cursor
3939                  * ----------
3940                  */
3941                 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3942                 tuptab = SPI_tuptable;
3943                 n = SPI_processed;
3944
3945                 /* ----------
3946                  * Set the target appropriately.
3947                  * ----------
3948                  */
3949                 if (n == 0)
3950                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3951                 else
3952                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3953
3954                 exec_eval_cleanup(estate);
3955                 SPI_freetuptable(tuptab);
3956         }
3957         else
3958         {
3959                 /* Move the cursor */
3960                 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3961                 n = SPI_processed;
3962         }
3963
3964         /* Set the ROW_COUNT and the global FOUND variable appropriately. */
3965         estate->eval_processed = n;
3966         exec_set_found(estate, n != 0);
3967
3968         return PLPGSQL_RC_OK;
3969 }
3970
3971 /* ----------
3972  * exec_stmt_close                      Close a cursor
3973  * ----------
3974  */
3975 static int
3976 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3977 {
3978         PLpgSQL_var *curvar = NULL;
3979         Portal          portal;
3980         char       *curname;
3981
3982         /* ----------
3983          * Get the portal of the cursor by name
3984          * ----------
3985          */
3986         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3987         if (curvar->isnull)
3988                 ereport(ERROR,
3989                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3990                                  errmsg("cursor variable \"%s\" is null", curvar->refname)));
3991         curname = TextDatumGetCString(curvar->value);
3992
3993         portal = SPI_cursor_find(curname);
3994         if (portal == NULL)
3995                 ereport(ERROR,
3996                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
3997                                  errmsg("cursor \"%s\" does not exist", curname)));
3998         pfree(curname);
3999
4000         /* ----------
4001          * And close it.
4002          * ----------
4003          */
4004         SPI_cursor_close(portal);
4005
4006         return PLPGSQL_RC_OK;
4007 }
4008
4009
4010 /* ----------
4011  * exec_assign_expr                     Put an expression's result into a variable.
4012  * ----------
4013  */
4014 static void
4015 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
4016                                  PLpgSQL_expr *expr)
4017 {
4018         Datum           value;
4019         bool            isnull;
4020         Oid                     valtype;
4021         int32           valtypmod;
4022
4023         value = exec_eval_expr(estate, expr, &isnull, &valtype, &valtypmod);
4024         exec_assign_value(estate, target, value, isnull, valtype, valtypmod);
4025         exec_eval_cleanup(estate);
4026 }
4027
4028
4029 /* ----------
4030  * exec_assign_c_string         Put a C string into a text variable.
4031  *
4032  * We take a NULL pointer as signifying empty string, not SQL null.
4033  * ----------
4034  */
4035 static void
4036 exec_assign_c_string(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
4037                                          const char *str)
4038 {
4039         text       *value;
4040
4041         if (str != NULL)
4042                 value = cstring_to_text(str);
4043         else
4044                 value = cstring_to_text("");
4045         exec_assign_value(estate, target, PointerGetDatum(value), false,
4046                                           TEXTOID, -1);
4047         pfree(value);
4048 }
4049
4050
4051 /* ----------
4052  * exec_assign_value                    Put a value into a target field
4053  *
4054  * Note: in some code paths, this will leak memory in the eval_econtext;
4055  * we assume that will be cleaned up later by exec_eval_cleanup.  We cannot
4056  * call exec_eval_cleanup here for fear of destroying the input Datum value.
4057  * ----------
4058  */
4059 static void
4060 exec_assign_value(PLpgSQL_execstate *estate,
4061                                   PLpgSQL_datum *target,
4062                                   Datum value, bool isNull,
4063                                   Oid valtype, int32 valtypmod)
4064 {
4065         switch (target->dtype)
4066         {
4067                 case PLPGSQL_DTYPE_VAR:
4068                         {
4069                                 /*
4070                                  * Target is a variable
4071                                  */
4072                                 PLpgSQL_var *var = (PLpgSQL_var *) target;
4073                                 Datum           newvalue;
4074
4075                                 newvalue = exec_cast_value(estate,
4076                                                                                    value,
4077                                                                                    &isNull,
4078                                                                                    valtype,
4079                                                                                    valtypmod,
4080                                                                                    var->datatype->typoid,
4081                                                                                    var->datatype->atttypmod);
4082
4083                                 if (isNull && var->notnull)
4084                                         ereport(ERROR,
4085                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4086                                                          errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
4087                                                                         var->refname)));
4088
4089                                 /*
4090                                  * If type is by-reference, copy the new value (which is
4091                                  * probably in the eval_econtext) into the procedure's memory
4092                                  * context.
4093                                  */
4094                                 if (!var->datatype->typbyval && !isNull)
4095                                         newvalue = datumCopy(newvalue,
4096                                                                                  false,
4097                                                                                  var->datatype->typlen);
4098
4099                                 /*
4100                                  * Now free the old value.  (We can't do this any earlier
4101                                  * because of the possibility that we are assigning the var's
4102                                  * old value to it, eg "foo := foo".  We could optimize out
4103                                  * the assignment altogether in such cases, but it's too
4104                                  * infrequent to be worth testing for.)
4105                                  */
4106                                 free_var(var);
4107
4108                                 var->value = newvalue;
4109                                 var->isnull = isNull;
4110                                 if (!var->datatype->typbyval && !isNull)
4111                                         var->freeval = true;
4112                                 break;
4113                         }
4114
4115                 case PLPGSQL_DTYPE_ROW:
4116                         {
4117                                 /*
4118                                  * Target is a row variable
4119                                  */
4120                                 PLpgSQL_row *row = (PLpgSQL_row *) target;
4121
4122                                 if (isNull)
4123                                 {
4124                                         /* If source is null, just assign nulls to the row */
4125                                         exec_move_row(estate, NULL, row, NULL, NULL);
4126                                 }
4127                                 else
4128                                 {
4129                                         /* Source must be of RECORD or composite type */
4130                                         if (!type_is_rowtype(valtype))
4131                                                 ereport(ERROR,
4132                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
4133                                                                  errmsg("cannot assign non-composite value to a row variable")));
4134                                         exec_move_row_from_datum(estate, NULL, row, value);
4135                                 }
4136                                 break;
4137                         }
4138
4139                 case PLPGSQL_DTYPE_REC:
4140                         {
4141                                 /*
4142                                  * Target is a record variable
4143                                  */
4144                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
4145
4146                                 if (isNull)
4147                                 {
4148                                         /* If source is null, just assign nulls to the record */
4149                                         exec_move_row(estate, rec, NULL, NULL, NULL);
4150                                 }
4151                                 else
4152                                 {
4153                                         /* Source must be of RECORD or composite type */
4154                                         if (!type_is_rowtype(valtype))
4155                                                 ereport(ERROR,
4156                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
4157                                                                  errmsg("cannot assign non-composite value to a record variable")));
4158                                         exec_move_row_from_datum(estate, rec, NULL, value);
4159                                 }
4160                                 break;
4161                         }
4162
4163                 case PLPGSQL_DTYPE_RECFIELD:
4164                         {
4165                                 /*
4166                                  * Target is a field of a record
4167                                  */
4168                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
4169                                 PLpgSQL_rec *rec;
4170                                 int                     fno;
4171                                 HeapTuple       newtup;
4172                                 int                     natts;
4173                                 Datum      *values;
4174                                 bool       *nulls;
4175                                 bool       *replaces;
4176                                 Oid                     atttype;
4177                                 int32           atttypmod;
4178
4179                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4180
4181                                 /*
4182                                  * Check that there is already a tuple in the record. We need
4183                                  * that because records don't have any predefined field
4184                                  * structure.
4185                                  */
4186                                 if (!HeapTupleIsValid(rec->tup))
4187                                         ereport(ERROR,
4188                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4189                                                    errmsg("record \"%s\" is not assigned yet",
4190                                                                   rec->refname),
4191                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4192
4193                                 /*
4194                                  * Get the number of the records field to change and the
4195                                  * number of attributes in the tuple.  Note: disallow system
4196                                  * column names because the code below won't cope.
4197                                  */
4198                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4199                                 if (fno <= 0)
4200                                         ereport(ERROR,
4201                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4202                                                          errmsg("record \"%s\" has no field \"%s\"",
4203                                                                         rec->refname, recfield->fieldname)));
4204                                 fno--;
4205                                 natts = rec->tupdesc->natts;
4206
4207                                 /*
4208                                  * Set up values/control arrays for heap_modify_tuple. For all
4209                                  * the attributes except the one we want to replace, use the
4210                                  * value that's in the old tuple.
4211                                  */
4212                                 values = palloc(sizeof(Datum) * natts);
4213                                 nulls = palloc(sizeof(bool) * natts);
4214                                 replaces = palloc(sizeof(bool) * natts);
4215
4216                                 memset(replaces, false, sizeof(bool) * natts);
4217                                 replaces[fno] = true;
4218
4219                                 /*
4220                                  * Now insert the new value, being careful to cast it to the
4221                                  * right type.
4222                                  */
4223                                 atttype = rec->tupdesc->attrs[fno]->atttypid;
4224                                 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
4225                                 values[fno] = exec_cast_value(estate,
4226                                                                                           value,
4227                                                                                           &isNull,
4228                                                                                           valtype,
4229                                                                                           valtypmod,
4230                                                                                           atttype,
4231                                                                                           atttypmod);
4232                                 nulls[fno] = isNull;
4233
4234                                 /*
4235                                  * Now call heap_modify_tuple() to create a new tuple that
4236                                  * replaces the old one in the record.
4237                                  */
4238                                 newtup = heap_modify_tuple(rec->tup, rec->tupdesc,
4239                                                                                    values, nulls, replaces);
4240
4241                                 if (rec->freetup)
4242                                         heap_freetuple(rec->tup);
4243
4244                                 rec->tup = newtup;
4245                                 rec->freetup = true;
4246
4247                                 pfree(values);
4248                                 pfree(nulls);
4249                                 pfree(replaces);
4250
4251                                 break;
4252                         }
4253
4254                 case PLPGSQL_DTYPE_ARRAYELEM:
4255                         {
4256                                 /*
4257                                  * Target is an element of an array
4258                                  */
4259                                 PLpgSQL_arrayelem *arrayelem;
4260                                 int                     nsubscripts;
4261                                 int                     i;
4262                                 PLpgSQL_expr *subscripts[MAXDIM];
4263                                 int                     subscriptvals[MAXDIM];
4264                                 Datum           oldarraydatum,
4265                                                         newarraydatum,
4266                                                         coerced_value;
4267                                 bool            oldarrayisnull;
4268                                 Oid                     parenttypoid;
4269                                 int32           parenttypmod;
4270                                 SPITupleTable *save_eval_tuptable;
4271                                 MemoryContext oldcontext;
4272
4273                                 /*
4274                                  * We need to do subscript evaluation, which might require
4275                                  * evaluating general expressions; and the caller might have
4276                                  * done that too in order to prepare the input Datum.  We have
4277                                  * to save and restore the caller's SPI_execute result, if
4278                                  * any.
4279                                  */
4280                                 save_eval_tuptable = estate->eval_tuptable;
4281                                 estate->eval_tuptable = NULL;
4282
4283                                 /*
4284                                  * To handle constructs like x[1][2] := something, we have to
4285                                  * be prepared to deal with a chain of arrayelem datums. Chase
4286                                  * back to find the base array datum, and save the subscript
4287                                  * expressions as we go.  (We are scanning right to left here,
4288                                  * but want to evaluate the subscripts left-to-right to
4289                                  * minimize surprises.)  Note that arrayelem is left pointing
4290                                  * to the leftmost arrayelem datum, where we will cache the
4291                                  * array element type data.
4292                                  */
4293                                 nsubscripts = 0;
4294                                 do
4295                                 {
4296                                         arrayelem = (PLpgSQL_arrayelem *) target;
4297                                         if (nsubscripts >= MAXDIM)
4298                                                 ereport(ERROR,
4299                                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4300                                                                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
4301                                                                                 nsubscripts + 1, MAXDIM)));
4302                                         subscripts[nsubscripts++] = arrayelem->subscript;
4303                                         target = estate->datums[arrayelem->arrayparentno];
4304                                 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
4305
4306                                 /* Fetch current value of array datum */
4307                                 exec_eval_datum(estate, target,
4308                                                                 &parenttypoid, &parenttypmod,
4309                                                                 &oldarraydatum, &oldarrayisnull);
4310
4311                                 /* Update cached type data if necessary */
4312                                 if (arrayelem->parenttypoid != parenttypoid ||
4313                                         arrayelem->parenttypmod != parenttypmod)
4314                                 {
4315                                         Oid                     arraytypoid;
4316                                         int32           arraytypmod = parenttypmod;
4317                                         int16           arraytyplen;
4318                                         Oid                     elemtypoid;
4319                                         int16           elemtyplen;
4320                                         bool            elemtypbyval;
4321                                         char            elemtypalign;
4322
4323                                         /* If target is domain over array, reduce to base type */
4324                                         arraytypoid = getBaseTypeAndTypmod(parenttypoid,
4325                                                                                                            &arraytypmod);
4326
4327                                         /* ... and identify the element type */
4328                                         elemtypoid = get_element_type(arraytypoid);
4329                                         if (!OidIsValid(elemtypoid))
4330                                                 ereport(ERROR,
4331                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
4332                                                           errmsg("subscripted object is not an array")));
4333
4334                                         /* Collect needed data about the types */
4335                                         arraytyplen = get_typlen(arraytypoid);
4336
4337                                         get_typlenbyvalalign(elemtypoid,
4338                                                                                  &elemtyplen,
4339                                                                                  &elemtypbyval,
4340                                                                                  &elemtypalign);
4341
4342                                         /* Now safe to update the cached data */
4343                                         arrayelem->parenttypoid = parenttypoid;
4344                                         arrayelem->parenttypmod = parenttypmod;
4345                                         arrayelem->arraytypoid = arraytypoid;
4346                                         arrayelem->arraytypmod = arraytypmod;
4347                                         arrayelem->arraytyplen = arraytyplen;
4348                                         arrayelem->elemtypoid = elemtypoid;
4349                                         arrayelem->elemtyplen = elemtyplen;
4350                                         arrayelem->elemtypbyval = elemtypbyval;
4351                                         arrayelem->elemtypalign = elemtypalign;
4352                                 }
4353
4354                                 /*
4355                                  * Evaluate the subscripts, switch into left-to-right order.
4356                                  * Like ExecEvalArrayRef(), complain if any subscript is null.
4357                                  */
4358                                 for (i = 0; i < nsubscripts; i++)
4359                                 {
4360                                         bool            subisnull;
4361
4362                                         subscriptvals[i] =
4363                                                 exec_eval_integer(estate,
4364                                                                                   subscripts[nsubscripts - 1 - i],
4365                                                                                   &subisnull);
4366                                         if (subisnull)
4367                                                 ereport(ERROR,
4368                                                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4369                                                                  errmsg("array subscript in assignment must not be null")));
4370
4371                                         /*
4372                                          * Clean up in case the subscript expression wasn't
4373                                          * simple. We can't do exec_eval_cleanup, but we can do
4374                                          * this much (which is safe because the integer subscript
4375                                          * value is surely pass-by-value), and we must do it in
4376                                          * case the next subscript expression isn't simple either.
4377                                          */
4378                                         if (estate->eval_tuptable != NULL)
4379                                                 SPI_freetuptable(estate->eval_tuptable);
4380                                         estate->eval_tuptable = NULL;
4381                                 }
4382
4383                                 /* Now we can restore caller's SPI_execute result if any. */
4384                                 Assert(estate->eval_tuptable == NULL);
4385                                 estate->eval_tuptable = save_eval_tuptable;
4386
4387                                 /* Coerce source value to match array element type. */
4388                                 coerced_value = exec_cast_value(estate,
4389                                                                                                 value,
4390                                                                                                 &isNull,
4391                                                                                                 valtype,
4392                                                                                                 valtypmod,
4393                                                                                                 arrayelem->elemtypoid,
4394                                                                                                 arrayelem->arraytypmod);
4395
4396                                 /*
4397                                  * If the original array is null, cons up an empty array so
4398                                  * that the assignment can proceed; we'll end with a
4399                                  * one-element array containing just the assigned-to
4400                                  * subscript.  This only works for varlena arrays, though; for
4401                                  * fixed-length array types we skip the assignment.  We can't
4402                                  * support assignment of a null entry into a fixed-length
4403                                  * array, either, so that's a no-op too.  This is all ugly but
4404                                  * corresponds to the current behavior of ExecEvalArrayRef().
4405                                  */
4406                                 if (arrayelem->arraytyplen > 0 &&               /* fixed-length array? */
4407                                         (oldarrayisnull || isNull))
4408                                         return;
4409
4410                                 /* empty array, if any, and newarraydatum are short-lived */
4411                                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4412
4413                                 if (oldarrayisnull)
4414                                         oldarraydatum = PointerGetDatum(construct_empty_array(arrayelem->elemtypoid));
4415
4416                                 /*
4417                                  * Build the modified array value.
4418                                  */
4419                                 newarraydatum = array_set_element(oldarraydatum,
4420                                                                                                   nsubscripts,
4421                                                                                                   subscriptvals,
4422                                                                                                   coerced_value,
4423                                                                                                   isNull,
4424                                                                                                   arrayelem->arraytyplen,
4425                                                                                                   arrayelem->elemtyplen,
4426                                                                                                   arrayelem->elemtypbyval,
4427                                                                                                   arrayelem->elemtypalign);
4428
4429                                 MemoryContextSwitchTo(oldcontext);
4430
4431                                 /*
4432                                  * Assign the new array to the base variable.  It's never NULL
4433                                  * at this point.  Note that if the target is a domain,
4434                                  * coercing the base array type back up to the domain will
4435                                  * happen within exec_assign_value.
4436                                  */
4437                                 exec_assign_value(estate, target,
4438                                                                   newarraydatum,
4439                                                                   false,
4440                                                                   arrayelem->arraytypoid,
4441                                                                   arrayelem->arraytypmod);
4442                                 break;
4443                         }
4444
4445                 default:
4446                         elog(ERROR, "unrecognized dtype: %d", target->dtype);
4447         }
4448 }
4449
4450 /*
4451  * exec_eval_datum                              Get current value of a PLpgSQL_datum
4452  *
4453  * The type oid, typmod, value in Datum format, and null flag are returned.
4454  *
4455  * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
4456  *
4457  * NOTE: caller must not modify the returned value, since it points right
4458  * at the stored value in the case of pass-by-reference datatypes.  In some
4459  * cases we have to palloc a return value, and in such cases we put it into
4460  * the estate's short-term memory context.
4461  */
4462 static void
4463 exec_eval_datum(PLpgSQL_execstate *estate,
4464                                 PLpgSQL_datum *datum,
4465                                 Oid *typeid,
4466                                 int32 *typetypmod,
4467                                 Datum *value,
4468                                 bool *isnull)
4469 {
4470         MemoryContext oldcontext;
4471
4472         switch (datum->dtype)
4473         {
4474                 case PLPGSQL_DTYPE_VAR:
4475                         {
4476                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4477
4478                                 *typeid = var->datatype->typoid;
4479                                 *typetypmod = var->datatype->atttypmod;
4480                                 *value = var->value;
4481                                 *isnull = var->isnull;
4482                                 break;
4483                         }
4484
4485                 case PLPGSQL_DTYPE_ROW:
4486                         {
4487                                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4488                                 HeapTuple       tup;
4489
4490                                 if (!row->rowtupdesc)   /* should not happen */
4491                                         elog(ERROR, "row variable has no tupdesc");
4492                                 /* Make sure we have a valid type/typmod setting */
4493                                 BlessTupleDesc(row->rowtupdesc);
4494                                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4495                                 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
4496                                 if (tup == NULL)        /* should not happen */
4497                                         elog(ERROR, "row not compatible with its own tupdesc");
4498                                 *typeid = row->rowtupdesc->tdtypeid;
4499                                 *typetypmod = row->rowtupdesc->tdtypmod;
4500                                 *value = HeapTupleGetDatum(tup);
4501                                 *isnull = false;
4502                                 MemoryContextSwitchTo(oldcontext);
4503                                 break;
4504                         }
4505
4506                 case PLPGSQL_DTYPE_REC:
4507                         {
4508                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4509
4510                                 if (!HeapTupleIsValid(rec->tup))
4511                                         ereport(ERROR,
4512                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4513                                                    errmsg("record \"%s\" is not assigned yet",
4514                                                                   rec->refname),
4515                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4516                                 Assert(rec->tupdesc != NULL);
4517                                 /* Make sure we have a valid type/typmod setting */
4518                                 BlessTupleDesc(rec->tupdesc);
4519
4520                                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4521                                 *typeid = rec->tupdesc->tdtypeid;
4522                                 *typetypmod = rec->tupdesc->tdtypmod;
4523                                 *value = heap_copy_tuple_as_datum(rec->tup, rec->tupdesc);
4524                                 *isnull = false;
4525                                 MemoryContextSwitchTo(oldcontext);
4526                                 break;
4527                         }
4528
4529                 case PLPGSQL_DTYPE_RECFIELD:
4530                         {
4531                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4532                                 PLpgSQL_rec *rec;
4533                                 int                     fno;
4534
4535                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4536                                 if (!HeapTupleIsValid(rec->tup))
4537                                         ereport(ERROR,
4538                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4539                                                    errmsg("record \"%s\" is not assigned yet",
4540                                                                   rec->refname),
4541                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4542                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4543                                 if (fno == SPI_ERROR_NOATTRIBUTE)
4544                                         ereport(ERROR,
4545                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4546                                                          errmsg("record \"%s\" has no field \"%s\"",
4547                                                                         rec->refname, recfield->fieldname)));
4548                                 *typeid = SPI_gettypeid(rec->tupdesc, fno);
4549                                 if (fno > 0)
4550                                         *typetypmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
4551                                 else
4552                                         *typetypmod = -1;
4553                                 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
4554                                 break;
4555                         }
4556
4557                 default:
4558                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4559         }
4560 }
4561
4562 /*
4563  * exec_get_datum_type                          Get datatype of a PLpgSQL_datum
4564  *
4565  * This is the same logic as in exec_eval_datum, except that it can handle
4566  * some cases where exec_eval_datum has to fail; specifically, we may have
4567  * a tupdesc but no row value for a record variable.  (This currently can
4568  * happen only for a trigger's NEW/OLD records.)
4569  */
4570 Oid
4571 exec_get_datum_type(PLpgSQL_execstate *estate,
4572                                         PLpgSQL_datum *datum)
4573 {
4574         Oid                     typeid;
4575
4576         switch (datum->dtype)
4577         {
4578                 case PLPGSQL_DTYPE_VAR:
4579                         {
4580                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4581
4582                                 typeid = var->datatype->typoid;
4583                                 break;
4584                         }
4585
4586                 case PLPGSQL_DTYPE_ROW:
4587                         {
4588                                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4589
4590                                 if (!row->rowtupdesc)   /* should not happen */
4591                                         elog(ERROR, "row variable has no tupdesc");
4592                                 /* Make sure we have a valid type/typmod setting */
4593                                 BlessTupleDesc(row->rowtupdesc);
4594                                 typeid = row->rowtupdesc->tdtypeid;
4595                                 break;
4596                         }
4597
4598                 case PLPGSQL_DTYPE_REC:
4599                         {
4600                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4601
4602                                 if (rec->tupdesc == NULL)
4603                                         ereport(ERROR,
4604                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4605                                                    errmsg("record \"%s\" is not assigned yet",
4606                                                                   rec->refname),
4607                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4608                                 /* Make sure we have a valid type/typmod setting */
4609                                 BlessTupleDesc(rec->tupdesc);
4610                                 typeid = rec->tupdesc->tdtypeid;
4611                                 break;
4612                         }
4613
4614                 case PLPGSQL_DTYPE_RECFIELD:
4615                         {
4616                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4617                                 PLpgSQL_rec *rec;
4618                                 int                     fno;
4619
4620                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4621                                 if (rec->tupdesc == NULL)
4622                                         ereport(ERROR,
4623                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4624                                                    errmsg("record \"%s\" is not assigned yet",
4625                                                                   rec->refname),
4626                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4627                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4628                                 if (fno == SPI_ERROR_NOATTRIBUTE)
4629                                         ereport(ERROR,
4630                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4631                                                          errmsg("record \"%s\" has no field \"%s\"",
4632                                                                         rec->refname, recfield->fieldname)));
4633                                 typeid = SPI_gettypeid(rec->tupdesc, fno);
4634                                 break;
4635                         }
4636
4637                 default:
4638                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4639                         typeid = InvalidOid;    /* keep compiler quiet */
4640                         break;
4641         }
4642
4643         return typeid;
4644 }
4645
4646 /*
4647  * exec_get_datum_type_info                     Get datatype etc of a PLpgSQL_datum
4648  *
4649  * An extended version of exec_get_datum_type, which also retrieves the
4650  * typmod and collation of the datum.
4651  */
4652 void
4653 exec_get_datum_type_info(PLpgSQL_execstate *estate,
4654                                                  PLpgSQL_datum *datum,
4655                                                  Oid *typeid, int32 *typmod, Oid *collation)
4656 {
4657         switch (datum->dtype)
4658         {
4659                 case PLPGSQL_DTYPE_VAR:
4660                         {
4661                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4662
4663                                 *typeid = var->datatype->typoid;
4664                                 *typmod = var->datatype->atttypmod;
4665                                 *collation = var->datatype->collation;
4666                                 break;
4667                         }
4668
4669                 case PLPGSQL_DTYPE_ROW:
4670                         {
4671                                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4672
4673                                 if (!row->rowtupdesc)   /* should not happen */
4674                                         elog(ERROR, "row variable has no tupdesc");
4675                                 /* Make sure we have a valid type/typmod setting */
4676                                 BlessTupleDesc(row->rowtupdesc);
4677                                 *typeid = row->rowtupdesc->tdtypeid;
4678                                 /* do NOT return the mutable typmod of a RECORD variable */
4679                                 *typmod = -1;
4680                                 /* composite types are never collatable */
4681                                 *collation = InvalidOid;
4682                                 break;
4683                         }
4684
4685                 case PLPGSQL_DTYPE_REC:
4686                         {
4687                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4688
4689                                 if (rec->tupdesc == NULL)
4690                                         ereport(ERROR,
4691                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4692                                                    errmsg("record \"%s\" is not assigned yet",
4693                                                                   rec->refname),
4694                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4695                                 /* Make sure we have a valid type/typmod setting */
4696                                 BlessTupleDesc(rec->tupdesc);
4697                                 *typeid = rec->tupdesc->tdtypeid;
4698                                 /* do NOT return the mutable typmod of a RECORD variable */
4699                                 *typmod = -1;
4700                                 /* composite types are never collatable */
4701                                 *collation = InvalidOid;
4702                                 break;
4703                         }
4704
4705                 case PLPGSQL_DTYPE_RECFIELD:
4706                         {
4707                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4708                                 PLpgSQL_rec *rec;
4709                                 int                     fno;
4710
4711                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4712                                 if (rec->tupdesc == NULL)
4713                                         ereport(ERROR,
4714                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4715                                                    errmsg("record \"%s\" is not assigned yet",
4716                                                                   rec->refname),
4717                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4718                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4719                                 if (fno == SPI_ERROR_NOATTRIBUTE)
4720                                         ereport(ERROR,
4721                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4722                                                          errmsg("record \"%s\" has no field \"%s\"",
4723                                                                         rec->refname, recfield->fieldname)));
4724                                 *typeid = SPI_gettypeid(rec->tupdesc, fno);
4725                                 if (fno > 0)
4726                                         *typmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
4727                                 else
4728                                         *typmod = -1;
4729                                 if (fno > 0)
4730                                         *collation = rec->tupdesc->attrs[fno - 1]->attcollation;
4731                                 else    /* no system column types have collation */
4732                                         *collation = InvalidOid;
4733                                 break;
4734                         }
4735
4736                 default:
4737                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4738                         *typeid = InvalidOid;           /* keep compiler quiet */
4739                         *typmod = -1;
4740                         *collation = InvalidOid;
4741                         break;
4742         }
4743 }
4744
4745 /* ----------
4746  * exec_eval_integer            Evaluate an expression, coerce result to int4
4747  *
4748  * Note we do not do exec_eval_cleanup here; the caller must do it at
4749  * some later point.  (We do this because the caller may be holding the
4750  * results of other, pass-by-reference, expression evaluations, such as
4751  * an array value to be subscripted.  Also see notes in exec_eval_simple_expr
4752  * about allocation of the parameter array.)
4753  * ----------
4754  */
4755 static int
4756 exec_eval_integer(PLpgSQL_execstate *estate,
4757                                   PLpgSQL_expr *expr,
4758                                   bool *isNull)
4759 {
4760         Datum           exprdatum;
4761         Oid                     exprtypeid;
4762         int32           exprtypmod;
4763
4764         exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
4765         exprdatum = exec_cast_value(estate, exprdatum, isNull,
4766                                                                 exprtypeid, exprtypmod,
4767                                                                 INT4OID, -1);
4768         return DatumGetInt32(exprdatum);
4769 }
4770
4771 /* ----------
4772  * exec_eval_boolean            Evaluate an expression, coerce result to bool
4773  *
4774  * Note we do not do exec_eval_cleanup here; the caller must do it at
4775  * some later point.
4776  * ----------
4777  */
4778 static bool
4779 exec_eval_boolean(PLpgSQL_execstate *estate,
4780                                   PLpgSQL_expr *expr,
4781                                   bool *isNull)
4782 {
4783         Datum           exprdatum;
4784         Oid                     exprtypeid;
4785         int32           exprtypmod;
4786
4787         exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
4788         exprdatum = exec_cast_value(estate, exprdatum, isNull,
4789                                                                 exprtypeid, exprtypmod,
4790                                                                 BOOLOID, -1);
4791         return DatumGetBool(exprdatum);
4792 }
4793
4794 /* ----------
4795  * exec_eval_expr                       Evaluate an expression and return
4796  *                                      the result Datum, along with data type/typmod.
4797  *
4798  * NOTE: caller must do exec_eval_cleanup when done with the Datum.
4799  * ----------
4800  */
4801 static Datum
4802 exec_eval_expr(PLpgSQL_execstate *estate,
4803                            PLpgSQL_expr *expr,
4804                            bool *isNull,
4805                            Oid *rettype,
4806                            int32 *rettypmod)
4807 {
4808         Datum           result = 0;
4809         int                     rc;
4810
4811         /*
4812          * If first time through, create a plan for this expression.
4813          */
4814         if (expr->plan == NULL)
4815                 exec_prepare_plan(estate, expr, 0);
4816
4817         /*
4818          * If this is a simple expression, bypass SPI and use the executor
4819          * directly
4820          */
4821         if (exec_eval_simple_expr(estate, expr,
4822                                                           &result, isNull, rettype, rettypmod))
4823                 return result;
4824
4825         /*
4826          * Else do it the hard way via exec_run_select
4827          */
4828         rc = exec_run_select(estate, expr, 2, NULL);
4829         if (rc != SPI_OK_SELECT)
4830                 ereport(ERROR,
4831                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4832                                  errmsg("query \"%s\" did not return data", expr->query)));
4833
4834         /*
4835          * Check that the expression returns exactly one column...
4836          */
4837         if (estate->eval_tuptable->tupdesc->natts != 1)
4838                 ereport(ERROR,
4839                                 (errcode(ERRCODE_SYNTAX_ERROR),
4840                                  errmsg_plural("query \"%s\" returned %d column",
4841                                                            "query \"%s\" returned %d columns",
4842                                                            estate->eval_tuptable->tupdesc->natts,
4843                                                            expr->query,
4844                                                            estate->eval_tuptable->tupdesc->natts)));
4845
4846         /*
4847          * ... and get the column's datatype.
4848          */
4849         *rettype = estate->eval_tuptable->tupdesc->attrs[0]->atttypid;
4850         *rettypmod = estate->eval_tuptable->tupdesc->attrs[0]->atttypmod;
4851
4852         /*
4853          * If there are no rows selected, the result is a NULL of that type.
4854          */
4855         if (estate->eval_processed == 0)
4856         {
4857                 *isNull = true;
4858                 return (Datum) 0;
4859         }
4860
4861         /*
4862          * Check that the expression returned no more than one row.
4863          */
4864         if (estate->eval_processed != 1)
4865                 ereport(ERROR,
4866                                 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4867                                  errmsg("query \"%s\" returned more than one row",
4868                                                 expr->query)));
4869
4870         /*
4871          * Return the single result Datum.
4872          */
4873         return SPI_getbinval(estate->eval_tuptable->vals[0],
4874                                                  estate->eval_tuptable->tupdesc, 1, isNull);
4875 }
4876
4877
4878 /* ----------
4879  * exec_run_select                      Execute a select query
4880  * ----------
4881  */
4882 static int
4883 exec_run_select(PLpgSQL_execstate *estate,
4884                                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4885 {
4886         ParamListInfo paramLI;
4887         int                     rc;
4888
4889         /*
4890          * On the first call for this expression generate the plan
4891          */
4892         if (expr->plan == NULL)
4893                 exec_prepare_plan(estate, expr, 0);
4894
4895         /*
4896          * Set up ParamListInfo (hook function and possibly data values)
4897          */
4898         paramLI = setup_param_list(estate, expr);
4899
4900         /*
4901          * If a portal was requested, put the query into the portal
4902          */
4903         if (portalP != NULL)
4904         {
4905                 *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
4906                                                                                                   paramLI,
4907                                                                                                   estate->readonly_func);
4908                 if (*portalP == NULL)
4909                         elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4910                                  expr->query, SPI_result_code_string(SPI_result));
4911                 if (paramLI)
4912                         pfree(paramLI);
4913                 return SPI_OK_CURSOR;
4914         }
4915
4916         /*
4917          * Execute the query
4918          */
4919         rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4920                                                                                  estate->readonly_func, maxtuples);
4921         if (rc != SPI_OK_SELECT)
4922                 ereport(ERROR,
4923                                 (errcode(ERRCODE_SYNTAX_ERROR),
4924                                  errmsg("query \"%s\" is not a SELECT", expr->query)));
4925
4926         /* Save query results for eventual cleanup */
4927         Assert(estate->eval_tuptable == NULL);
4928         estate->eval_tuptable = SPI_tuptable;
4929         estate->eval_processed = SPI_processed;
4930         estate->eval_lastoid = SPI_lastoid;
4931
4932         if (paramLI)
4933                 pfree(paramLI);
4934
4935         return rc;
4936 }
4937
4938
4939 /*
4940  * exec_for_query --- execute body of FOR loop for each row from a portal
4941  *
4942  * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
4943  */
4944 static int
4945 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
4946                            Portal portal, bool prefetch_ok)
4947 {
4948         PLpgSQL_rec *rec = NULL;
4949         PLpgSQL_row *row = NULL;
4950         SPITupleTable *tuptab;
4951         bool            found = false;
4952         int                     rc = PLPGSQL_RC_OK;
4953         int                     n;
4954
4955         /*
4956          * Determine if we assign to a record or a row
4957          */
4958         if (stmt->rec != NULL)
4959                 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
4960         else if (stmt->row != NULL)
4961                 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
4962         else
4963                 elog(ERROR, "unsupported target");
4964
4965         /*
4966          * Make sure the portal doesn't get closed by the user statements we
4967          * execute.
4968          */
4969         PinPortal(portal);
4970
4971         /*
4972          * Fetch the initial tuple(s).  If prefetching is allowed then we grab a
4973          * few more rows to avoid multiple trips through executor startup
4974          * overhead.
4975          */
4976         SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
4977         tuptab = SPI_tuptable;
4978         n = SPI_processed;
4979
4980         /*
4981          * If the query didn't return any rows, set the target to NULL and fall
4982          * through with found = false.
4983          */
4984         if (n <= 0)
4985         {
4986                 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
4987                 exec_eval_cleanup(estate);
4988         }
4989         else
4990                 found = true;                   /* processed at least one tuple */
4991
4992         /*
4993          * Now do the loop
4994          */
4995         while (n > 0)
4996         {
4997                 int                     i;
4998
4999                 for (i = 0; i < n; i++)
5000                 {
5001                         /*
5002                          * Assign the tuple to the target
5003                          */
5004                         exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
5005                         exec_eval_cleanup(estate);
5006
5007                         /*
5008                          * Execute the statements
5009                          */
5010                         rc = exec_stmts(estate, stmt->body);
5011
5012                         if (rc != PLPGSQL_RC_OK)
5013                         {
5014                                 if (rc == PLPGSQL_RC_EXIT)
5015                                 {
5016                                         if (estate->exitlabel == NULL)
5017                                         {
5018                                                 /* unlabelled exit, so exit the current loop */
5019                                                 rc = PLPGSQL_RC_OK;
5020                                         }
5021                                         else if (stmt->label != NULL &&
5022                                                          strcmp(stmt->label, estate->exitlabel) == 0)
5023                                         {
5024                                                 /* label matches this loop, so exit loop */
5025                                                 estate->exitlabel = NULL;
5026                                                 rc = PLPGSQL_RC_OK;
5027                                         }
5028
5029                                         /*
5030                                          * otherwise, we processed a labelled exit that does not
5031                                          * match the current statement's label, if any; return
5032                                          * RC_EXIT so that the EXIT continues to recurse upward.
5033                                          */
5034                                 }
5035                                 else if (rc == PLPGSQL_RC_CONTINUE)
5036                                 {
5037                                         if (estate->exitlabel == NULL)
5038                                         {
5039                                                 /* unlabelled continue, so re-run the current loop */
5040                                                 rc = PLPGSQL_RC_OK;
5041                                                 continue;
5042                                         }
5043                                         else if (stmt->label != NULL &&
5044                                                          strcmp(stmt->label, estate->exitlabel) == 0)
5045                                         {
5046                                                 /* label matches this loop, so re-run loop */
5047                                                 estate->exitlabel = NULL;
5048                                                 rc = PLPGSQL_RC_OK;
5049                                                 continue;
5050                                         }
5051
5052                                         /*
5053                                          * otherwise, we process a labelled continue that does not
5054                                          * match the current statement's label, if any; return
5055                                          * RC_CONTINUE so that the CONTINUE will propagate up the
5056                                          * stack.
5057                                          */
5058                                 }
5059
5060                                 /*
5061                                  * We're aborting the loop.  Need a goto to get out of two
5062                                  * levels of loop...
5063                                  */
5064                                 goto loop_exit;
5065                         }
5066                 }
5067
5068                 SPI_freetuptable(tuptab);
5069
5070                 /*
5071                  * Fetch more tuples.  If prefetching is allowed, grab 50 at a time.
5072                  */
5073                 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
5074                 tuptab = SPI_tuptable;
5075                 n = SPI_processed;
5076         }
5077
5078 loop_exit:
5079
5080         /*
5081          * Release last group of tuples (if any)
5082          */
5083         SPI_freetuptable(tuptab);
5084
5085         UnpinPortal(portal);
5086
5087         /*
5088          * Set the FOUND variable to indicate the result of executing the loop
5089          * (namely, whether we looped one or more times). This must be set last so
5090          * that it does not interfere with the value of the FOUND variable inside
5091          * the loop processing itself.
5092          */
5093         exec_set_found(estate, found);
5094
5095         return rc;
5096 }
5097
5098
5099 /* ----------
5100  * exec_eval_simple_expr -              Evaluate a simple expression returning
5101  *                                                              a Datum by directly calling ExecEvalExpr().
5102  *
5103  * If successful, store results into *result, *isNull, *rettype, *rettypmod
5104  * and return TRUE.  If the expression cannot be handled by simple evaluation,
5105  * return FALSE.
5106  *
5107  * Because we only store one execution tree for a simple expression, we
5108  * can't handle recursion cases.  So, if we see the tree is already busy
5109  * with an evaluation in the current xact, we just return FALSE and let the
5110  * caller run the expression the hard way.  (Other alternatives such as
5111  * creating a new tree for a recursive call either introduce memory leaks,
5112  * or add enough bookkeeping to be doubtful wins anyway.)  Another case that
5113  * is covered by the expr_simple_in_use test is where a previous execution
5114  * of the tree was aborted by an error: the tree may contain bogus state
5115  * so we dare not re-use it.
5116  *
5117  * It is possible though unlikely for a simple expression to become non-simple
5118  * (consider for example redefining a trivial view).  We must handle that for
5119  * correctness; fortunately it's normally inexpensive to call
5120  * SPI_plan_get_cached_plan for a simple expression.  We do not consider the
5121  * other direction (non-simple expression becoming simple) because we'll still
5122  * give correct results if that happens, and it's unlikely to be worth the
5123  * cycles to check.
5124  *
5125  * Note: if pass-by-reference, the result is in the eval_econtext's
5126  * temporary memory context.  It will be freed when exec_eval_cleanup
5127  * is done.
5128  * ----------
5129  */
5130 static bool
5131 exec_eval_simple_expr(PLpgSQL_execstate *estate,
5132                                           PLpgSQL_expr *expr,
5133                                           Datum *result,
5134                                           bool *isNull,
5135                                           Oid *rettype,
5136                                           int32 *rettypmod)
5137 {
5138         ExprContext *econtext = estate->eval_econtext;
5139         LocalTransactionId curlxid = MyProc->lxid;
5140         CachedPlan *cplan;
5141         ParamListInfo paramLI;
5142         PLpgSQL_expr *save_cur_expr;
5143         MemoryContext oldcontext;
5144
5145         /*
5146          * Forget it if expression wasn't simple before.
5147          */
5148         if (expr->expr_simple_expr == NULL)
5149                 return false;
5150
5151         /*
5152          * If expression is in use in current xact, don't touch it.
5153          */
5154         if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
5155                 return false;
5156
5157         /*
5158          * Revalidate cached plan, so that we will notice if it became stale. (We
5159          * need to hold a refcount while using the plan, anyway.)
5160          */
5161         cplan = SPI_plan_get_cached_plan(expr->plan);
5162
5163         /*
5164          * We can't get a failure here, because the number of CachedPlanSources in
5165          * the SPI plan can't change from what exec_simple_check_plan saw; it's a
5166          * property of the raw parsetree generated from the query text.
5167          */
5168         Assert(cplan != NULL);
5169
5170         if (cplan->generation != expr->expr_simple_generation)
5171         {
5172                 /* It got replanned ... is it still simple? */
5173                 exec_simple_recheck_plan(expr, cplan);
5174                 if (expr->expr_simple_expr == NULL)
5175                 {
5176                         /* Ooops, release refcount and fail */
5177                         ReleaseCachedPlan(cplan, true);
5178                         return false;
5179                 }
5180         }
5181
5182         /*
5183          * Pass back previously-determined result type.
5184          */
5185         *rettype = expr->expr_simple_type;
5186         *rettypmod = expr->expr_simple_typmod;
5187
5188         /*
5189          * Prepare the expression for execution, if it's not been done already in
5190          * the current transaction.  (This will be forced to happen if we called
5191          * exec_simple_recheck_plan above.)
5192          */
5193         if (expr->expr_simple_lxid != curlxid)
5194         {
5195                 oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
5196                 expr->expr_simple_state = ExecInitExpr(expr->expr_simple_expr, NULL);
5197                 expr->expr_simple_in_use = false;
5198                 expr->expr_simple_lxid = curlxid;
5199                 MemoryContextSwitchTo(oldcontext);
5200         }
5201
5202         /*
5203          * We have to do some of the things SPI_execute_plan would do, in
5204          * particular advance the snapshot if we are in a non-read-only function.
5205          * Without this, stable functions within the expression would fail to see
5206          * updates made so far by our own function.
5207          */
5208         SPI_push();
5209
5210         oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
5211         if (!estate->readonly_func)
5212         {
5213                 CommandCounterIncrement();
5214                 PushActiveSnapshot(GetTransactionSnapshot());
5215         }
5216
5217         /*
5218          * Create the param list in econtext's temporary memory context. We won't
5219          * need to free it explicitly, since it will go away at the next reset of
5220          * that context.
5221          *
5222          * Just for paranoia's sake, save and restore the prior value of
5223          * estate->cur_expr, which setup_param_list() sets.
5224          */
5225         save_cur_expr = estate->cur_expr;
5226
5227         paramLI = setup_param_list(estate, expr);
5228         econtext->ecxt_param_list_info = paramLI;
5229
5230         /*
5231          * Mark expression as busy for the duration of the ExecEvalExpr call.
5232          */
5233         expr->expr_simple_in_use = true;
5234
5235         /*
5236          * Finally we can call the executor to evaluate the expression
5237          */
5238         *result = ExecEvalExpr(expr->expr_simple_state,
5239                                                    econtext,
5240                                                    isNull,
5241                                                    NULL);
5242
5243         /* Assorted cleanup */
5244         expr->expr_simple_in_use = false;
5245
5246         estate->cur_expr = save_cur_expr;
5247
5248         if (!estate->readonly_func)
5249                 PopActiveSnapshot();
5250
5251         MemoryContextSwitchTo(oldcontext);
5252
5253         SPI_pop();
5254
5255         /*
5256          * Now we can release our refcount on the cached plan.
5257          */
5258         ReleaseCachedPlan(cplan, true);
5259
5260         /*
5261          * That's it.
5262          */
5263         return true;
5264 }
5265
5266
5267 /*
5268  * Create a ParamListInfo to pass to SPI
5269  *
5270  * We fill in the values for any expression parameters that are plain
5271  * PLpgSQL_var datums; these are cheap and safe to evaluate, and by setting
5272  * them with PARAM_FLAG_CONST flags, we allow the planner to use those values
5273  * in custom plans.  However, parameters that are not plain PLpgSQL_vars
5274  * should not be evaluated here, because they could throw errors (for example
5275  * "no such record field") and we do not want that to happen in a part of
5276  * the expression that might never be evaluated at runtime.  To handle those
5277  * parameters, we set up a paramFetch hook for the executor to call when it
5278  * wants a not-presupplied value.
5279  *
5280  * The result is a locally palloc'd array that should be pfree'd after use;
5281  * but note it can be NULL.
5282  */
5283 static ParamListInfo
5284 setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
5285 {
5286         ParamListInfo paramLI;
5287
5288         /*
5289          * We must have created the SPIPlan already (hence, query text has been
5290          * parsed/analyzed at least once); else we cannot rely on expr->paramnos.
5291          */
5292         Assert(expr->plan != NULL);
5293
5294         /*
5295          * Could we re-use these arrays instead of palloc'ing a new one each time?
5296          * However, we'd have to re-fill the array each time anyway, since new
5297          * values might have been assigned to the variables.
5298          */
5299         if (!bms_is_empty(expr->paramnos))
5300         {
5301                 int                     dno;
5302
5303                 paramLI = (ParamListInfo)
5304                         palloc0(offsetof(ParamListInfoData, params) +
5305                                         estate->ndatums * sizeof(ParamExternData));
5306                 paramLI->paramFetch = plpgsql_param_fetch;
5307                 paramLI->paramFetchArg = (void *) estate;
5308                 paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
5309                 paramLI->parserSetupArg = (void *) expr;
5310                 paramLI->numParams = estate->ndatums;
5311
5312                 /* Instantiate values for "safe" parameters of the expression */
5313                 dno = -1;
5314                 while ((dno = bms_next_member(expr->paramnos, dno)) >= 0)
5315                 {
5316                         PLpgSQL_datum *datum = estate->datums[dno];
5317
5318                         if (datum->dtype == PLPGSQL_DTYPE_VAR)
5319                         {
5320                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
5321                                 ParamExternData *prm = &paramLI->params[dno];
5322
5323                                 prm->value = var->value;
5324                                 prm->isnull = var->isnull;
5325                                 prm->pflags = PARAM_FLAG_CONST;
5326                                 prm->ptype = var->datatype->typoid;
5327                         }
5328                 }
5329
5330                 /*
5331                  * Set up link to active expr where the hook functions can find it.
5332                  * Callers must save and restore cur_expr if there is any chance that
5333                  * they are interrupting an active use of parameters.
5334                  */
5335                 estate->cur_expr = expr;
5336
5337                 /*
5338                  * Also make sure this is set before parser hooks need it.  There is
5339                  * no need to save and restore, since the value is always correct once
5340                  * set.  (Should be set already, but let's be sure.)
5341                  */
5342                 expr->func = estate->func;
5343         }
5344         else
5345         {
5346                 /*
5347                  * Expression requires no parameters.  Be sure we represent this case
5348                  * as a NULL ParamListInfo, so that plancache.c knows there is no
5349                  * point in a custom plan.
5350                  */
5351                 paramLI = NULL;
5352         }
5353         return paramLI;
5354 }
5355
5356 /*
5357  * plpgsql_param_fetch          paramFetch callback for dynamic parameter fetch
5358  */
5359 static void
5360 plpgsql_param_fetch(ParamListInfo params, int paramid)
5361 {
5362         int                     dno;
5363         PLpgSQL_execstate *estate;
5364         PLpgSQL_expr *expr;
5365         PLpgSQL_datum *datum;
5366         ParamExternData *prm;
5367         int32           prmtypmod;
5368
5369         /* paramid's are 1-based, but dnos are 0-based */
5370         dno = paramid - 1;
5371         Assert(dno >= 0 && dno < params->numParams);
5372
5373         /* fetch back the hook data */
5374         estate = (PLpgSQL_execstate *) params->paramFetchArg;
5375         expr = estate->cur_expr;
5376         Assert(params->numParams == estate->ndatums);
5377
5378         /*
5379          * Do nothing if asked for a value that's not supposed to be used by this
5380          * SQL expression.  This avoids unwanted evaluations when functions such
5381          * as copyParamList try to materialize all the values.
5382          */
5383         if (!bms_is_member(dno, expr->paramnos))
5384                 return;
5385
5386         /* OK, evaluate the value and store into the appropriate paramlist slot */
5387         datum = estate->datums[dno];
5388         prm = &params->params[dno];
5389         exec_eval_datum(estate, datum,
5390                                         &prm->ptype, &prmtypmod,
5391                                         &prm->value, &prm->isnull);
5392 }
5393
5394
5395 /* ----------
5396  * exec_move_row                        Move one tuple's values into a record or row
5397  *
5398  * Since this uses exec_assign_value, caller should eventually call
5399  * exec_eval_cleanup to prevent long-term memory leaks.
5400  * ----------
5401  */
5402 static void
5403 exec_move_row(PLpgSQL_execstate *estate,
5404                           PLpgSQL_rec *rec,
5405                           PLpgSQL_row *row,
5406                           HeapTuple tup, TupleDesc tupdesc)
5407 {
5408         /*
5409          * Record is simple - just copy the tuple and its descriptor into the
5410          * record variable
5411          */
5412         if (rec != NULL)
5413         {
5414                 /*
5415                  * Copy input first, just in case it is pointing at variable's value
5416                  */
5417                 if (HeapTupleIsValid(tup))
5418                         tup = heap_copytuple(tup);
5419                 else if (tupdesc)
5420                 {
5421                         /* If we have a tupdesc but no data, form an all-nulls tuple */
5422                         bool       *nulls;
5423
5424                         nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
5425                         memset(nulls, true, tupdesc->natts * sizeof(bool));
5426
5427                         tup = heap_form_tuple(tupdesc, NULL, nulls);
5428
5429                         pfree(nulls);
5430                 }
5431
5432                 if (tupdesc)
5433                         tupdesc = CreateTupleDescCopy(tupdesc);
5434
5435                 /* Free the old value ... */
5436                 if (rec->freetup)
5437                 {
5438                         heap_freetuple(rec->tup);
5439                         rec->freetup = false;
5440                 }
5441                 if (rec->freetupdesc)
5442                 {
5443                         FreeTupleDesc(rec->tupdesc);
5444                         rec->freetupdesc = false;
5445                 }
5446
5447                 /* ... and install the new */
5448                 if (HeapTupleIsValid(tup))
5449                 {
5450                         rec->tup = tup;
5451                         rec->freetup = true;
5452                 }
5453                 else
5454                         rec->tup = NULL;
5455
5456                 if (tupdesc)
5457                 {
5458                         rec->tupdesc = tupdesc;
5459                         rec->freetupdesc = true;
5460                 }
5461                 else
5462                         rec->tupdesc = NULL;
5463
5464                 return;
5465         }
5466
5467         /*
5468          * Row is a bit more complicated in that we assign the individual
5469          * attributes of the tuple to the variables the row points to.
5470          *
5471          * NOTE: this code used to demand row->nfields ==
5472          * HeapTupleHeaderGetNatts(tup->t_data), but that's wrong.  The tuple
5473          * might have more fields than we expected if it's from an
5474          * inheritance-child table of the current table, or it might have fewer if
5475          * the table has had columns added by ALTER TABLE. Ignore extra columns
5476          * and assume NULL for missing columns, the same as heap_getattr would do.
5477          * We also have to skip over dropped columns in either the source or
5478          * destination.
5479          *
5480          * If we have no tuple data at all, we'll assign NULL to all columns of
5481          * the row variable.
5482          */
5483         if (row != NULL)
5484         {
5485                 int                     td_natts = tupdesc ? tupdesc->natts : 0;
5486                 int                     t_natts;
5487                 int                     fnum;
5488                 int                     anum;
5489
5490                 if (HeapTupleIsValid(tup))
5491                         t_natts = HeapTupleHeaderGetNatts(tup->t_data);
5492                 else
5493                         t_natts = 0;
5494
5495                 anum = 0;
5496                 for (fnum = 0; fnum < row->nfields; fnum++)
5497                 {
5498                         PLpgSQL_var *var;
5499                         Datum           value;
5500                         bool            isnull;
5501                         Oid                     valtype;
5502                         int32           valtypmod;
5503
5504                         if (row->varnos[fnum] < 0)
5505                                 continue;               /* skip dropped column in row struct */
5506
5507                         var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
5508
5509                         while (anum < td_natts && tupdesc->attrs[anum]->attisdropped)
5510                                 anum++;                 /* skip dropped column in tuple */
5511
5512                         if (anum < td_natts)
5513                         {
5514                                 if (anum < t_natts)
5515                                         value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
5516                                 else
5517                                 {
5518                                         value = (Datum) 0;
5519                                         isnull = true;
5520                                 }
5521                                 valtype = tupdesc->attrs[anum]->atttypid;
5522                                 valtypmod = tupdesc->attrs[anum]->atttypmod;
5523                                 anum++;
5524                         }
5525                         else
5526                         {
5527                                 value = (Datum) 0;
5528                                 isnull = true;
5529                                 valtype = UNKNOWNOID;
5530                                 valtypmod = -1;
5531                         }
5532
5533                         exec_assign_value(estate, (PLpgSQL_datum *) var,
5534                                                           value, isnull, valtype, valtypmod);
5535                 }
5536
5537                 return;
5538         }
5539
5540         elog(ERROR, "unsupported target");
5541 }
5542
5543 /* ----------
5544  * make_tuple_from_row          Make a tuple from the values of a row object
5545  *
5546  * A NULL return indicates rowtype mismatch; caller must raise suitable error
5547  * ----------
5548  */
5549 static HeapTuple
5550 make_tuple_from_row(PLpgSQL_execstate *estate,
5551                                         PLpgSQL_row *row,
5552                                         TupleDesc tupdesc)
5553 {
5554         int                     natts = tupdesc->natts;
5555         HeapTuple       tuple;
5556         Datum      *dvalues;
5557         bool       *nulls;
5558         int                     i;
5559
5560         if (natts != row->nfields)
5561                 return NULL;
5562
5563         dvalues = (Datum *) palloc0(natts * sizeof(Datum));
5564         nulls = (bool *) palloc(natts * sizeof(bool));
5565
5566         for (i = 0; i < natts; i++)
5567         {
5568                 Oid                     fieldtypeid;
5569                 int32           fieldtypmod;
5570
5571                 if (tupdesc->attrs[i]->attisdropped)
5572                 {
5573                         nulls[i] = true;        /* leave the column as null */
5574                         continue;
5575                 }
5576                 if (row->varnos[i] < 0) /* should not happen */
5577                         elog(ERROR, "dropped rowtype entry for non-dropped column");
5578
5579                 exec_eval_datum(estate, estate->datums[row->varnos[i]],
5580                                                 &fieldtypeid, &fieldtypmod,
5581                                                 &dvalues[i], &nulls[i]);
5582                 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
5583                         return NULL;
5584                 /* XXX should we insist on typmod match, too? */
5585         }
5586
5587         tuple = heap_form_tuple(tupdesc, dvalues, nulls);
5588
5589         pfree(dvalues);
5590         pfree(nulls);
5591
5592         return tuple;
5593 }
5594
5595 /* ----------
5596  * get_tuple_from_datum         extract a tuple from a composite Datum
5597  *
5598  * Returns a freshly palloc'd HeapTuple.
5599  *
5600  * Note: it's caller's responsibility to be sure value is of composite type.
5601  * ----------
5602  */
5603 static HeapTuple
5604 get_tuple_from_datum(Datum value)
5605 {
5606         HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5607         HeapTupleData tmptup;
5608
5609         /* Build a temporary HeapTuple control structure */
5610         tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
5611         ItemPointerSetInvalid(&(tmptup.t_self));
5612         tmptup.t_tableOid = InvalidOid;
5613         tmptup.t_data = td;
5614
5615         /* Build a copy and return it */
5616         return heap_copytuple(&tmptup);
5617 }
5618
5619 /* ----------
5620  * get_tupdesc_from_datum       get a tuple descriptor for a composite Datum
5621  *
5622  * Returns a pointer to the TupleDesc of the tuple's rowtype.
5623  * Caller is responsible for calling ReleaseTupleDesc when done with it.
5624  *
5625  * Note: it's caller's responsibility to be sure value is of composite type.
5626  * ----------
5627  */
5628 static TupleDesc
5629 get_tupdesc_from_datum(Datum value)
5630 {
5631         HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5632         Oid                     tupType;
5633         int32           tupTypmod;
5634
5635         /* Extract rowtype info and find a tupdesc */
5636         tupType = HeapTupleHeaderGetTypeId(td);
5637         tupTypmod = HeapTupleHeaderGetTypMod(td);
5638         return lookup_rowtype_tupdesc(tupType, tupTypmod);
5639 }
5640
5641 /* ----------
5642  * exec_move_row_from_datum             Move a composite Datum into a record or row
5643  *
5644  * This is equivalent to get_tuple_from_datum() followed by exec_move_row(),
5645  * but we avoid constructing an intermediate physical copy of the tuple.
5646  * ----------
5647  */
5648 static void
5649 exec_move_row_from_datum(PLpgSQL_execstate *estate,
5650                                                  PLpgSQL_rec *rec,
5651                                                  PLpgSQL_row *row,
5652                                                  Datum value)
5653 {
5654         HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5655         Oid                     tupType;
5656         int32           tupTypmod;
5657         TupleDesc       tupdesc;
5658         HeapTupleData tmptup;
5659
5660         /* Extract rowtype info and find a tupdesc */
5661         tupType = HeapTupleHeaderGetTypeId(td);
5662         tupTypmod = HeapTupleHeaderGetTypMod(td);
5663         tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
5664
5665         /* Build a temporary HeapTuple control structure */
5666         tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
5667         ItemPointerSetInvalid(&(tmptup.t_self));
5668         tmptup.t_tableOid = InvalidOid;
5669         tmptup.t_data = td;
5670
5671         /* Do the move */
5672         exec_move_row(estate, rec, row, &tmptup, tupdesc);
5673
5674         /* Release tupdesc usage count */
5675         ReleaseTupleDesc(tupdesc);
5676 }
5677
5678 /* ----------
5679  * convert_value_to_string                      Convert a non-null Datum to C string
5680  *
5681  * Note: the result is in the estate's eval_econtext, and will be cleared
5682  * by the next exec_eval_cleanup() call.  The invoked output function might
5683  * leave additional cruft there as well, so just pfree'ing the result string
5684  * would not be enough to avoid memory leaks if we did not do it like this.
5685  * In most usages the Datum being passed in is also in that context (if
5686  * pass-by-reference) and so an exec_eval_cleanup() call is needed anyway.
5687  *
5688  * Note: not caching the conversion function lookup is bad for performance.
5689  * However, this function isn't currently used in any places where an extra
5690  * catalog lookup or two seems like a big deal.
5691  * ----------
5692  */
5693 static char *
5694 convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
5695 {
5696         char       *result;
5697         MemoryContext oldcontext;
5698         Oid                     typoutput;
5699         bool            typIsVarlena;
5700
5701         oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
5702         getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
5703         result = OidOutputFunctionCall(typoutput, value);
5704         MemoryContextSwitchTo(oldcontext);
5705
5706         return result;
5707 }
5708
5709 /* ----------
5710  * exec_cast_value                      Cast a value if required
5711  *
5712  * Note that *isnull is an input and also an output parameter.  While it's
5713  * unlikely that a cast operation would produce null from non-null or vice
5714  * versa, that could happen in principle.
5715  *
5716  * Note: the estate's eval_econtext is used for temporary storage, and may
5717  * also contain the result Datum if we have to do a conversion to a pass-
5718  * by-reference data type.  Be sure to do an exec_eval_cleanup() call when
5719  * done with the result.
5720  * ----------
5721  */
5722 static Datum
5723 exec_cast_value(PLpgSQL_execstate *estate,
5724                                 Datum value, bool *isnull,
5725                                 Oid valtype, int32 valtypmod,
5726                                 Oid reqtype, int32 reqtypmod)
5727 {
5728         /*
5729          * If the type of the given value isn't what's requested, convert it.
5730          */
5731         if (valtype != reqtype ||
5732                 (valtypmod != reqtypmod && reqtypmod != -1))
5733         {
5734                 ExprState  *cast_expr;
5735
5736                 cast_expr = get_cast_expression(estate, valtype, reqtype, reqtypmod);
5737                 if (cast_expr)
5738                 {
5739                         ExprContext *econtext = estate->eval_econtext;
5740                         MemoryContext oldcontext;
5741
5742                         oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
5743
5744                         econtext->caseValue_datum = value;
5745                         econtext->caseValue_isNull = *isnull;
5746
5747                         value = ExecEvalExpr(cast_expr, econtext, isnull, NULL);
5748
5749                         MemoryContextSwitchTo(oldcontext);
5750                 }
5751         }
5752
5753         return value;
5754 }
5755
5756 /* ----------
5757  * get_cast_expression                  Look up how to perform a type cast
5758  *
5759  * Returns an expression evaluation tree based on a CaseTestExpr input,
5760  * or NULL if the cast is a mere no-op relabeling.
5761  *
5762  * We cache the results of the lookup in a per-function hash table.
5763  * It's tempting to consider using a session-wide hash table instead,
5764  * but that introduces some corner-case questions that probably aren't
5765  * worth dealing with; in particular that re-entrant use of an evaluation
5766  * tree might occur.  That would also set in stone the assumption that
5767  * collation isn't important to a cast function.
5768  * ----------
5769  */
5770 static ExprState *
5771 get_cast_expression(PLpgSQL_execstate *estate,
5772                                         Oid srctype, Oid dsttype, int32 dsttypmod)
5773 {
5774         HTAB       *cast_hash = estate->func->cast_hash;
5775         plpgsql_CastHashKey cast_key;
5776         plpgsql_CastHashEntry *cast_entry;
5777         bool            found;
5778         CaseTestExpr *placeholder;
5779         Node       *cast_expr;
5780         ExprState  *cast_exprstate;
5781         MemoryContext oldcontext;
5782
5783         /* Create the cast-info hash table if we didn't already */
5784         if (cast_hash == NULL)
5785         {
5786                 HASHCTL         ctl;
5787
5788                 memset(&ctl, 0, sizeof(ctl));
5789                 ctl.keysize = sizeof(plpgsql_CastHashKey);
5790                 ctl.entrysize = sizeof(plpgsql_CastHashEntry);
5791                 ctl.hcxt = estate->func->fn_cxt;
5792                 cast_hash = hash_create("PLpgSQL cast cache",
5793                                                                 16,             /* start small and extend */
5794                                                                 &ctl,
5795                                                                 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5796                 estate->func->cast_hash = cast_hash;
5797         }
5798
5799         /* Look for existing entry */
5800         cast_key.srctype = srctype;
5801         cast_key.dsttype = dsttype;
5802         cast_key.dsttypmod = dsttypmod;
5803         cast_entry = (plpgsql_CastHashEntry *) hash_search(cast_hash,
5804                                                                                                            (void *) &cast_key,
5805                                                                                                            HASH_FIND, NULL);
5806         if (cast_entry)
5807                 return cast_entry->cast_exprstate;
5808
5809         /* Construct expression tree for coercion in function's context */
5810         oldcontext = MemoryContextSwitchTo(estate->func->fn_cxt);
5811
5812         /*
5813          * We use a CaseTestExpr as the base of the coercion tree, since it's very
5814          * cheap to insert the source value for that.
5815          */
5816         placeholder = makeNode(CaseTestExpr);
5817         placeholder->typeId = srctype;
5818         placeholder->typeMod = -1;
5819         placeholder->collation = get_typcollation(srctype);
5820         if (OidIsValid(estate->func->fn_input_collation) &&
5821                 OidIsValid(placeholder->collation))
5822                 placeholder->collation = estate->func->fn_input_collation;
5823
5824         /*
5825          * Apply coercion.  We use ASSIGNMENT coercion because that's the closest
5826          * match to plpgsql's historical behavior; in particular, EXPLICIT
5827          * coercion would allow silent truncation to a destination
5828          * varchar/bpchar's length, which we do not want.
5829          *
5830          * If source type is UNKNOWN, coerce_to_target_type will fail (it only
5831          * expects to see that for Const input nodes), so don't call it; we'll
5832          * apply CoerceViaIO instead.
5833          */
5834         if (srctype != UNKNOWNOID)
5835                 cast_expr = coerce_to_target_type(NULL,
5836                                                                                   (Node *) placeholder, srctype,
5837                                                                                   dsttype, dsttypmod,
5838                                                                                   COERCION_ASSIGNMENT,
5839                                                                                   COERCE_IMPLICIT_CAST,
5840                                                                                   -1);
5841         else
5842                 cast_expr = NULL;
5843
5844         /*
5845          * If there's no cast path according to the parser, fall back to using an
5846          * I/O coercion; this is semantically dubious but matches plpgsql's
5847          * historical behavior.  We would need something of the sort for UNKNOWN
5848          * literals in any case.
5849          */
5850         if (cast_expr == NULL)
5851         {
5852                 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
5853
5854                 iocoerce->arg = (Expr *) placeholder;
5855                 iocoerce->resulttype = dsttype;
5856                 iocoerce->resultcollid = InvalidOid;
5857                 iocoerce->coerceformat = COERCE_IMPLICIT_CAST;
5858                 iocoerce->location = -1;
5859                 cast_expr = (Node *) iocoerce;
5860                 if (dsttypmod != -1)
5861                         cast_expr = coerce_to_target_type(NULL,
5862                                                                                           cast_expr, dsttype,
5863                                                                                           dsttype, dsttypmod,
5864                                                                                           COERCION_ASSIGNMENT,
5865                                                                                           COERCE_IMPLICIT_CAST,
5866                                                                                           -1);
5867         }
5868
5869         /* Note: we don't bother labeling the expression tree with collation */
5870
5871         /* Detect whether we have a no-op (RelabelType) coercion */
5872         if (IsA(cast_expr, RelabelType) &&
5873                 ((RelabelType *) cast_expr)->arg == (Expr *) placeholder)
5874                 cast_expr = NULL;
5875
5876         if (cast_expr)
5877         {
5878                 /* ExecInitExpr assumes we've planned the expression */
5879                 cast_expr = (Node *) expression_planner((Expr *) cast_expr);
5880                 /* Create an expression eval state tree for it */
5881                 cast_exprstate = ExecInitExpr((Expr *) cast_expr, NULL);
5882         }
5883         else
5884                 cast_exprstate = NULL;
5885
5886         MemoryContextSwitchTo(oldcontext);
5887
5888         /*
5889          * Now fill in a hashtable entry.  If we fail anywhere up to/including
5890          * this step, we've only leaked some memory in the function context, which
5891          * isn't great but isn't disastrous either.
5892          */
5893         cast_entry = (plpgsql_CastHashEntry *) hash_search(cast_hash,
5894                                                                                                            (void *) &cast_key,
5895                                                                                                            HASH_ENTER, &found);
5896         Assert(!found);                         /* wasn't there a moment ago */
5897
5898         cast_entry->cast_exprstate = cast_exprstate;
5899
5900         return cast_exprstate;
5901 }
5902
5903 /* ----------
5904  * exec_simple_check_node -             Recursively check if an expression
5905  *                                                              is made only of simple things we can
5906  *                                                              hand out directly to ExecEvalExpr()
5907  *                                                              instead of calling SPI.
5908  * ----------
5909  */
5910 static bool
5911 exec_simple_check_node(Node *node)
5912 {
5913         if (node == NULL)
5914                 return TRUE;
5915
5916         switch (nodeTag(node))
5917         {
5918                 case T_Const:
5919                         return TRUE;
5920
5921                 case T_Param:
5922                         return TRUE;
5923
5924                 case T_ArrayRef:
5925                         {
5926                                 ArrayRef   *expr = (ArrayRef *) node;
5927
5928                                 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
5929                                         return FALSE;
5930                                 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
5931                                         return FALSE;
5932                                 if (!exec_simple_check_node((Node *) expr->refexpr))
5933                                         return FALSE;
5934                                 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
5935                                         return FALSE;
5936
5937                                 return TRUE;
5938                         }
5939
5940                 case T_FuncExpr:
5941                         {
5942                                 FuncExpr   *expr = (FuncExpr *) node;
5943
5944                                 if (expr->funcretset)
5945                                         return FALSE;
5946                                 if (!exec_simple_check_node((Node *) expr->args))
5947                                         return FALSE;
5948
5949                                 return TRUE;
5950                         }
5951
5952                 case T_OpExpr:
5953                         {
5954                                 OpExpr     *expr = (OpExpr *) node;
5955
5956                                 if (expr->opretset)
5957                                         return FALSE;
5958                                 if (!exec_simple_check_node((Node *) expr->args))
5959                                         return FALSE;
5960
5961                                 return TRUE;
5962                         }
5963
5964                 case T_DistinctExpr:
5965                         {
5966                                 DistinctExpr *expr = (DistinctExpr *) node;
5967
5968                                 if (expr->opretset)
5969                                         return FALSE;
5970                                 if (!exec_simple_check_node((Node *) expr->args))
5971                                         return FALSE;
5972
5973                                 return TRUE;
5974                         }
5975
5976                 case T_NullIfExpr:
5977                         {
5978                                 NullIfExpr *expr = (NullIfExpr *) node;
5979
5980                                 if (expr->opretset)
5981                                         return FALSE;
5982                                 if (!exec_simple_check_node((Node *) expr->args))
5983                                         return FALSE;
5984
5985                                 return TRUE;
5986                         }
5987
5988                 case T_ScalarArrayOpExpr:
5989                         {
5990                                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
5991
5992                                 if (!exec_simple_check_node((Node *) expr->args))
5993                                         return FALSE;
5994
5995                                 return TRUE;
5996                         }
5997
5998                 case T_BoolExpr:
5999                         {
6000                                 BoolExpr   *expr = (BoolExpr *) node;
6001
6002                                 if (!exec_simple_check_node((Node *) expr->args))
6003                                         return FALSE;
6004
6005                                 return TRUE;
6006                         }
6007
6008                 case T_FieldSelect:
6009                         return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
6010
6011                 case T_FieldStore:
6012                         {
6013                                 FieldStore *expr = (FieldStore *) node;
6014
6015                                 if (!exec_simple_check_node((Node *) expr->arg))
6016                                         return FALSE;
6017                                 if (!exec_simple_check_node((Node *) expr->newvals))
6018                                         return FALSE;
6019
6020                                 return TRUE;
6021                         }
6022
6023                 case T_RelabelType:
6024                         return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
6025
6026                 case T_CoerceViaIO:
6027                         return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
6028
6029                 case T_ArrayCoerceExpr:
6030                         return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
6031
6032                 case T_ConvertRowtypeExpr:
6033                         return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
6034
6035                 case T_CaseExpr:
6036                         {
6037                                 CaseExpr   *expr = (CaseExpr *) node;
6038
6039                                 if (!exec_simple_check_node((Node *) expr->arg))
6040                                         return FALSE;
6041                                 if (!exec_simple_check_node((Node *) expr->args))
6042                                         return FALSE;
6043                                 if (!exec_simple_check_node((Node *) expr->defresult))
6044                                         return FALSE;
6045
6046                                 return TRUE;
6047                         }
6048
6049                 case T_CaseWhen:
6050                         {
6051                                 CaseWhen   *when = (CaseWhen *) node;
6052
6053                                 if (!exec_simple_check_node((Node *) when->expr))
6054                                         return FALSE;
6055                                 if (!exec_simple_check_node((Node *) when->result))
6056                                         return FALSE;
6057
6058                                 return TRUE;
6059                         }
6060
6061                 case T_CaseTestExpr:
6062                         return TRUE;
6063
6064                 case T_ArrayExpr:
6065                         {
6066                                 ArrayExpr  *expr = (ArrayExpr *) node;
6067
6068                                 if (!exec_simple_check_node((Node *) expr->elements))
6069                                         return FALSE;
6070
6071                                 return TRUE;
6072                         }
6073
6074                 case T_RowExpr:
6075                         {
6076                                 RowExpr    *expr = (RowExpr *) node;
6077
6078                                 if (!exec_simple_check_node((Node *) expr->args))
6079                                         return FALSE;
6080
6081                                 return TRUE;
6082                         }
6083
6084                 case T_RowCompareExpr:
6085                         {
6086                                 RowCompareExpr *expr = (RowCompareExpr *) node;
6087
6088                                 if (!exec_simple_check_node((Node *) expr->largs))
6089                                         return FALSE;
6090                                 if (!exec_simple_check_node((Node *) expr->rargs))
6091                                         return FALSE;
6092
6093                                 return TRUE;
6094                         }
6095
6096                 case T_CoalesceExpr:
6097                         {
6098                                 CoalesceExpr *expr = (CoalesceExpr *) node;
6099
6100                                 if (!exec_simple_check_node((Node *) expr->args))
6101                                         return FALSE;
6102
6103                                 return TRUE;
6104                         }
6105
6106                 case T_MinMaxExpr:
6107                         {
6108                                 MinMaxExpr *expr = (MinMaxExpr *) node;
6109
6110                                 if (!exec_simple_check_node((Node *) expr->args))
6111                                         return FALSE;
6112
6113                                 return TRUE;
6114                         }
6115
6116                 case T_XmlExpr:
6117                         {
6118                                 XmlExpr    *expr = (XmlExpr *) node;
6119
6120                                 if (!exec_simple_check_node((Node *) expr->named_args))
6121                                         return FALSE;
6122                                 if (!exec_simple_check_node((Node *) expr->args))
6123                                         return FALSE;
6124
6125                                 return TRUE;
6126                         }
6127
6128                 case T_NullTest:
6129                         return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
6130
6131                 case T_BooleanTest:
6132                         return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
6133
6134                 case T_CoerceToDomain:
6135                         return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
6136
6137                 case T_CoerceToDomainValue:
6138                         return TRUE;
6139
6140                 case T_List:
6141                         {
6142                                 List       *expr = (List *) node;
6143                                 ListCell   *l;
6144
6145                                 foreach(l, expr)
6146                                 {
6147                                         if (!exec_simple_check_node(lfirst(l)))
6148                                                 return FALSE;
6149                                 }
6150
6151                                 return TRUE;
6152                         }
6153
6154                 default:
6155                         return FALSE;
6156         }
6157 }
6158
6159
6160 /* ----------
6161  * exec_simple_check_plan -             Check if a plan is simple enough to
6162  *                                                              be evaluated by ExecEvalExpr() instead
6163  *                                                              of SPI.
6164  * ----------
6165  */
6166 static void
6167 exec_simple_check_plan(PLpgSQL_expr *expr)
6168 {
6169         List       *plansources;
6170         CachedPlanSource *plansource;
6171         Query      *query;
6172         CachedPlan *cplan;
6173
6174         /*
6175          * Initialize to "not simple", and remember the plan generation number we
6176          * last checked.  (If we don't get as far as obtaining a plan to check, we
6177          * just leave expr_simple_generation set to 0.)
6178          */
6179         expr->expr_simple_expr = NULL;
6180         expr->expr_simple_generation = 0;
6181
6182         /*
6183          * We can only test queries that resulted in exactly one CachedPlanSource
6184          */
6185         plansources = SPI_plan_get_plan_sources(expr->plan);
6186         if (list_length(plansources) != 1)
6187                 return;
6188         plansource = (CachedPlanSource *) linitial(plansources);
6189
6190         /*
6191          * Do some checking on the analyzed-and-rewritten form of the query. These
6192          * checks are basically redundant with the tests in
6193          * exec_simple_recheck_plan, but the point is to avoid building a plan if
6194          * possible.  Since this function is only called immediately after
6195          * creating the CachedPlanSource, we need not worry about the query being
6196          * stale.
6197          */
6198
6199         /*
6200          * 1. There must be one single querytree.
6201          */
6202         if (list_length(plansource->query_list) != 1)
6203                 return;
6204         query = (Query *) linitial(plansource->query_list);
6205
6206         /*
6207          * 2. It must be a plain SELECT query without any input tables
6208          */
6209         if (!IsA(query, Query))
6210                 return;
6211         if (query->commandType != CMD_SELECT)
6212                 return;
6213         if (query->rtable != NIL)
6214                 return;
6215
6216         /*
6217          * 3. Can't have any subplans, aggregates, qual clauses either
6218          */
6219         if (query->hasAggs ||
6220                 query->hasWindowFuncs ||
6221                 query->hasSubLinks ||
6222                 query->hasForUpdate ||
6223                 query->cteList ||
6224                 query->jointree->quals ||
6225                 query->groupClause ||
6226                 query->havingQual ||
6227                 query->windowClause ||
6228                 query->distinctClause ||
6229                 query->sortClause ||
6230                 query->limitOffset ||
6231                 query->limitCount ||
6232                 query->setOperations)
6233                 return;
6234
6235         /*
6236          * 4. The query must have a single attribute as result
6237          */
6238         if (list_length(query->targetList) != 1)
6239                 return;
6240
6241         /*
6242          * OK, it seems worth constructing a plan for more careful checking.
6243          */
6244
6245         /* Get the generic plan for the query */
6246         cplan = SPI_plan_get_cached_plan(expr->plan);
6247
6248         /* Can't fail, because we checked for a single CachedPlanSource above */
6249         Assert(cplan != NULL);
6250
6251         /* Share the remaining work with recheck code path */
6252         exec_simple_recheck_plan(expr, cplan);
6253
6254         /* Release our plan refcount */
6255         ReleaseCachedPlan(cplan, true);
6256 }
6257
6258 /*
6259  * exec_simple_recheck_plan --- check for simple plan once we have CachedPlan
6260  */
6261 static void
6262 exec_simple_recheck_plan(PLpgSQL_expr *expr, CachedPlan *cplan)
6263 {
6264         PlannedStmt *stmt;
6265         Plan       *plan;
6266         TargetEntry *tle;
6267
6268         /*
6269          * Initialize to "not simple", and remember the plan generation number we
6270          * last checked.
6271          */
6272         expr->expr_simple_expr = NULL;
6273         expr->expr_simple_generation = cplan->generation;
6274
6275         /*
6276          * 1. There must be one single plantree
6277          */
6278         if (list_length(cplan->stmt_list) != 1)
6279                 return;
6280         stmt = (PlannedStmt *) linitial(cplan->stmt_list);
6281
6282         /*
6283          * 2. It must be a RESULT plan --> no scan's required
6284          */
6285         if (!IsA(stmt, PlannedStmt))
6286                 return;
6287         if (stmt->commandType != CMD_SELECT)
6288                 return;
6289         plan = stmt->planTree;
6290         if (!IsA(plan, Result))
6291                 return;
6292
6293         /*
6294          * 3. Can't have any subplan or qual clause, either
6295          */
6296         if (plan->lefttree != NULL ||
6297                 plan->righttree != NULL ||
6298                 plan->initPlan != NULL ||
6299                 plan->qual != NULL ||
6300                 ((Result *) plan)->resconstantqual != NULL)
6301                 return;
6302
6303         /*
6304          * 4. The plan must have a single attribute as result
6305          */
6306         if (list_length(plan->targetlist) != 1)
6307                 return;
6308
6309         tle = (TargetEntry *) linitial(plan->targetlist);
6310
6311         /*
6312          * 5. Check that all the nodes in the expression are non-scary.
6313          */
6314         if (!exec_simple_check_node((Node *) tle->expr))
6315                 return;
6316
6317         /*
6318          * Yes - this is a simple expression.  Mark it as such, and initialize
6319          * state to "not valid in current transaction".
6320          */
6321         expr->expr_simple_expr = tle->expr;
6322         expr->expr_simple_state = NULL;
6323         expr->expr_simple_in_use = false;
6324         expr->expr_simple_lxid = InvalidLocalTransactionId;
6325         /* Also stash away the expression result type */
6326         expr->expr_simple_type = exprType((Node *) tle->expr);
6327         expr->expr_simple_typmod = exprTypmod((Node *) tle->expr);
6328 }
6329
6330 /* ----------
6331  * exec_set_found                       Set the global found variable to true/false
6332  * ----------
6333  */
6334 static void
6335 exec_set_found(PLpgSQL_execstate *estate, bool state)
6336 {
6337         PLpgSQL_var *var;
6338
6339         var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
6340         var->value = BoolGetDatum(state);
6341         var->isnull = false;
6342 }
6343
6344 /*
6345  * plpgsql_create_econtext --- create an eval_econtext for the current function
6346  *
6347  * We may need to create a new shared_simple_eval_estate too, if there's not
6348  * one already for the current transaction.  The EState will be cleaned up at
6349  * transaction end.
6350  */
6351 static void
6352 plpgsql_create_econtext(PLpgSQL_execstate *estate)
6353 {
6354         SimpleEcontextStackEntry *entry;
6355
6356         /*
6357          * Create an EState for evaluation of simple expressions, if there's not
6358          * one already in the current transaction.  The EState is made a child of
6359          * TopTransactionContext so it will have the right lifespan.
6360          *
6361          * Note that this path is never taken when executing a DO block; the
6362          * required EState was already made by plpgsql_inline_handler.
6363          */
6364         if (estate->simple_eval_estate == NULL)
6365         {
6366                 MemoryContext oldcontext;
6367
6368                 Assert(shared_simple_eval_estate == NULL);
6369                 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
6370                 shared_simple_eval_estate = CreateExecutorState();
6371                 estate->simple_eval_estate = shared_simple_eval_estate;
6372                 MemoryContextSwitchTo(oldcontext);
6373         }
6374
6375         /*
6376          * Create a child econtext for the current function.
6377          */
6378         estate->eval_econtext = CreateExprContext(estate->simple_eval_estate);
6379
6380         /*
6381          * Make a stack entry so we can clean up the econtext at subxact end.
6382          * Stack entries are kept in TopTransactionContext for simplicity.
6383          */
6384         entry = (SimpleEcontextStackEntry *)
6385                 MemoryContextAlloc(TopTransactionContext,
6386                                                    sizeof(SimpleEcontextStackEntry));
6387
6388         entry->stack_econtext = estate->eval_econtext;
6389         entry->xact_subxid = GetCurrentSubTransactionId();
6390
6391         entry->next = simple_econtext_stack;
6392         simple_econtext_stack = entry;
6393 }
6394
6395 /*
6396  * plpgsql_destroy_econtext --- destroy function's econtext
6397  *
6398  * We check that it matches the top stack entry, and destroy the stack
6399  * entry along with the context.
6400  */
6401 static void
6402 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
6403 {
6404         SimpleEcontextStackEntry *next;
6405
6406         Assert(simple_econtext_stack != NULL);
6407         Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
6408
6409         next = simple_econtext_stack->next;
6410         pfree(simple_econtext_stack);
6411         simple_econtext_stack = next;
6412
6413         FreeExprContext(estate->eval_econtext, true);
6414         estate->eval_econtext = NULL;
6415 }
6416
6417 /*
6418  * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
6419  *
6420  * If a simple-expression EState was created in the current transaction,
6421  * it has to be cleaned up.
6422  */
6423 void
6424 plpgsql_xact_cb(XactEvent event, void *arg)
6425 {
6426         /*
6427          * If we are doing a clean transaction shutdown, free the EState (so that
6428          * any remaining resources will be released correctly). In an abort, we
6429          * expect the regular abort recovery procedures to release everything of
6430          * interest.
6431          */
6432         if (event == XACT_EVENT_COMMIT || event == XACT_EVENT_PREPARE)
6433         {
6434                 /* Shouldn't be any econtext stack entries left at commit */
6435                 Assert(simple_econtext_stack == NULL);
6436
6437                 if (shared_simple_eval_estate)
6438                         FreeExecutorState(shared_simple_eval_estate);
6439                 shared_simple_eval_estate = NULL;
6440         }
6441         else if (event == XACT_EVENT_ABORT)
6442         {
6443                 simple_econtext_stack = NULL;
6444                 shared_simple_eval_estate = NULL;
6445         }
6446 }
6447
6448 /*
6449  * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
6450  *
6451  * Make sure any simple-expression econtexts created in the current
6452  * subtransaction get cleaned up.  We have to do this explicitly because
6453  * no other code knows which econtexts belong to which level of subxact.
6454  */
6455 void
6456 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
6457                                    SubTransactionId parentSubid, void *arg)
6458 {
6459         if (event == SUBXACT_EVENT_COMMIT_SUB || event == SUBXACT_EVENT_ABORT_SUB)
6460         {
6461                 while (simple_econtext_stack != NULL &&
6462                            simple_econtext_stack->xact_subxid == mySubid)
6463                 {
6464                         SimpleEcontextStackEntry *next;
6465
6466                         FreeExprContext(simple_econtext_stack->stack_econtext,
6467                                                         (event == SUBXACT_EVENT_COMMIT_SUB));
6468                         next = simple_econtext_stack->next;
6469                         pfree(simple_econtext_stack);
6470                         simple_econtext_stack = next;
6471                 }
6472         }
6473 }
6474
6475 /*
6476  * free_var --- pfree any pass-by-reference value of the variable.
6477  *
6478  * This should always be followed by some assignment to var->value,
6479  * as it leaves a dangling pointer.
6480  */
6481 static void
6482 free_var(PLpgSQL_var *var)
6483 {
6484         if (var->freeval)
6485         {
6486                 pfree(DatumGetPointer(var->value));
6487                 var->freeval = false;
6488         }
6489 }
6490
6491 /*
6492  * free old value of a text variable and assign new value from C string
6493  */
6494 static void
6495 assign_text_var(PLpgSQL_var *var, const char *str)
6496 {
6497         free_var(var);
6498         var->value = CStringGetTextDatum(str);
6499         var->isnull = false;
6500         var->freeval = true;
6501 }
6502
6503 /*
6504  * exec_eval_using_params --- evaluate params of USING clause
6505  */
6506 static PreparedParamsData *
6507 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
6508 {
6509         PreparedParamsData *ppd;
6510         int                     nargs;
6511         int                     i;
6512         ListCell   *lc;
6513
6514         ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
6515         nargs = list_length(params);
6516
6517         ppd->nargs = nargs;
6518         ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
6519         ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
6520         ppd->nulls = (char *) palloc(nargs * sizeof(char));
6521         ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
6522
6523         i = 0;
6524         foreach(lc, params)
6525         {
6526                 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
6527                 bool            isnull;
6528                 int32           ppdtypmod;
6529
6530                 ppd->values[i] = exec_eval_expr(estate, param,
6531                                                                                 &isnull,
6532                                                                                 &ppd->types[i],
6533                                                                                 &ppdtypmod);
6534                 ppd->nulls[i] = isnull ? 'n' : ' ';
6535                 ppd->freevals[i] = false;
6536
6537                 if (ppd->types[i] == UNKNOWNOID)
6538                 {
6539                         /*
6540                          * Treat 'unknown' parameters as text, since that's what most
6541                          * people would expect. SPI_execute_with_args can coerce unknown
6542                          * constants in a more intelligent way, but not unknown Params.
6543                          * This code also takes care of copying into the right context.
6544                          * Note we assume 'unknown' has the representation of C-string.
6545                          */
6546                         ppd->types[i] = TEXTOID;
6547                         if (!isnull)
6548                         {
6549                                 ppd->values[i] = CStringGetTextDatum(DatumGetCString(ppd->values[i]));
6550                                 ppd->freevals[i] = true;
6551                         }
6552                 }
6553                 /* pass-by-ref non null values must be copied into plpgsql context */
6554                 else if (!isnull)
6555                 {
6556                         int16           typLen;
6557                         bool            typByVal;
6558
6559                         get_typlenbyval(ppd->types[i], &typLen, &typByVal);
6560                         if (!typByVal)
6561                         {
6562                                 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
6563                                 ppd->freevals[i] = true;
6564                         }
6565                 }
6566
6567                 exec_eval_cleanup(estate);
6568
6569                 i++;
6570         }
6571
6572         return ppd;
6573 }
6574
6575 /*
6576  * free_params_data --- pfree all pass-by-reference values used in USING clause
6577  */
6578 static void
6579 free_params_data(PreparedParamsData *ppd)
6580 {
6581         int                     i;
6582
6583         for (i = 0; i < ppd->nargs; i++)
6584         {
6585                 if (ppd->freevals[i])
6586                         pfree(DatumGetPointer(ppd->values[i]));
6587         }
6588
6589         pfree(ppd->types);
6590         pfree(ppd->values);
6591         pfree(ppd->nulls);
6592         pfree(ppd->freevals);
6593
6594         pfree(ppd);
6595 }
6596
6597 /*
6598  * Open portal for dynamic query
6599  */
6600 static Portal
6601 exec_dynquery_with_params(PLpgSQL_execstate *estate,
6602                                                   PLpgSQL_expr *dynquery,
6603                                                   List *params,
6604                                                   const char *portalname,
6605                                                   int cursorOptions)
6606 {
6607         Portal          portal;
6608         Datum           query;
6609         bool            isnull;
6610         Oid                     restype;
6611         int32           restypmod;
6612         char       *querystr;
6613
6614         /*
6615          * Evaluate the string expression after the EXECUTE keyword. Its result is
6616          * the querystring we have to execute.
6617          */
6618         query = exec_eval_expr(estate, dynquery, &isnull, &restype, &restypmod);
6619         if (isnull)
6620                 ereport(ERROR,
6621                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6622                                  errmsg("query string argument of EXECUTE is null")));
6623
6624         /* Get the C-String representation */
6625         querystr = convert_value_to_string(estate, query, restype);
6626
6627         /* copy it out of the temporary context before we clean up */
6628         querystr = pstrdup(querystr);
6629
6630         exec_eval_cleanup(estate);
6631
6632         /*
6633          * Open an implicit cursor for the query.  We use
6634          * SPI_cursor_open_with_args even when there are no params, because this
6635          * avoids making and freeing one copy of the plan.
6636          */
6637         if (params)
6638         {
6639                 PreparedParamsData *ppd;
6640
6641                 ppd = exec_eval_using_params(estate, params);
6642                 portal = SPI_cursor_open_with_args(portalname,
6643                                                                                    querystr,
6644                                                                                    ppd->nargs, ppd->types,
6645                                                                                    ppd->values, ppd->nulls,
6646                                                                                    estate->readonly_func,
6647                                                                                    cursorOptions);
6648                 free_params_data(ppd);
6649         }
6650         else
6651         {
6652                 portal = SPI_cursor_open_with_args(portalname,
6653                                                                                    querystr,
6654                                                                                    0, NULL,
6655                                                                                    NULL, NULL,
6656                                                                                    estate->readonly_func,
6657                                                                                    cursorOptions);
6658         }
6659
6660         if (portal == NULL)
6661                 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
6662                          querystr, SPI_result_code_string(SPI_result));
6663         pfree(querystr);
6664
6665         return portal;
6666 }
6667
6668 /*
6669  * Return a formatted string with information about an expression's parameters,
6670  * or NULL if the expression does not take any parameters.
6671  */
6672 static char *
6673 format_expr_params(PLpgSQL_execstate *estate,
6674                                    const PLpgSQL_expr *expr)
6675 {
6676         int                     paramno;
6677         int                     dno;
6678         StringInfoData paramstr;
6679
6680         if (!expr->paramnos)
6681                 return NULL;
6682
6683         initStringInfo(&paramstr);
6684         paramno = 0;
6685         dno = -1;
6686         while ((dno = bms_next_member(expr->paramnos, dno)) >= 0)
6687         {
6688                 Datum           paramdatum;
6689                 Oid                     paramtypeid;
6690                 bool            paramisnull;
6691                 int32           paramtypmod;
6692                 PLpgSQL_var *curvar;
6693
6694                 curvar = (PLpgSQL_var *) estate->datums[dno];
6695
6696                 exec_eval_datum(estate, (PLpgSQL_datum *) curvar, &paramtypeid,
6697                                                 &paramtypmod, &paramdatum, &paramisnull);
6698
6699                 appendStringInfo(&paramstr, "%s%s = ",
6700                                                  paramno > 0 ? ", " : "",
6701                                                  curvar->refname);
6702
6703                 if (paramisnull)
6704                         appendStringInfoString(&paramstr, "NULL");
6705                 else
6706                 {
6707                         char       *value = convert_value_to_string(estate, paramdatum, paramtypeid);
6708                         char       *p;
6709
6710                         appendStringInfoCharMacro(&paramstr, '\'');
6711                         for (p = value; *p; p++)
6712                         {
6713                                 if (*p == '\'') /* double single quotes */
6714                                         appendStringInfoCharMacro(&paramstr, *p);
6715                                 appendStringInfoCharMacro(&paramstr, *p);
6716                         }
6717                         appendStringInfoCharMacro(&paramstr, '\'');
6718                 }
6719
6720                 paramno++;
6721         }
6722
6723         return paramstr.data;
6724 }
6725
6726 /*
6727  * Return a formatted string with information about PreparedParamsData, or NULL
6728  * if there are no parameters.
6729  */
6730 static char *
6731 format_preparedparamsdata(PLpgSQL_execstate *estate,
6732                                                   const PreparedParamsData *ppd)
6733 {
6734         int                     paramno;
6735         StringInfoData paramstr;
6736
6737         if (!ppd)
6738                 return NULL;
6739
6740         initStringInfo(&paramstr);
6741         for (paramno = 0; paramno < ppd->nargs; paramno++)
6742         {
6743                 appendStringInfo(&paramstr, "%s$%d = ",
6744                                                  paramno > 0 ? ", " : "",
6745                                                  paramno + 1);
6746
6747                 if (ppd->nulls[paramno] == 'n')
6748                         appendStringInfoString(&paramstr, "NULL");
6749                 else
6750                 {
6751                         char       *value = convert_value_to_string(estate, ppd->values[paramno], ppd->types[paramno]);
6752                         char       *p;
6753
6754                         appendStringInfoCharMacro(&paramstr, '\'');
6755                         for (p = value; *p; p++)
6756                         {
6757                                 if (*p == '\'') /* double single quotes */
6758                                         appendStringInfoCharMacro(&paramstr, *p);
6759                                 appendStringInfoCharMacro(&paramstr, *p);
6760                         }
6761                         appendStringInfoCharMacro(&paramstr, '\'');
6762                 }
6763         }
6764
6765         return paramstr.data;
6766 }