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