]> granicus.if.org Git - postgresql/blob - src/pl/plpgsql/src/pl_exec.c
Remove all traces that suggest that a non-Bison yacc might be supported, and
[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-2008, 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.218 2008/08/29 13:02:33 petere Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "plpgsql.h"
17
18 #include <ctype.h>
19
20 #include "access/transam.h"
21 #include "catalog/pg_proc.h"
22 #include "catalog/pg_type.h"
23 #include "executor/spi_priv.h"
24 #include "funcapi.h"
25 #include "nodes/nodeFuncs.h"
26 #include "parser/scansup.h"
27 #include "tcop/tcopprot.h"
28 #include "utils/array.h"
29 #include "utils/builtins.h"
30 #include "utils/lsyscache.h"
31 #include "utils/memutils.h"
32 #include "utils/snapmgr.h"
33 #include "utils/typcache.h"
34
35
36 static const char *const raise_skip_msg = "RAISE";
37
38 typedef struct
39 {
40         int                     nargs;                  /* number of arguments */
41         Oid                *types;                      /* types of arguments */
42         Datum      *values;                     /* evaluated argument values */
43         char       *nulls;                      /* null markers (' '/'n' style) */
44         bool       *freevals;           /* which arguments are pfree-able */
45 } PreparedParamsData;
46
47 /*
48  * All plpgsql function executions within a single transaction share the same
49  * executor EState for evaluating "simple" expressions.  Each function call
50  * creates its own "eval_econtext" ExprContext within this estate for
51  * per-evaluation workspace.  eval_econtext is freed at normal function exit,
52  * and the EState is freed at transaction end (in case of error, we assume
53  * that the abort mechanisms clean it all up).  In order to be sure
54  * ExprContext callbacks are handled properly, each subtransaction has to have
55  * its own such EState; hence we need a stack.  We use a simple counter to
56  * distinguish different instantiations of the EState, so that we can tell
57  * whether we have a current copy of a prepared expression.
58  *
59  * This arrangement is a bit tedious to maintain, but it's worth the trouble
60  * so that we don't have to re-prepare simple expressions on each trip through
61  * a function.  (We assume the case to optimize is many repetitions of a
62  * function within a transaction.)
63  */
64 typedef struct SimpleEstateStackEntry
65 {
66         EState     *xact_eval_estate;           /* EState for current xact level */
67         long int        xact_estate_simple_id;  /* ID for xact_eval_estate */
68         SubTransactionId xact_subxid;           /* ID for current subxact */
69         struct SimpleEstateStackEntry *next;            /* next stack entry up */
70 } SimpleEstateStackEntry;
71
72 static SimpleEstateStackEntry *simple_estate_stack = NULL;
73 static long int simple_estate_id_counter = 0;
74
75 /************************************************************
76  * Local function forward declarations
77  ************************************************************/
78 static void plpgsql_exec_error_callback(void *arg);
79 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
80
81 static int exec_stmt_block(PLpgSQL_execstate *estate,
82                                 PLpgSQL_stmt_block *block);
83 static int exec_stmts(PLpgSQL_execstate *estate,
84                    List *stmts);
85 static int exec_stmt(PLpgSQL_execstate *estate,
86                   PLpgSQL_stmt *stmt);
87 static int exec_stmt_assign(PLpgSQL_execstate *estate,
88                                  PLpgSQL_stmt_assign *stmt);
89 static int exec_stmt_perform(PLpgSQL_execstate *estate,
90                                   PLpgSQL_stmt_perform *stmt);
91 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
92                                   PLpgSQL_stmt_getdiag *stmt);
93 static int exec_stmt_if(PLpgSQL_execstate *estate,
94                          PLpgSQL_stmt_if *stmt);
95 static int exec_stmt_case(PLpgSQL_execstate *estate,
96                                                   PLpgSQL_stmt_case *stmt);
97 static int exec_stmt_loop(PLpgSQL_execstate *estate,
98                            PLpgSQL_stmt_loop *stmt);
99 static int exec_stmt_while(PLpgSQL_execstate *estate,
100                                 PLpgSQL_stmt_while *stmt);
101 static int exec_stmt_fori(PLpgSQL_execstate *estate,
102                            PLpgSQL_stmt_fori *stmt);
103 static int exec_stmt_fors(PLpgSQL_execstate *estate,
104                            PLpgSQL_stmt_fors *stmt);
105 static int exec_stmt_forc(PLpgSQL_execstate *estate,
106                            PLpgSQL_stmt_forc *stmt);
107 static int exec_stmt_open(PLpgSQL_execstate *estate,
108                            PLpgSQL_stmt_open *stmt);
109 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
110                                 PLpgSQL_stmt_fetch *stmt);
111 static int exec_stmt_close(PLpgSQL_execstate *estate,
112                                 PLpgSQL_stmt_close *stmt);
113 static int exec_stmt_exit(PLpgSQL_execstate *estate,
114                            PLpgSQL_stmt_exit *stmt);
115 static int exec_stmt_return(PLpgSQL_execstate *estate,
116                                  PLpgSQL_stmt_return *stmt);
117 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
118                                           PLpgSQL_stmt_return_next *stmt);
119 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
120                                            PLpgSQL_stmt_return_query *stmt);
121 static int exec_stmt_raise(PLpgSQL_execstate *estate,
122                                 PLpgSQL_stmt_raise *stmt);
123 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
124                                   PLpgSQL_stmt_execsql *stmt);
125 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
126                                          PLpgSQL_stmt_dynexecute *stmt);
127 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
128                                   PLpgSQL_stmt_dynfors *stmt);
129
130 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
131                                          PLpgSQL_function *func,
132                                          ReturnSetInfo *rsi);
133 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
134
135 static void exec_prepare_plan(PLpgSQL_execstate *estate,
136                                   PLpgSQL_expr *expr, int cursorOptions);
137 static bool exec_simple_check_node(Node *node);
138 static void exec_simple_check_plan(PLpgSQL_expr *expr);
139 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
140                                           PLpgSQL_expr *expr,
141                                           Datum *result,
142                                           bool *isNull,
143                                           Oid *rettype);
144
145 static void exec_assign_expr(PLpgSQL_execstate *estate,
146                                  PLpgSQL_datum *target,
147                                  PLpgSQL_expr *expr);
148 static void exec_assign_value(PLpgSQL_execstate *estate,
149                                   PLpgSQL_datum *target,
150                                   Datum value, Oid valtype, bool *isNull);
151 static void exec_eval_datum(PLpgSQL_execstate *estate,
152                                 PLpgSQL_datum *datum,
153                                 Oid expectedtypeid,
154                                 Oid *typeid,
155                                 Datum *value,
156                                 bool *isnull);
157 static int exec_eval_integer(PLpgSQL_execstate *estate,
158                                   PLpgSQL_expr *expr,
159                                   bool *isNull);
160 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
161                                   PLpgSQL_expr *expr,
162                                   bool *isNull);
163 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
164                            PLpgSQL_expr *expr,
165                            bool *isNull,
166                            Oid *rettype);
167 static int exec_run_select(PLpgSQL_execstate *estate,
168                                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
169 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
170                                                   Portal portal, bool prefetch_ok);
171 static void eval_expr_params(PLpgSQL_execstate *estate,
172                                  PLpgSQL_expr *expr, Datum **p_values, char **p_nulls);
173 static void exec_move_row(PLpgSQL_execstate *estate,
174                           PLpgSQL_rec *rec,
175                           PLpgSQL_row *row,
176                           HeapTuple tup, TupleDesc tupdesc);
177 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
178                                         PLpgSQL_row *row,
179                                         TupleDesc tupdesc);
180 static char *convert_value_to_string(Datum value, Oid valtype);
181 static Datum exec_cast_value(Datum value, Oid valtype,
182                                 Oid reqtype,
183                                 FmgrInfo *reqinput,
184                                 Oid reqtypioparam,
185                                 int32 reqtypmod,
186                                 bool isnull);
187 static Datum exec_simple_cast_value(Datum value, Oid valtype,
188                                            Oid reqtype, int32 reqtypmod,
189                                            bool isnull);
190 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
191 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
192 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
193 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
194 static void free_var(PLpgSQL_var *var);
195 static void assign_text_var(PLpgSQL_var *var, const char *str);
196 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
197                                                                                                   List *params);
198 static void free_params_data(PreparedParamsData *ppd);
199 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
200                                                                                 PLpgSQL_expr *query, List *params);
201
202
203 /* ----------
204  * plpgsql_exec_function        Called by the call handler for
205  *                              function execution.
206  * ----------
207  */
208 Datum
209 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
210 {
211         PLpgSQL_execstate estate;
212         ErrorContextCallback plerrcontext;
213         int                     i;
214         int                     rc;
215
216         /*
217          * Setup the execution state
218          */
219         plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
220
221         /*
222          * Setup error traceback support for ereport()
223          */
224         plerrcontext.callback = plpgsql_exec_error_callback;
225         plerrcontext.arg = &estate;
226         plerrcontext.previous = error_context_stack;
227         error_context_stack = &plerrcontext;
228
229         /*
230          * Make local execution copies of all the datums
231          */
232         estate.err_text = gettext_noop("during initialization of execution state");
233         for (i = 0; i < estate.ndatums; i++)
234                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
235
236         /*
237          * Store the actual call argument values into the appropriate variables
238          */
239         estate.err_text = gettext_noop("while storing call arguments into local variables");
240         for (i = 0; i < func->fn_nargs; i++)
241         {
242                 int                     n = func->fn_argvarnos[i];
243
244                 switch (estate.datums[n]->dtype)
245                 {
246                         case PLPGSQL_DTYPE_VAR:
247                                 {
248                                         PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
249
250                                         var->value = fcinfo->arg[i];
251                                         var->isnull = fcinfo->argnull[i];
252                                         var->freeval = false;
253                                 }
254                                 break;
255
256                         case PLPGSQL_DTYPE_ROW:
257                                 {
258                                         PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
259
260                                         if (!fcinfo->argnull[i])
261                                         {
262                                                 HeapTupleHeader td;
263                                                 Oid                     tupType;
264                                                 int32           tupTypmod;
265                                                 TupleDesc       tupdesc;
266                                                 HeapTupleData tmptup;
267
268                                                 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
269                                                 /* Extract rowtype info and find a tupdesc */
270                                                 tupType = HeapTupleHeaderGetTypeId(td);
271                                                 tupTypmod = HeapTupleHeaderGetTypMod(td);
272                                                 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
273                                                 /* Build a temporary HeapTuple control structure */
274                                                 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
275                                                 ItemPointerSetInvalid(&(tmptup.t_self));
276                                                 tmptup.t_tableOid = InvalidOid;
277                                                 tmptup.t_data = td;
278                                                 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
279                                                 ReleaseTupleDesc(tupdesc);
280                                         }
281                                         else
282                                         {
283                                                 /* If arg is null, treat it as an empty row */
284                                                 exec_move_row(&estate, NULL, row, NULL, NULL);
285                                         }
286                                 }
287                                 break;
288
289                         default:
290                                 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
291                 }
292         }
293
294         estate.err_text = gettext_noop("during function entry");
295
296         /*
297          * Set the magic variable FOUND to false
298          */
299         exec_set_found(&estate, false);
300
301         /*
302          * Let the instrumentation plugin peek at this function
303          */
304         if (*plugin_ptr && (*plugin_ptr)->func_beg)
305                 ((*plugin_ptr)->func_beg) (&estate, func);
306
307         /*
308          * Now call the toplevel block of statements
309          */
310         estate.err_text = NULL;
311         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
312         rc = exec_stmt_block(&estate, func->action);
313         if (rc != PLPGSQL_RC_RETURN)
314         {
315                 estate.err_stmt = NULL;
316                 estate.err_text = NULL;
317
318                 /*
319                  * Provide a more helpful message if a CONTINUE or RAISE has been used
320                  * outside the context it can work in.
321                  */
322                 if (rc == PLPGSQL_RC_CONTINUE)
323                         ereport(ERROR,
324                                         (errcode(ERRCODE_SYNTAX_ERROR),
325                                          errmsg("CONTINUE cannot be used outside a loop")));
326                 else if (rc == PLPGSQL_RC_RERAISE)
327                         ereport(ERROR,
328                                         (errcode(ERRCODE_SYNTAX_ERROR),
329                                          errmsg("RAISE without parameters cannot be used outside an exception handler")));
330                 else
331                         ereport(ERROR,
332                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
333                                 errmsg("control reached end of function without RETURN")));
334         }
335
336         /*
337          * We got a return value - process it
338          */
339         estate.err_stmt = NULL;
340         estate.err_text = gettext_noop("while casting return value to function's return type");
341
342         fcinfo->isnull = estate.retisnull;
343
344         if (estate.retisset)
345         {
346                 ReturnSetInfo *rsi = estate.rsi;
347
348                 /* Check caller can handle a set result */
349                 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
350                         (rsi->allowedModes & SFRM_Materialize) == 0)
351                         ereport(ERROR,
352                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
353                                          errmsg("set-valued function called in context that cannot accept a set")));
354                 rsi->returnMode = SFRM_Materialize;
355
356                 /* If we produced any tuples, send back the result */
357                 if (estate.tuple_store)
358                 {
359                         rsi->setResult = estate.tuple_store;
360                         if (estate.rettupdesc)
361                         {
362                                 MemoryContext oldcxt;
363
364                                 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
365                                 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
366                                 MemoryContextSwitchTo(oldcxt);
367                         }
368                 }
369                 estate.retval = (Datum) 0;
370                 fcinfo->isnull = true;
371         }
372         else if (!estate.retisnull)
373         {
374                 if (estate.retistuple)
375                 {
376                         /*
377                          * We have to check that the returned tuple actually matches the
378                          * expected result type.  XXX would be better to cache the tupdesc
379                          * instead of repeating get_call_result_type()
380                          */
381                         TupleDesc       tupdesc;
382
383                         switch (get_call_result_type(fcinfo, NULL, &tupdesc))
384                         {
385                                 case TYPEFUNC_COMPOSITE:
386                                         /* got the expected result rowtype, now check it */
387                                         if (estate.rettupdesc == NULL ||
388                                                 !compatible_tupdesc(estate.rettupdesc, tupdesc))
389                                                 ereport(ERROR,
390                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
391                                                                  errmsg("returned record type does not match expected record type")));
392                                         break;
393                                 case TYPEFUNC_RECORD:
394
395                                         /*
396                                          * Failed to determine actual type of RECORD.  We could
397                                          * raise an error here, but what this means in practice is
398                                          * that the caller is expecting any old generic rowtype,
399                                          * so we don't really need to be restrictive. Pass back
400                                          * the generated result type, instead.
401                                          */
402                                         tupdesc = estate.rettupdesc;
403                                         if (tupdesc == NULL)            /* shouldn't happen */
404                                                 elog(ERROR, "return type must be a row type");
405                                         break;
406                                 default:
407                                         /* shouldn't get here if retistuple is true ... */
408                                         elog(ERROR, "return type must be a row type");
409                                         break;
410                         }
411
412                         /*
413                          * Copy tuple to upper executor memory, as a tuple Datum. Make
414                          * sure it is labeled with the caller-supplied tuple type.
415                          */
416                         estate.retval =
417                                 PointerGetDatum(SPI_returntuple((HeapTuple)DatumGetPointer(estate.retval),
418                                                                                                 tupdesc));
419                 }
420                 else
421                 {
422                         /* Cast value to proper type */
423                         estate.retval = exec_cast_value(estate.retval, estate.rettype,
424                                                                                         func->fn_rettype,
425                                                                                         &(func->fn_retinput),
426                                                                                         func->fn_rettypioparam,
427                                                                                         -1,
428                                                                                         fcinfo->isnull);
429
430                         /*
431                          * If the function's return type isn't by value, copy the value
432                          * into upper executor memory context.
433                          */
434                         if (!fcinfo->isnull && !func->fn_retbyval)
435                         {
436                                 Size            len;
437                                 void       *tmp;
438
439                                 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
440                                 tmp = SPI_palloc(len);
441                                 memcpy(tmp, DatumGetPointer(estate.retval), len);
442                                 estate.retval = PointerGetDatum(tmp);
443                         }
444                 }
445         }
446
447         estate.err_text = gettext_noop("during function exit");
448
449         /*
450          * Let the instrumentation plugin peek at this function
451          */
452         if (*plugin_ptr && (*plugin_ptr)->func_end)
453                 ((*plugin_ptr)->func_end) (&estate, func);
454
455         /* Clean up any leftover temporary memory */
456         FreeExprContext(estate.eval_econtext);
457         estate.eval_econtext = NULL;
458         exec_eval_cleanup(&estate);
459
460         /*
461          * Pop the error context stack
462          */
463         error_context_stack = plerrcontext.previous;
464
465         /*
466          * Return the function's result
467          */
468         return estate.retval;
469 }
470
471
472 /* ----------
473  * plpgsql_exec_trigger         Called by the call handler for
474  *                              trigger execution.
475  * ----------
476  */
477 HeapTuple
478 plpgsql_exec_trigger(PLpgSQL_function *func,
479                                          TriggerData *trigdata)
480 {
481         PLpgSQL_execstate estate;
482         ErrorContextCallback plerrcontext;
483         int                     i;
484         int                     rc;
485         PLpgSQL_var *var;
486         PLpgSQL_rec *rec_new,
487                            *rec_old;
488         HeapTuple       rettup;
489
490         /*
491          * Setup the execution state
492          */
493         plpgsql_estate_setup(&estate, func, NULL);
494
495         /*
496          * Setup error traceback support for ereport()
497          */
498         plerrcontext.callback = plpgsql_exec_error_callback;
499         plerrcontext.arg = &estate;
500         plerrcontext.previous = error_context_stack;
501         error_context_stack = &plerrcontext;
502
503         /*
504          * Make local execution copies of all the datums
505          */
506         estate.err_text = gettext_noop("during initialization of execution state");
507         for (i = 0; i < estate.ndatums; i++)
508                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
509
510         /*
511          * Put the OLD and NEW tuples into record variables
512          */
513         rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
514         rec_new->freetup = false;
515         rec_new->freetupdesc = false;
516         rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
517         rec_old->freetup = false;
518         rec_old->freetupdesc = false;
519
520         if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
521         {
522                 /*
523                  * Per-statement triggers don't use OLD/NEW variables
524                  */
525                 rec_new->tup = NULL;
526                 rec_new->tupdesc = NULL;
527                 rec_old->tup = NULL;
528                 rec_old->tupdesc = NULL;
529         }
530         else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
531         {
532                 rec_new->tup = trigdata->tg_trigtuple;
533                 rec_new->tupdesc = trigdata->tg_relation->rd_att;
534                 rec_old->tup = NULL;
535                 rec_old->tupdesc = NULL;
536         }
537         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
538         {
539                 rec_new->tup = trigdata->tg_newtuple;
540                 rec_new->tupdesc = trigdata->tg_relation->rd_att;
541                 rec_old->tup = trigdata->tg_trigtuple;
542                 rec_old->tupdesc = trigdata->tg_relation->rd_att;
543         }
544         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
545         {
546                 rec_new->tup = NULL;
547                 rec_new->tupdesc = NULL;
548                 rec_old->tup = trigdata->tg_trigtuple;
549                 rec_old->tupdesc = trigdata->tg_relation->rd_att;
550         }
551         else
552                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
553
554         /*
555          * Assign the special tg_ variables
556          */
557
558         var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
559         if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
560                 var->value = CStringGetTextDatum("INSERT");
561         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
562                 var->value = CStringGetTextDatum("UPDATE");
563         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
564                 var->value = CStringGetTextDatum("DELETE");
565         else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
566                 var->value = CStringGetTextDatum("TRUNCATE");
567         else
568                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
569         var->isnull = false;
570         var->freeval = true;
571
572         var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
573         var->value = DirectFunctionCall1(namein,
574                                                           CStringGetDatum(trigdata->tg_trigger->tgname));
575         var->isnull = false;
576         var->freeval = true;
577
578         var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
579         if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
580                 var->value = CStringGetTextDatum("BEFORE");
581         else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
582                 var->value = CStringGetTextDatum("AFTER");
583         else
584                 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
585         var->isnull = false;
586         var->freeval = true;
587
588         var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
589         if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
590                 var->value = CStringGetTextDatum("ROW");
591         else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
592                 var->value = CStringGetTextDatum("STATEMENT");
593         else
594                 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
595         var->isnull = false;
596         var->freeval = true;
597
598         var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
599         var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
600         var->isnull = false;
601         var->freeval = false;
602
603         var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
604         var->value = DirectFunctionCall1(namein,
605                         CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
606         var->isnull = false;
607         var->freeval = true;
608
609         var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
610         var->value = DirectFunctionCall1(namein,
611                         CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
612         var->isnull = false;
613         var->freeval = true;
614
615         var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
616         var->value = DirectFunctionCall1(namein,
617                                                                          CStringGetDatum(
618                                                                                                          get_namespace_name(
619                                                                                                                 RelationGetNamespace(
620                                                                                                    trigdata->tg_relation))));
621         var->isnull = false;
622         var->freeval = true;
623
624         var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
625         var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
626         var->isnull = false;
627         var->freeval = false;
628
629         /*
630          * Store the trigger argument values into the special execution state
631          * variables
632          */
633         estate.err_text = gettext_noop("while storing call arguments into local variables");
634         estate.trig_nargs = trigdata->tg_trigger->tgnargs;
635         if (estate.trig_nargs == 0)
636                 estate.trig_argv = NULL;
637         else
638         {
639                 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
640                 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
641                         estate.trig_argv[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
642         }
643
644         estate.err_text = gettext_noop("during function entry");
645
646         /*
647          * Set the magic variable FOUND to false
648          */
649         exec_set_found(&estate, false);
650
651         /*
652          * Let the instrumentation plugin peek at this function
653          */
654         if (*plugin_ptr && (*plugin_ptr)->func_beg)
655                 ((*plugin_ptr)->func_beg) (&estate, func);
656
657         /*
658          * Now call the toplevel block of statements
659          */
660         estate.err_text = NULL;
661         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
662         rc = exec_stmt_block(&estate, func->action);
663         if (rc != PLPGSQL_RC_RETURN)
664         {
665                 estate.err_stmt = NULL;
666                 estate.err_text = NULL;
667
668                 /*
669                  * Provide a more helpful message if a CONTINUE or RAISE has been used
670                  * outside the context it can work in.
671                  */
672                 if (rc == PLPGSQL_RC_CONTINUE)
673                         ereport(ERROR,
674                                         (errcode(ERRCODE_SYNTAX_ERROR),
675                                          errmsg("CONTINUE cannot be used outside a loop")));
676                 else if (rc == PLPGSQL_RC_RERAISE)
677                         ereport(ERROR,
678                                         (errcode(ERRCODE_SYNTAX_ERROR),
679                                          errmsg("RAISE without parameters cannot be used outside an exception handler")));
680                 else
681                         ereport(ERROR,
682                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
683                                 errmsg("control reached end of trigger procedure without RETURN")));
684         }
685
686         estate.err_stmt = NULL;
687         estate.err_text = gettext_noop("during function exit");
688
689         if (estate.retisset)
690                 ereport(ERROR,
691                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
692                                  errmsg("trigger procedure cannot return a set")));
693
694         /*
695          * Check that the returned tuple structure has the same attributes, the
696          * relation that fired the trigger has. A per-statement trigger always
697          * needs to return NULL, so we ignore any return value the function itself
698          * produces (XXX: is this a good idea?)
699          *
700          * XXX This way it is possible, that the trigger returns a tuple where
701          * attributes don't have the correct atttypmod's length. It's up to the
702          * trigger's programmer to ensure that this doesn't happen. Jan
703          */
704         if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
705                 rettup = NULL;
706         else
707         {
708                 if (!compatible_tupdesc(estate.rettupdesc,
709                                                                 trigdata->tg_relation->rd_att))
710                         ereport(ERROR,
711                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
712                                          errmsg("returned tuple structure does not match table of trigger event")));
713                 /* Copy tuple to upper executor memory */
714                 rettup = SPI_copytuple((HeapTuple) DatumGetPointer(estate.retval));
715         }
716
717         /*
718          * Let the instrumentation plugin peek at this function
719          */
720         if (*plugin_ptr && (*plugin_ptr)->func_end)
721                 ((*plugin_ptr)->func_end) (&estate, func);
722
723         /* Clean up any leftover temporary memory */
724         FreeExprContext(estate.eval_econtext);
725         estate.eval_econtext = NULL;
726         exec_eval_cleanup(&estate);
727
728         /*
729          * Pop the error context stack
730          */
731         error_context_stack = plerrcontext.previous;
732
733         /*
734          * Return the trigger's result
735          */
736         return rettup;
737 }
738
739
740 /*
741  * error context callback to let us supply a call-stack traceback
742  */
743 static void
744 plpgsql_exec_error_callback(void *arg)
745 {
746         PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
747
748         /* safety check, shouldn't happen */
749         if (estate->err_func == NULL)
750                 return;
751
752         /* if we are doing RAISE, don't report its location */
753         if (estate->err_text == raise_skip_msg)
754                 return;
755
756         if (estate->err_text != NULL)
757         {
758                 /*
759                  * We don't expend the cycles to run gettext() on err_text unless we
760                  * actually need it.  Therefore, places that set up err_text should
761                  * use gettext_noop() to ensure the strings get recorded in the
762                  * message dictionary.
763                  *
764                  * If both err_text and err_stmt are set, use the err_text as
765                  * description, but report the err_stmt's line number.  When err_stmt
766                  * is not set, we're in function entry/exit, or some such place not
767                  * attached to a specific line number.
768                  */
769                 if (estate->err_stmt != NULL)
770                 {
771                         /*
772                          * translator: last %s is a phrase such as "during statement block
773                          * local variable initialization"
774                          */
775                         errcontext("PL/pgSQL function \"%s\" line %d %s",
776                                            estate->err_func->fn_name,
777                                            estate->err_stmt->lineno,
778                                            gettext(estate->err_text));
779                 }
780                 else
781                 {
782                         /*
783                          * translator: last %s is a phrase such as "while storing call
784                          * arguments into local variables"
785                          */
786                         errcontext("PL/pgSQL function \"%s\" %s",
787                                            estate->err_func->fn_name,
788                                            gettext(estate->err_text));
789                 }
790         }
791         else if (estate->err_stmt != NULL)
792         {
793                 /* translator: last %s is a plpgsql statement type name */
794                 errcontext("PL/pgSQL function \"%s\" line %d at %s",
795                                    estate->err_func->fn_name,
796                                    estate->err_stmt->lineno,
797                                    plpgsql_stmt_typename(estate->err_stmt));
798         }
799         else
800                 errcontext("PL/pgSQL function \"%s\"",
801                                    estate->err_func->fn_name);
802 }
803
804
805 /* ----------
806  * Support function for initializing local execution variables
807  * ----------
808  */
809 static PLpgSQL_datum *
810 copy_plpgsql_datum(PLpgSQL_datum *datum)
811 {
812         PLpgSQL_datum *result;
813
814         switch (datum->dtype)
815         {
816                 case PLPGSQL_DTYPE_VAR:
817                         {
818                                 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
819
820                                 memcpy(new, datum, sizeof(PLpgSQL_var));
821                                 /* Ensure the value is null (possibly not needed?) */
822                                 new->value = 0;
823                                 new->isnull = true;
824                                 new->freeval = false;
825
826                                 result = (PLpgSQL_datum *) new;
827                         }
828                         break;
829
830                 case PLPGSQL_DTYPE_REC:
831                         {
832                                 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
833
834                                 memcpy(new, datum, sizeof(PLpgSQL_rec));
835                                 /* Ensure the value is null (possibly not needed?) */
836                                 new->tup = NULL;
837                                 new->tupdesc = NULL;
838                                 new->freetup = false;
839                                 new->freetupdesc = false;
840
841                                 result = (PLpgSQL_datum *) new;
842                         }
843                         break;
844
845                 case PLPGSQL_DTYPE_ROW:
846                 case PLPGSQL_DTYPE_RECFIELD:
847                 case PLPGSQL_DTYPE_ARRAYELEM:
848                 case PLPGSQL_DTYPE_TRIGARG:
849
850                         /*
851                          * These datum records are read-only at runtime, so no need to
852                          * copy them
853                          */
854                         result = datum;
855                         break;
856
857                 default:
858                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
859                         result = NULL;          /* keep compiler quiet */
860                         break;
861         }
862
863         return result;
864 }
865
866
867 static bool
868 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
869 {
870         for (; cond != NULL; cond = cond->next)
871         {
872                 int                     sqlerrstate = cond->sqlerrstate;
873
874                 /*
875                  * OTHERS matches everything *except* query-canceled; if you're
876                  * foolish enough, you can match that explicitly.
877                  */
878                 if (sqlerrstate == 0)
879                 {
880                         if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
881                                 return true;
882                 }
883                 /* Exact match? */
884                 else if (edata->sqlerrcode == sqlerrstate)
885                         return true;
886                 /* Category match? */
887                 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
888                                  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
889                         return true;
890         }
891         return false;
892 }
893
894
895 /* ----------
896  * exec_stmt_block                      Execute a block of statements
897  * ----------
898  */
899 static int
900 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
901 {
902         volatile int rc = -1;
903         int                     i;
904         int                     n;
905
906         /*
907          * First initialize all variables declared in this block
908          */
909         estate->err_text = gettext_noop("during statement block local variable initialization");
910
911         for (i = 0; i < block->n_initvars; i++)
912         {
913                 n = block->initvarnos[i];
914
915                 switch (estate->datums[n]->dtype)
916                 {
917                         case PLPGSQL_DTYPE_VAR:
918                                 {
919                                         PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
920
921                                         /* free any old value, in case re-entering block */
922                                         free_var(var);
923
924                                         /* Initially it contains a NULL */
925                                         var->value = (Datum) 0;
926                                         var->isnull = true;
927
928                                         if (var->default_val == NULL)
929                                         {
930                                                 /*
931                                                  * If needed, give the datatype a chance to reject
932                                                  * NULLs, by assigning a NULL to the variable. We
933                                                  * claim the value is of type UNKNOWN, not the var's
934                                                  * datatype, else coercion will be skipped. (Do this
935                                                  * before the notnull check to be consistent with
936                                                  * exec_assign_value.)
937                                                  */
938                                                 if (!var->datatype->typinput.fn_strict)
939                                                 {
940                                                         bool            valIsNull = true;
941
942                                                         exec_assign_value(estate,
943                                                                                           (PLpgSQL_datum *) var,
944                                                                                           (Datum) 0,
945                                                                                           UNKNOWNOID,
946                                                                                           &valIsNull);
947                                                 }
948                                                 if (var->notnull)
949                                                         ereport(ERROR,
950                                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
951                                                                          errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
952                                                                                         var->refname)));
953                                         }
954                                         else
955                                         {
956                                                 exec_assign_expr(estate, (PLpgSQL_datum *) var,
957                                                                                  var->default_val);
958                                         }
959                                 }
960                                 break;
961
962                         case PLPGSQL_DTYPE_REC:
963                                 {
964                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
965
966                                         if (rec->freetup)
967                                         {
968                                                 heap_freetuple(rec->tup);
969                                                 FreeTupleDesc(rec->tupdesc);
970                                                 rec->freetup = false;
971                                         }
972
973                                         rec->tup = NULL;
974                                         rec->tupdesc = NULL;
975                                 }
976                                 break;
977
978                         case PLPGSQL_DTYPE_RECFIELD:
979                         case PLPGSQL_DTYPE_ARRAYELEM:
980                                 break;
981
982                         default:
983                                 elog(ERROR, "unrecognized dtype: %d",
984                                          estate->datums[n]->dtype);
985                 }
986         }
987
988         if (block->exceptions)
989         {
990                 /*
991                  * Execute the statements in the block's body inside a sub-transaction
992                  */
993                 MemoryContext oldcontext = CurrentMemoryContext;
994                 ResourceOwner oldowner = CurrentResourceOwner;
995                 ExprContext *old_eval_econtext = estate->eval_econtext;
996                 EState     *old_eval_estate = estate->eval_estate;
997                 long int        old_eval_estate_simple_id = estate->eval_estate_simple_id;
998
999                 estate->err_text = gettext_noop("during statement block entry");
1000
1001                 BeginInternalSubTransaction(NULL);
1002                 /* Want to run statements inside function's memory context */
1003                 MemoryContextSwitchTo(oldcontext);
1004
1005                 PG_TRY();
1006                 {
1007                         /*
1008                          * We need to run the block's statements with a new eval_econtext
1009                          * that belongs to the current subtransaction; if we try to use
1010                          * the outer econtext then ExprContext shutdown callbacks will be
1011                          * called at the wrong times.
1012                          */
1013                         plpgsql_create_econtext(estate);
1014
1015                         estate->err_text = NULL;
1016
1017                         /* Run the block's statements */
1018                         rc = exec_stmts(estate, block->body);
1019
1020                         estate->err_text = gettext_noop("during statement block exit");
1021
1022                         /*
1023                          * If the block ended with RETURN, we may need to copy the return
1024                          * value out of the subtransaction eval_context.  This is
1025                          * currently only needed for scalar result types --- rowtype
1026                          * values will always exist in the function's own memory context.
1027                          */
1028                         if (rc == PLPGSQL_RC_RETURN &&
1029                                 !estate->retisset &&
1030                                 !estate->retisnull &&
1031                                 estate->rettupdesc == NULL)
1032                         {
1033                                 int16           resTypLen;
1034                                 bool            resTypByVal;
1035
1036                                 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1037                                 estate->retval = datumCopy(estate->retval,
1038                                                                                    resTypByVal, resTypLen);
1039                         }
1040
1041                         /* Commit the inner transaction, return to outer xact context */
1042                         ReleaseCurrentSubTransaction();
1043                         MemoryContextSwitchTo(oldcontext);
1044                         CurrentResourceOwner = oldowner;
1045
1046                         /* Revert to outer eval_econtext */
1047                         estate->eval_econtext = old_eval_econtext;
1048                         estate->eval_estate = old_eval_estate;
1049                         estate->eval_estate_simple_id = old_eval_estate_simple_id;
1050
1051                         /*
1052                          * AtEOSubXact_SPI() should not have popped any SPI context, but
1053                          * just in case it did, make sure we remain connected.
1054                          */
1055                         SPI_restore_connection();
1056                 }
1057                 PG_CATCH();
1058                 {
1059                         ErrorData  *edata;
1060                         ListCell   *e;
1061
1062                         estate->err_text = gettext_noop("during exception cleanup");
1063
1064                         /* Save error info */
1065                         MemoryContextSwitchTo(oldcontext);
1066                         edata = CopyErrorData();
1067                         FlushErrorState();
1068
1069                         /* Abort the inner transaction */
1070                         RollbackAndReleaseCurrentSubTransaction();
1071                         MemoryContextSwitchTo(oldcontext);
1072                         CurrentResourceOwner = oldowner;
1073
1074                         /* Revert to outer eval_econtext */
1075                         estate->eval_econtext = old_eval_econtext;
1076                         estate->eval_estate = old_eval_estate;
1077                         estate->eval_estate_simple_id = old_eval_estate_simple_id;
1078
1079                         /*
1080                          * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1081                          * will have left us in a disconnected state.  We need this hack
1082                          * to return to connected state.
1083                          */
1084                         SPI_restore_connection();
1085
1086                         /* Look for a matching exception handler */
1087                         foreach(e, block->exceptions->exc_list)
1088                         {
1089                                 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1090
1091                                 if (exception_matches_conditions(edata, exception->conditions))
1092                                 {
1093                                         /*
1094                                          * Initialize the magic SQLSTATE and SQLERRM variables for
1095                                          * the exception block. We needn't do this until we have
1096                                          * found a matching exception.
1097                                          */
1098                                         PLpgSQL_var *state_var;
1099                                         PLpgSQL_var *errm_var;
1100
1101                                         state_var = (PLpgSQL_var *)
1102                                                 estate->datums[block->exceptions->sqlstate_varno];
1103                                         errm_var = (PLpgSQL_var *)
1104                                                 estate->datums[block->exceptions->sqlerrm_varno];
1105
1106                                         assign_text_var(state_var,
1107                                                                         unpack_sql_state(edata->sqlerrcode));
1108                                         assign_text_var(errm_var, edata->message);
1109
1110                                         estate->err_text = NULL;
1111
1112                                         rc = exec_stmts(estate, exception->action);
1113
1114                                         free_var(state_var);
1115                                         state_var->value = (Datum) 0;
1116                                         state_var->isnull = true;
1117                                         free_var(errm_var);
1118                                         errm_var->value = (Datum) 0;
1119                                         errm_var->isnull = true;
1120
1121                                         /* re-throw error if requested by handler */
1122                                         if (rc == PLPGSQL_RC_RERAISE)
1123                                                 ReThrowError(edata);
1124
1125                                         break;
1126                                 }
1127                         }
1128
1129                         /* If no match found, re-throw the error */
1130                         if (e == NULL)
1131                                 ReThrowError(edata);
1132                         else
1133                                 FreeErrorData(edata);
1134                 }
1135                 PG_END_TRY();
1136         }
1137         else
1138         {
1139                 /*
1140                  * Just execute the statements in the block's body
1141                  */
1142                 estate->err_text = NULL;
1143
1144                 rc = exec_stmts(estate, block->body);
1145         }
1146
1147         estate->err_text = NULL;
1148
1149         /*
1150          * Handle the return code.
1151          */
1152         switch (rc)
1153         {
1154                 case PLPGSQL_RC_OK:
1155                 case PLPGSQL_RC_RETURN:
1156                 case PLPGSQL_RC_CONTINUE:
1157                 case PLPGSQL_RC_RERAISE:
1158                         return rc;
1159
1160                 case PLPGSQL_RC_EXIT:
1161                         if (estate->exitlabel == NULL)
1162                                 return PLPGSQL_RC_OK;
1163                         if (block->label == NULL)
1164                                 return PLPGSQL_RC_EXIT;
1165                         if (strcmp(block->label, estate->exitlabel))
1166                                 return PLPGSQL_RC_EXIT;
1167                         estate->exitlabel = NULL;
1168                         return PLPGSQL_RC_OK;
1169
1170                 default:
1171                         elog(ERROR, "unrecognized rc: %d", rc);
1172         }
1173
1174         return PLPGSQL_RC_OK;
1175 }
1176
1177
1178 /* ----------
1179  * exec_stmts                   Iterate over a list of statements
1180  *                              as long as their return code is OK
1181  * ----------
1182  */
1183 static int
1184 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1185 {
1186         ListCell   *s;
1187
1188         if (stmts == NIL)
1189         {
1190                 /*
1191                  * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1192                  * statement.  This prevents hangup in a tight loop if, for instance,
1193                  * there is a LOOP construct with an empty body.
1194                  */
1195                 CHECK_FOR_INTERRUPTS();
1196                 return PLPGSQL_RC_OK;
1197         }
1198
1199         foreach(s, stmts)
1200         {
1201                 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1202                 int                     rc = exec_stmt(estate, stmt);
1203
1204                 if (rc != PLPGSQL_RC_OK)
1205                         return rc;
1206         }
1207
1208         return PLPGSQL_RC_OK;
1209 }
1210
1211
1212 /* ----------
1213  * exec_stmt                    Distribute one statement to the statements
1214  *                              type specific execution function.
1215  * ----------
1216  */
1217 static int
1218 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1219 {
1220         PLpgSQL_stmt *save_estmt;
1221         int                     rc = -1;
1222
1223         save_estmt = estate->err_stmt;
1224         estate->err_stmt = stmt;
1225
1226         /* Let the plugin know that we are about to execute this statement */
1227         if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1228                 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1229
1230         CHECK_FOR_INTERRUPTS();
1231
1232         switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1233         {
1234                 case PLPGSQL_STMT_BLOCK:
1235                         rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1236                         break;
1237
1238                 case PLPGSQL_STMT_ASSIGN:
1239                         rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1240                         break;
1241
1242                 case PLPGSQL_STMT_PERFORM:
1243                         rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1244                         break;
1245
1246                 case PLPGSQL_STMT_GETDIAG:
1247                         rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1248                         break;
1249
1250                 case PLPGSQL_STMT_IF:
1251                         rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1252                         break;
1253
1254                 case PLPGSQL_STMT_CASE:
1255                         rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1256                         break;
1257
1258                 case PLPGSQL_STMT_LOOP:
1259                         rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1260                         break;
1261
1262                 case PLPGSQL_STMT_WHILE:
1263                         rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1264                         break;
1265
1266                 case PLPGSQL_STMT_FORI:
1267                         rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1268                         break;
1269
1270                 case PLPGSQL_STMT_FORS:
1271                         rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1272                         break;
1273
1274                 case PLPGSQL_STMT_FORC:
1275                         rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1276                         break;
1277
1278                 case PLPGSQL_STMT_EXIT:
1279                         rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1280                         break;
1281
1282                 case PLPGSQL_STMT_RETURN:
1283                         rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1284                         break;
1285
1286                 case PLPGSQL_STMT_RETURN_NEXT:
1287                         rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1288                         break;
1289
1290                 case PLPGSQL_STMT_RETURN_QUERY:
1291                         rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1292                         break;
1293
1294                 case PLPGSQL_STMT_RAISE:
1295                         rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1296                         break;
1297
1298                 case PLPGSQL_STMT_EXECSQL:
1299                         rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1300                         break;
1301
1302                 case PLPGSQL_STMT_DYNEXECUTE:
1303                         rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1304                         break;
1305
1306                 case PLPGSQL_STMT_DYNFORS:
1307                         rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1308                         break;
1309
1310                 case PLPGSQL_STMT_OPEN:
1311                         rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1312                         break;
1313
1314                 case PLPGSQL_STMT_FETCH:
1315                         rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1316                         break;
1317
1318                 case PLPGSQL_STMT_CLOSE:
1319                         rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1320                         break;
1321
1322                 default:
1323                         estate->err_stmt = save_estmt;
1324                         elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1325         }
1326
1327         /* Let the plugin know that we have finished executing this statement */
1328         if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1329                 ((*plugin_ptr)->stmt_end) (estate, stmt);
1330
1331         estate->err_stmt = save_estmt;
1332
1333         return rc;
1334 }
1335
1336
1337 /* ----------
1338  * exec_stmt_assign                     Evaluate an expression and
1339  *                                      put the result into a variable.
1340  * ----------
1341  */
1342 static int
1343 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1344 {
1345         Assert(stmt->varno >= 0);
1346
1347         exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1348
1349         return PLPGSQL_RC_OK;
1350 }
1351
1352 /* ----------
1353  * exec_stmt_perform            Evaluate query and discard result (but set
1354  *                                                      FOUND depending on whether at least one row
1355  *                                                      was returned).
1356  * ----------
1357  */
1358 static int
1359 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1360 {
1361         PLpgSQL_expr *expr = stmt->expr;
1362
1363         (void) exec_run_select(estate, expr, 0, NULL);
1364         exec_set_found(estate, (estate->eval_processed != 0));
1365         exec_eval_cleanup(estate);
1366
1367         return PLPGSQL_RC_OK;
1368 }
1369
1370 /* ----------
1371  * exec_stmt_getdiag                                    Put internal PG information into
1372  *                                                                              specified variables.
1373  * ----------
1374  */
1375 static int
1376 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1377 {
1378         ListCell   *lc;
1379
1380         foreach(lc, stmt->diag_items)
1381         {
1382                 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1383                 PLpgSQL_datum *var;
1384                 bool            isnull = false;
1385
1386                 if (diag_item->target <= 0)
1387                         continue;
1388
1389                 var = estate->datums[diag_item->target];
1390
1391                 if (var == NULL)
1392                         continue;
1393
1394                 switch (diag_item->kind)
1395                 {
1396                         case PLPGSQL_GETDIAG_ROW_COUNT:
1397
1398                                 exec_assign_value(estate, var,
1399                                                                   UInt32GetDatum(estate->eval_processed),
1400                                                                   INT4OID, &isnull);
1401                                 break;
1402
1403                         case PLPGSQL_GETDIAG_RESULT_OID:
1404
1405                                 exec_assign_value(estate, var,
1406                                                                   ObjectIdGetDatum(estate->eval_lastoid),
1407                                                                   OIDOID, &isnull);
1408                                 break;
1409
1410                         default:
1411                                 elog(ERROR, "unrecognized attribute request: %d",
1412                                          diag_item->kind);
1413                 }
1414         }
1415
1416         return PLPGSQL_RC_OK;
1417 }
1418
1419 /* ----------
1420  * exec_stmt_if                         Evaluate a bool expression and
1421  *                                      execute the true or false body
1422  *                                      conditionally.
1423  * ----------
1424  */
1425 static int
1426 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1427 {
1428         bool            value;
1429         bool            isnull;
1430
1431         value = exec_eval_boolean(estate, stmt->cond, &isnull);
1432         exec_eval_cleanup(estate);
1433
1434         if (!isnull && value)
1435         {
1436                 if (stmt->true_body != NIL)
1437                         return exec_stmts(estate, stmt->true_body);
1438         }
1439         else
1440         {
1441                 if (stmt->false_body != NIL)
1442                         return exec_stmts(estate, stmt->false_body);
1443         }
1444
1445         return PLPGSQL_RC_OK;
1446 }
1447
1448
1449 /*-----------
1450  * exec_stmt_case
1451  *-----------
1452  */
1453 static int
1454 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1455 {
1456         PLpgSQL_var *t_var = NULL;
1457         bool            isnull;
1458         ListCell   *l;
1459
1460         if (stmt->t_expr != NULL)
1461         {
1462                 /* simple case */
1463                 Datum   t_val;
1464                 Oid             t_oid;
1465
1466                 t_val = exec_eval_expr(estate, stmt->t_expr, &isnull, &t_oid);
1467
1468                 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1469
1470                 /*
1471                  * When expected datatype is different from real, change it.
1472                  * Note that what we're modifying here is an execution copy
1473                  * of the datum, so this doesn't affect the originally stored
1474                  * function parse tree.
1475                  */
1476                 if (t_var->datatype->typoid != t_oid)
1477                         t_var->datatype = plpgsql_build_datatype(t_oid, -1);
1478
1479                 /* now we can assign to the variable */
1480                 exec_assign_value(estate,
1481                                                   (PLpgSQL_datum *) t_var,
1482                                                   t_val,
1483                                                   t_oid,
1484                                                   &isnull);
1485
1486                 exec_eval_cleanup(estate);
1487         }
1488
1489         /* Now search for a successful WHEN clause */
1490         foreach(l, stmt->case_when_list)
1491         {
1492                 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1493                 bool    value;
1494
1495                 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1496                 exec_eval_cleanup(estate);
1497                 if (!isnull && value)
1498                 {
1499                         /* Found it */
1500
1501                         /* We can now discard any value we had for the temp variable */
1502                         if (t_var != NULL)
1503                         {
1504                                 free_var(t_var);
1505                                 t_var->value = (Datum) 0;
1506                                 t_var->isnull = true;
1507                         }
1508
1509                         /* Evaluate the statement(s), and we're done */
1510                         return exec_stmts(estate, cwt->stmts);
1511                 }
1512         }
1513
1514         /* We can now discard any value we had for the temp variable */
1515         if (t_var != NULL)
1516         {
1517                 free_var(t_var);
1518                 t_var->value = (Datum) 0;
1519                 t_var->isnull = true;
1520         }
1521
1522         /* SQL2003 mandates this error if there was no ELSE clause */
1523         if (!stmt->have_else)
1524                 ereport(ERROR,
1525                                 (errcode(ERRCODE_CASE_NOT_FOUND),
1526                                  errmsg("case not found"),
1527                                  errhint("CASE statement is missing ELSE part.")));
1528
1529         /* Evaluate the ELSE statements, and we're done */
1530         return exec_stmts(estate, stmt->else_stmts);
1531 }
1532
1533
1534 /* ----------
1535  * exec_stmt_loop                       Loop over statements until
1536  *                                      an exit occurs.
1537  * ----------
1538  */
1539 static int
1540 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1541 {
1542         for (;;)
1543         {
1544                 int                     rc = exec_stmts(estate, stmt->body);
1545
1546                 switch (rc)
1547                 {
1548                         case PLPGSQL_RC_OK:
1549                                 break;
1550
1551                         case PLPGSQL_RC_EXIT:
1552                                 if (estate->exitlabel == NULL)
1553                                         return PLPGSQL_RC_OK;
1554                                 if (stmt->label == NULL)
1555                                         return PLPGSQL_RC_EXIT;
1556                                 if (strcmp(stmt->label, estate->exitlabel) != 0)
1557                                         return PLPGSQL_RC_EXIT;
1558                                 estate->exitlabel = NULL;
1559                                 return PLPGSQL_RC_OK;
1560
1561                         case PLPGSQL_RC_CONTINUE:
1562                                 if (estate->exitlabel == NULL)
1563                                         /* anonymous continue, so re-run the loop */
1564                                         break;
1565                                 else if (stmt->label != NULL &&
1566                                                  strcmp(stmt->label, estate->exitlabel) == 0)
1567                                         /* label matches named continue, so re-run loop */
1568                                         estate->exitlabel = NULL;
1569                                 else
1570                                         /* label doesn't match named continue, so propagate upward */
1571                                         return PLPGSQL_RC_CONTINUE;
1572                                 break;
1573
1574                         case PLPGSQL_RC_RETURN:
1575                         case PLPGSQL_RC_RERAISE:
1576                                 return rc;
1577
1578                         default:
1579                                 elog(ERROR, "unrecognized rc: %d", rc);
1580                 }
1581         }
1582
1583         return PLPGSQL_RC_OK;
1584 }
1585
1586
1587 /* ----------
1588  * exec_stmt_while                      Loop over statements as long
1589  *                                      as an expression evaluates to
1590  *                                      true or an exit occurs.
1591  * ----------
1592  */
1593 static int
1594 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1595 {
1596         for (;;)
1597         {
1598                 int                     rc;
1599                 bool            value;
1600                 bool            isnull;
1601
1602                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1603                 exec_eval_cleanup(estate);
1604
1605                 if (isnull || !value)
1606                         break;
1607
1608                 rc = exec_stmts(estate, stmt->body);
1609
1610                 switch (rc)
1611                 {
1612                         case PLPGSQL_RC_OK:
1613                                 break;
1614
1615                         case PLPGSQL_RC_EXIT:
1616                                 if (estate->exitlabel == NULL)
1617                                         return PLPGSQL_RC_OK;
1618                                 if (stmt->label == NULL)
1619                                         return PLPGSQL_RC_EXIT;
1620                                 if (strcmp(stmt->label, estate->exitlabel))
1621                                         return PLPGSQL_RC_EXIT;
1622                                 estate->exitlabel = NULL;
1623                                 return PLPGSQL_RC_OK;
1624
1625                         case PLPGSQL_RC_CONTINUE:
1626                                 if (estate->exitlabel == NULL)
1627                                         /* anonymous continue, so re-run loop */
1628                                         break;
1629                                 else if (stmt->label != NULL &&
1630                                                  strcmp(stmt->label, estate->exitlabel) == 0)
1631                                         /* label matches named continue, so re-run loop */
1632                                         estate->exitlabel = NULL;
1633                                 else
1634                                         /* label doesn't match named continue, propagate upward */
1635                                         return PLPGSQL_RC_CONTINUE;
1636                                 break;
1637
1638                         case PLPGSQL_RC_RETURN:
1639                         case PLPGSQL_RC_RERAISE:
1640                                 return rc;
1641
1642                         default:
1643                                 elog(ERROR, "unrecognized rc: %d", rc);
1644                 }
1645         }
1646
1647         return PLPGSQL_RC_OK;
1648 }
1649
1650
1651 /* ----------
1652  * exec_stmt_fori                       Iterate an integer variable
1653  *                                      from a lower to an upper value
1654  *                                      incrementing or decrementing by the BY value
1655  * ----------
1656  */
1657 static int
1658 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1659 {
1660         PLpgSQL_var *var;
1661         Datum           value;
1662         bool            isnull;
1663         Oid                     valtype;
1664         int32           loop_value;
1665         int32           end_value;
1666         int32           step_value;
1667         bool            found = false;
1668         int                     rc = PLPGSQL_RC_OK;
1669
1670         var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1671
1672         /*
1673          * Get the value of the lower bound
1674          */
1675         value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1676         value = exec_cast_value(value, valtype, var->datatype->typoid,
1677                                                         &(var->datatype->typinput),
1678                                                         var->datatype->typioparam,
1679                                                         var->datatype->atttypmod, isnull);
1680         if (isnull)
1681                 ereport(ERROR,
1682                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1683                                  errmsg("lower bound of FOR loop cannot be NULL")));
1684         loop_value = DatumGetInt32(value);
1685         exec_eval_cleanup(estate);
1686
1687         /*
1688          * Get the value of the upper bound
1689          */
1690         value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1691         value = exec_cast_value(value, valtype, var->datatype->typoid,
1692                                                         &(var->datatype->typinput),
1693                                                         var->datatype->typioparam,
1694                                                         var->datatype->atttypmod, isnull);
1695         if (isnull)
1696                 ereport(ERROR,
1697                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1698                                  errmsg("upper bound of FOR loop cannot be NULL")));
1699         end_value = DatumGetInt32(value);
1700         exec_eval_cleanup(estate);
1701
1702         /*
1703          * Get the step value
1704          */
1705         if (stmt->step)
1706         {
1707                 value = exec_eval_expr(estate, stmt->step, &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("BY value of FOR loop cannot be NULL")));
1716                 step_value = DatumGetInt32(value);
1717                 exec_eval_cleanup(estate);
1718                 if (step_value <= 0)
1719                         ereport(ERROR,
1720                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1721                                   errmsg("BY value of FOR loop must be greater than zero")));
1722         }
1723         else
1724                 step_value = 1;
1725
1726         /*
1727          * Now do the loop
1728          */
1729         for (;;)
1730         {
1731                 /*
1732                  * Check against upper bound
1733                  */
1734                 if (stmt->reverse)
1735                 {
1736                         if (loop_value < end_value)
1737                                 break;
1738                 }
1739                 else
1740                 {
1741                         if (loop_value > end_value)
1742                                 break;
1743                 }
1744
1745                 found = true;                   /* looped at least once */
1746
1747                 /*
1748                  * Assign current value to loop var
1749                  */
1750                 var->value = Int32GetDatum(loop_value);
1751                 var->isnull = false;
1752
1753                 /*
1754                  * Execute the statements
1755                  */
1756                 rc = exec_stmts(estate, stmt->body);
1757
1758                 if (rc == PLPGSQL_RC_RETURN ||
1759                         rc == PLPGSQL_RC_RERAISE)
1760                         break;                          /* break out of the loop */
1761                 else if (rc == PLPGSQL_RC_EXIT)
1762                 {
1763                         if (estate->exitlabel == NULL)
1764                                 /* unlabelled exit, finish the current loop */
1765                                 rc = PLPGSQL_RC_OK;
1766                         else if (stmt->label != NULL &&
1767                                          strcmp(stmt->label, estate->exitlabel) == 0)
1768                         {
1769                                 /* labelled exit, matches the current stmt's label */
1770                                 estate->exitlabel = NULL;
1771                                 rc = PLPGSQL_RC_OK;
1772                         }
1773
1774                         /*
1775                          * otherwise, this is a labelled exit that does not match the
1776                          * current statement's label, if any: return RC_EXIT so that the
1777                          * EXIT continues to propagate up the stack.
1778                          */
1779                         break;
1780                 }
1781                 else if (rc == PLPGSQL_RC_CONTINUE)
1782                 {
1783                         if (estate->exitlabel == NULL)
1784                                 /* unlabelled continue, so re-run the current loop */
1785                                 rc = PLPGSQL_RC_OK;
1786                         else if (stmt->label != NULL &&
1787                                          strcmp(stmt->label, estate->exitlabel) == 0)
1788                         {
1789                                 /* label matches named continue, so re-run loop */
1790                                 estate->exitlabel = NULL;
1791                                 rc = PLPGSQL_RC_OK;
1792                         }
1793                         else
1794                         {
1795                                 /*
1796                                  * otherwise, this is a named continue that does not match the
1797                                  * current statement's label, if any: return RC_CONTINUE so
1798                                  * that the CONTINUE will propagate up the stack.
1799                                  */
1800                                 break;
1801                         }
1802                 }
1803
1804                 /*
1805                  * Increase/decrease loop value, unless it would overflow, in which
1806                  * case exit the loop.
1807                  */
1808                 if (stmt->reverse)
1809                 {
1810                         if ((int32) (loop_value - step_value) > loop_value)
1811                                 break;
1812                         loop_value -= step_value;
1813                 }
1814                 else
1815                 {
1816                         if ((int32) (loop_value + step_value) < loop_value)
1817                                 break;
1818                         loop_value += step_value;
1819                 }
1820         }
1821
1822         /*
1823          * Set the FOUND variable to indicate the result of executing the loop
1824          * (namely, whether we looped one or more times). This must be set here so
1825          * that it does not interfere with the value of the FOUND variable inside
1826          * the loop processing itself.
1827          */
1828         exec_set_found(estate, found);
1829
1830         return rc;
1831 }
1832
1833
1834 /* ----------
1835  * exec_stmt_fors                       Execute a query, assign each
1836  *                                      tuple to a record or row and
1837  *                                      execute a group of statements
1838  *                                      for it.
1839  * ----------
1840  */
1841 static int
1842 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1843 {
1844         Portal          portal;
1845         int                     rc;
1846
1847         /*
1848          * Open the implicit cursor for the statement using exec_run_select
1849          */
1850         exec_run_select(estate, stmt->query, 0, &portal);
1851
1852         /*
1853          * Execute the loop
1854          */
1855         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
1856
1857         /*
1858          * Close the implicit cursor
1859          */
1860         SPI_cursor_close(portal);
1861
1862         return rc;
1863 }
1864
1865
1866 /* ----------
1867  * exec_stmt_forc                       Execute a loop for each row from a cursor.
1868  * ----------
1869  */
1870 static int
1871 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
1872 {
1873         PLpgSQL_var *curvar;
1874         char       *curname = NULL;
1875         PLpgSQL_expr *query;
1876         Portal          portal;
1877         int                     rc;
1878         Datum      *values;
1879         char       *nulls;
1880
1881         /* ----------
1882          * Get the cursor variable and if it has an assigned name, check
1883          * that it's not in use currently.
1884          * ----------
1885          */
1886         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
1887         if (!curvar->isnull)
1888         {
1889                 curname = TextDatumGetCString(curvar->value);
1890                 if (SPI_cursor_find(curname) != NULL)
1891                         ereport(ERROR,
1892                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
1893                                          errmsg("cursor \"%s\" already in use", curname)));
1894         }
1895
1896         /* ----------
1897          * Open the cursor just like an OPEN command
1898          *
1899          * Note: parser should already have checked that statement supplies
1900          * args iff cursor needs them, but we check again to be safe.
1901          * ----------
1902          */
1903         if (stmt->argquery != NULL)
1904         {
1905                 /* ----------
1906                  * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
1907                  * statement to evaluate the args and put 'em into the
1908                  * internal row.
1909                  * ----------
1910                  */
1911                 PLpgSQL_stmt_execsql set_args;
1912
1913                 if (curvar->cursor_explicit_argrow < 0)
1914                         ereport(ERROR,
1915                                         (errcode(ERRCODE_SYNTAX_ERROR),
1916                                         errmsg("arguments given for cursor without arguments")));
1917
1918                 memset(&set_args, 0, sizeof(set_args));
1919                 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
1920                 set_args.lineno = stmt->lineno;
1921                 set_args.sqlstmt = stmt->argquery;
1922                 set_args.into = true;
1923                 /* XXX historically this has not been STRICT */
1924                 set_args.row = (PLpgSQL_row *)
1925                         (estate->datums[curvar->cursor_explicit_argrow]);
1926
1927                 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
1928                         elog(ERROR, "open cursor failed during argument processing");
1929         }
1930         else
1931         {
1932                 if (curvar->cursor_explicit_argrow >= 0)
1933                         ereport(ERROR,
1934                                         (errcode(ERRCODE_SYNTAX_ERROR),
1935                                          errmsg("arguments required for cursor")));
1936         }
1937
1938         query = curvar->cursor_explicit_expr;
1939         Assert(query);
1940
1941         if (query->plan == NULL)
1942                 exec_prepare_plan(estate, query, curvar->cursor_options);
1943
1944         /*
1945          * Now build up the values and nulls arguments for SPI_execute_plan()
1946          */
1947         eval_expr_params(estate, query, &values, &nulls);
1948
1949         /*
1950          * Open the cursor
1951          */
1952         portal = SPI_cursor_open(curname, query->plan, values, nulls,
1953                                                          estate->readonly_func);
1954         if (portal == NULL)
1955                 elog(ERROR, "could not open cursor: %s",
1956                          SPI_result_code_string(SPI_result));
1957
1958         /*
1959          * If cursor variable was NULL, store the generated portal name in it
1960          */
1961         if (curname == NULL)
1962                 assign_text_var(curvar, portal->name);
1963
1964         /*
1965          * Execute the loop.  We can't prefetch because the cursor is accessible
1966          * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
1967          */
1968         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
1969
1970         /* ----------
1971          * Close portal, and restore cursor variable if it was initially NULL.
1972          * ----------
1973          */
1974         SPI_cursor_close(portal);
1975
1976         if (curname == NULL)
1977         {
1978                 free_var(curvar);
1979                 curvar->value = (Datum) 0;
1980                 curvar->isnull = true;
1981         }
1982
1983         pfree(values);
1984         pfree(nulls);
1985         if (curname)
1986                 pfree(curname);
1987
1988         return rc;
1989 }
1990
1991
1992 /* ----------
1993  * exec_stmt_exit                       Implements EXIT and CONTINUE
1994  *
1995  * This begins the process of exiting / restarting a loop.
1996  * ----------
1997  */
1998 static int
1999 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
2000 {
2001         /*
2002          * If the exit / continue has a condition, evaluate it
2003          */
2004         if (stmt->cond != NULL)
2005         {
2006                 bool            value;
2007                 bool            isnull;
2008
2009                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2010                 exec_eval_cleanup(estate);
2011                 if (isnull || value == false)
2012                         return PLPGSQL_RC_OK;
2013         }
2014
2015         estate->exitlabel = stmt->label;
2016         if (stmt->is_exit)
2017                 return PLPGSQL_RC_EXIT;
2018         else
2019                 return PLPGSQL_RC_CONTINUE;
2020 }
2021
2022
2023 /* ----------
2024  * exec_stmt_return                     Evaluate an expression and start
2025  *                                      returning from the function.
2026  * ----------
2027  */
2028 static int
2029 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
2030 {
2031         /*
2032          * If processing a set-returning PL/PgSQL function, the final RETURN
2033          * indicates that the function is finished producing tuples.  The rest of
2034          * the work will be done at the top level.
2035          */
2036         if (estate->retisset)
2037                 return PLPGSQL_RC_RETURN;
2038
2039         /* initialize for null result (possibly a tuple) */
2040         estate->retval = (Datum) 0;
2041         estate->rettupdesc = NULL;
2042         estate->retisnull = true;
2043
2044         if (stmt->retvarno >= 0)
2045         {
2046                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2047
2048                 switch (retvar->dtype)
2049                 {
2050                         case PLPGSQL_DTYPE_VAR:
2051                                 {
2052                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2053
2054                                         estate->retval = var->value;
2055                                         estate->retisnull = var->isnull;
2056                                         estate->rettype = var->datatype->typoid;
2057                                 }
2058                                 break;
2059
2060                         case PLPGSQL_DTYPE_REC:
2061                                 {
2062                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2063
2064                                         if (HeapTupleIsValid(rec->tup))
2065                                         {
2066                                                 estate->retval = PointerGetDatum(rec->tup);
2067                                                 estate->rettupdesc = rec->tupdesc;
2068                                                 estate->retisnull = false;
2069                                         }
2070                                 }
2071                                 break;
2072
2073                         case PLPGSQL_DTYPE_ROW:
2074                                 {
2075                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2076
2077                                         Assert(row->rowtupdesc);
2078                                         estate->retval =
2079                                                 PointerGetDatum(make_tuple_from_row(estate, row,
2080                                                                                                                         row->rowtupdesc));
2081                                         if (DatumGetPointer(estate->retval) == NULL) /* should not happen */
2082                                                 elog(ERROR, "row not compatible with its own tupdesc");
2083                                         estate->rettupdesc = row->rowtupdesc;
2084                                         estate->retisnull = false;
2085                                 }
2086                                 break;
2087
2088                         default:
2089                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2090                 }
2091
2092                 return PLPGSQL_RC_RETURN;
2093         }
2094
2095         if (stmt->expr != NULL)
2096         {
2097                 if (estate->retistuple)
2098                 {
2099                         exec_run_select(estate, stmt->expr, 1, NULL);
2100                         if (estate->eval_processed > 0)
2101                         {
2102                                 estate->retval = PointerGetDatum(estate->eval_tuptable->vals[0]);
2103                                 estate->rettupdesc = estate->eval_tuptable->tupdesc;
2104                                 estate->retisnull = false;
2105                         }
2106                 }
2107                 else
2108                 {
2109                         /* Normal case for scalar results */
2110                         estate->retval = exec_eval_expr(estate, stmt->expr,
2111                                                                                         &(estate->retisnull),
2112                                                                                         &(estate->rettype));
2113                 }
2114
2115                 return PLPGSQL_RC_RETURN;
2116         }
2117
2118         /*
2119          * Special hack for function returning VOID: instead of NULL, return a
2120          * non-null VOID value.  This is of dubious importance but is kept for
2121          * backwards compatibility.  Note that the only other way to get here is
2122          * to have written "RETURN NULL" in a function returning tuple.
2123          */
2124         if (estate->fn_rettype == VOIDOID)
2125         {
2126                 estate->retval = (Datum) 0;
2127                 estate->retisnull = false;
2128                 estate->rettype = VOIDOID;
2129         }
2130
2131         return PLPGSQL_RC_RETURN;
2132 }
2133
2134 /* ----------
2135  * exec_stmt_return_next                Evaluate an expression and add it to the
2136  *                                                              list of tuples returned by the current
2137  *                                                              SRF.
2138  * ----------
2139  */
2140 static int
2141 exec_stmt_return_next(PLpgSQL_execstate *estate,
2142                                           PLpgSQL_stmt_return_next *stmt)
2143 {
2144         TupleDesc               tupdesc;
2145         int                             natts;
2146         MemoryContext   oldcxt;
2147         HeapTuple               tuple = NULL;
2148         bool                    free_tuple = false;
2149
2150         if (!estate->retisset)
2151                 ereport(ERROR,
2152                                 (errcode(ERRCODE_SYNTAX_ERROR),
2153                                  errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2154
2155         if (estate->tuple_store == NULL)
2156                 exec_init_tuple_store(estate);
2157
2158         /* rettupdesc will be filled by exec_init_tuple_store */
2159         tupdesc = estate->rettupdesc;
2160         natts = tupdesc->natts;
2161
2162         if (stmt->retvarno >= 0)
2163         {
2164                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2165
2166                 switch (retvar->dtype)
2167                 {
2168                         case PLPGSQL_DTYPE_VAR:
2169                                 {
2170                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2171                                         Datum           retval = var->value;
2172                                         bool            isNull = var->isnull;
2173
2174                                         if (natts != 1)
2175                                                 ereport(ERROR,
2176                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2177                                                 errmsg("wrong result type supplied in RETURN NEXT")));
2178
2179                                         /* coerce type if needed */
2180                                         retval = exec_simple_cast_value(retval,
2181                                                                                                         var->datatype->typoid,
2182                                                                                                  tupdesc->attrs[0]->atttypid,
2183                                                                                                 tupdesc->attrs[0]->atttypmod,
2184                                                                                                         isNull);
2185
2186                                         oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2187                                         tuplestore_putvalues(estate->tuple_store, tupdesc,
2188                                                                                  &retval, &isNull);
2189                                         MemoryContextSwitchTo(oldcxt);
2190                                 }
2191                                 break;
2192
2193                         case PLPGSQL_DTYPE_REC:
2194                                 {
2195                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2196
2197                                         if (!HeapTupleIsValid(rec->tup))
2198                                                 ereport(ERROR,
2199                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2200                                                    errmsg("record \"%s\" is not assigned yet",
2201                                                                   rec->refname),
2202                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
2203                                         if (!compatible_tupdesc(tupdesc, rec->tupdesc))
2204                                                 ereport(ERROR,
2205                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2206                                                 errmsg("wrong record type supplied in RETURN NEXT")));
2207                                         tuple = rec->tup;
2208                                 }
2209                                 break;
2210
2211                         case PLPGSQL_DTYPE_ROW:
2212                                 {
2213                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2214
2215                                         tuple = make_tuple_from_row(estate, row, tupdesc);
2216                                         if (tuple == NULL)
2217                                                 ereport(ERROR,
2218                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2219                                                 errmsg("wrong record type supplied in RETURN NEXT")));
2220                                         free_tuple = true;
2221                                 }
2222                                 break;
2223
2224                         default:
2225                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2226                                 break;
2227                 }
2228         }
2229         else if (stmt->expr)
2230         {
2231                 Datum           retval;
2232                 bool            isNull;
2233                 Oid                     rettype;
2234
2235                 if (natts != 1)
2236                         ereport(ERROR,
2237                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
2238                                          errmsg("wrong result type supplied in RETURN NEXT")));
2239
2240                 retval = exec_eval_expr(estate,
2241                                                                 stmt->expr,
2242                                                                 &isNull,
2243                                                                 &rettype);
2244
2245                 /* coerce type if needed */
2246                 retval = exec_simple_cast_value(retval,
2247                                                                                 rettype,
2248                                                                                 tupdesc->attrs[0]->atttypid,
2249                                                                                 tupdesc->attrs[0]->atttypmod,
2250                                                                                 isNull);
2251
2252                 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2253                 tuplestore_putvalues(estate->tuple_store, tupdesc,
2254                                                          &retval, &isNull);
2255                 MemoryContextSwitchTo(oldcxt);
2256
2257                 exec_eval_cleanup(estate);
2258         }
2259         else
2260         {
2261                 ereport(ERROR,
2262                                 (errcode(ERRCODE_SYNTAX_ERROR),
2263                                  errmsg("RETURN NEXT must have a parameter")));
2264         }
2265
2266         if (HeapTupleIsValid(tuple))
2267         {
2268                 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2269                 tuplestore_puttuple(estate->tuple_store, tuple);
2270                 MemoryContextSwitchTo(oldcxt);
2271
2272                 if (free_tuple)
2273                         heap_freetuple(tuple);
2274         }
2275
2276         return PLPGSQL_RC_OK;
2277 }
2278
2279 /* ----------
2280  * exec_stmt_return_query               Evaluate a query and add it to the
2281  *                                                              list of tuples returned by the current
2282  *                                                              SRF.
2283  * ----------
2284  */
2285 static int
2286 exec_stmt_return_query(PLpgSQL_execstate *estate,
2287                                            PLpgSQL_stmt_return_query *stmt)
2288 {
2289         Portal          portal;
2290
2291         if (!estate->retisset)
2292                 ereport(ERROR,
2293                                 (errcode(ERRCODE_SYNTAX_ERROR),
2294                                  errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2295
2296         if (estate->tuple_store == NULL)
2297                 exec_init_tuple_store(estate);
2298
2299         if (stmt->query != NULL)
2300         {
2301                 /* static query */
2302                 exec_run_select(estate, stmt->query, 0, &portal);
2303         }
2304         else
2305         {
2306                 /* RETURN QUERY EXECUTE */
2307                 Assert(stmt->dynquery != NULL);
2308                 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2309                                                                                    stmt->params);
2310         }
2311
2312         if (!compatible_tupdesc(estate->rettupdesc, portal->tupDesc))
2313                 ereport(ERROR,
2314                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2315                   errmsg("structure of query does not match function result type")));
2316
2317         while (true)
2318         {
2319                 MemoryContext old_cxt;
2320                 int                     i;
2321
2322                 SPI_cursor_fetch(portal, true, 50);
2323                 if (SPI_processed == 0)
2324                         break;
2325
2326                 old_cxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2327                 for (i = 0; i < SPI_processed; i++)
2328                 {
2329                         HeapTuple       tuple = SPI_tuptable->vals[i];
2330
2331                         tuplestore_puttuple(estate->tuple_store, tuple);
2332                 }
2333                 MemoryContextSwitchTo(old_cxt);
2334
2335                 SPI_freetuptable(SPI_tuptable);
2336         }
2337
2338         SPI_freetuptable(SPI_tuptable);
2339         SPI_cursor_close(portal);
2340
2341         return PLPGSQL_RC_OK;
2342 }
2343
2344 static void
2345 exec_init_tuple_store(PLpgSQL_execstate *estate)
2346 {
2347         ReturnSetInfo *rsi = estate->rsi;
2348         MemoryContext oldcxt;
2349
2350         /*
2351          * Check caller can handle a set result in the way we want
2352          */
2353         if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2354                 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2355                 rsi->expectedDesc == NULL)
2356                 ereport(ERROR,
2357                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2358                                  errmsg("set-valued function called in context that cannot accept a set")));
2359
2360         estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2361
2362         oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2363         estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
2364         MemoryContextSwitchTo(oldcxt);
2365
2366         estate->rettupdesc = rsi->expectedDesc;
2367 }
2368
2369 /* ----------
2370  * exec_stmt_raise                      Build a message and throw it with elog()
2371  * ----------
2372  */
2373 static int
2374 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2375 {
2376         int                     err_code = 0;
2377         char       *condname = NULL;
2378         char       *err_message = NULL;
2379         char       *err_detail = NULL;
2380         char       *err_hint = NULL;
2381         ListCell   *lc;
2382
2383         /* RAISE with no parameters: re-throw current exception */
2384         if (stmt->condname == NULL && stmt->message == NULL &&
2385                 stmt->options == NIL)
2386                 return PLPGSQL_RC_RERAISE;
2387
2388         if (stmt->condname)
2389         {
2390                 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2391                 condname = pstrdup(stmt->condname);
2392         }
2393
2394         if (stmt->message)
2395         {
2396                 PLpgSQL_dstring ds;
2397                 ListCell   *current_param;
2398                 char       *cp;
2399
2400                 plpgsql_dstring_init(&ds);
2401                 current_param = list_head(stmt->params);
2402
2403                 for (cp = stmt->message; *cp; cp++)
2404                 {
2405                         /*
2406                          * Occurrences of a single % are replaced by the next parameter's
2407                          * external representation. Double %'s are converted to one %.
2408                          */
2409                         if (cp[0] == '%')
2410                         {
2411                                 Oid                     paramtypeid;
2412                                 Datum           paramvalue;
2413                                 bool            paramisnull;
2414                                 char       *extval;
2415
2416                                 if (cp[1] == '%')
2417                                 {
2418                                         plpgsql_dstring_append_char(&ds, cp[1]);
2419                                         cp++;
2420                                         continue;
2421                                 }
2422
2423                                 if (current_param == NULL)
2424                                         ereport(ERROR,
2425                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2426                                                          errmsg("too few parameters specified for RAISE")));
2427
2428                                 paramvalue = exec_eval_expr(estate,
2429                                                                                         (PLpgSQL_expr *) lfirst(current_param),
2430                                                                                         &paramisnull,
2431                                                                                         &paramtypeid);
2432
2433                                 if (paramisnull)
2434                                         extval = "<NULL>";
2435                                 else
2436                                         extval = convert_value_to_string(paramvalue, paramtypeid);
2437                                 plpgsql_dstring_append(&ds, extval);
2438                                 current_param = lnext(current_param);
2439                                 exec_eval_cleanup(estate);
2440                         }
2441                         else
2442                                 plpgsql_dstring_append_char(&ds, cp[0]);
2443                 }
2444
2445                 /*
2446                  * If more parameters were specified than were required to process the
2447                  * format string, throw an error
2448                  */
2449                 if (current_param != NULL)
2450                         ereport(ERROR,
2451                                         (errcode(ERRCODE_SYNTAX_ERROR),
2452                                          errmsg("too many parameters specified for RAISE")));
2453
2454                 err_message = plpgsql_dstring_get(&ds);
2455                 /* No dstring_free here, the pfree(err_message) does it */
2456         }
2457
2458         foreach(lc, stmt->options)
2459         {
2460                 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
2461                 Datum           optionvalue;
2462                 bool            optionisnull;
2463                 Oid                     optiontypeid;
2464                 char       *extval;
2465
2466                 optionvalue = exec_eval_expr(estate, opt->expr,
2467                                                                          &optionisnull,
2468                                                                          &optiontypeid);
2469                 if (optionisnull)
2470                         ereport(ERROR,
2471                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2472                                          errmsg("RAISE statement option cannot be NULL")));
2473
2474                 extval = convert_value_to_string(optionvalue, optiontypeid);
2475
2476                 switch (opt->opt_type)
2477                 {
2478                         case PLPGSQL_RAISEOPTION_ERRCODE:
2479                                 if (err_code)
2480                                         ereport(ERROR,
2481                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2482                                                          errmsg("RAISE option already specified: %s",
2483                                                                         "ERRCODE")));
2484                                 err_code = plpgsql_recognize_err_condition(extval, true);
2485                                 condname = pstrdup(extval);
2486                                 break;
2487                         case PLPGSQL_RAISEOPTION_MESSAGE:
2488                                 if (err_message)
2489                                         ereport(ERROR,
2490                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2491                                                          errmsg("RAISE option already specified: %s",
2492                                                                         "MESSAGE")));
2493                                 err_message = pstrdup(extval);
2494                                 break;
2495                         case PLPGSQL_RAISEOPTION_DETAIL:
2496                                 if (err_detail)
2497                                         ereport(ERROR,
2498                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2499                                                          errmsg("RAISE option already specified: %s",
2500                                                                         "DETAIL")));
2501                                 err_detail = pstrdup(extval);
2502                                 break;
2503                         case PLPGSQL_RAISEOPTION_HINT:
2504                                 if (err_hint)
2505                                         ereport(ERROR,
2506                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2507                                                          errmsg("RAISE option already specified: %s",
2508                                                                         "HINT")));
2509                                 err_hint = pstrdup(extval);
2510                                 break;
2511                         default:
2512                                 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
2513                 }
2514
2515                 exec_eval_cleanup(estate);
2516         }
2517
2518         /* Default code if nothing specified */
2519         if (err_code == 0 && stmt->elog_level >= ERROR)
2520                 err_code = ERRCODE_RAISE_EXCEPTION;
2521
2522         /* Default error message if nothing specified */
2523         if (err_message == NULL)
2524         {
2525                 if (condname)
2526                 {
2527                         err_message = condname;
2528                         condname = NULL;
2529                 }
2530                 else
2531                         err_message = pstrdup(unpack_sql_state(err_code));
2532         }
2533
2534         /*
2535          * Throw the error (may or may not come back)
2536          */
2537         estate->err_text = raise_skip_msg;      /* suppress traceback of raise */
2538
2539         ereport(stmt->elog_level,
2540                         (err_code ? errcode(err_code) : 0,
2541                          errmsg_internal("%s", err_message),
2542                          (err_detail != NULL) ? errdetail(err_detail) : 0,
2543                          (err_hint != NULL) ? errhint(err_hint) : 0));
2544
2545         estate->err_text = NULL;        /* un-suppress... */
2546
2547         if (condname != NULL)
2548                 pfree(condname);
2549         if (err_message != NULL)
2550                 pfree(err_message);
2551         if (err_detail != NULL)
2552                 pfree(err_detail);
2553         if (err_hint != NULL)
2554                 pfree(err_hint);
2555
2556         return PLPGSQL_RC_OK;
2557 }
2558
2559
2560 /* ----------
2561  * Initialize a mostly empty execution state
2562  * ----------
2563  */
2564 static void
2565 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2566                                          PLpgSQL_function *func,
2567                                          ReturnSetInfo *rsi)
2568 {
2569         estate->retval = (Datum) 0;
2570         estate->retisnull = true;
2571         estate->rettype = InvalidOid;
2572
2573         estate->fn_rettype = func->fn_rettype;
2574         estate->retistuple = func->fn_retistuple;
2575         estate->retisset = func->fn_retset;
2576
2577         estate->readonly_func = func->fn_readonly;
2578
2579         estate->rettupdesc = NULL;
2580         estate->exitlabel = NULL;
2581
2582         estate->tuple_store = NULL;
2583         estate->tuple_store_cxt = NULL;
2584         estate->rsi = rsi;
2585
2586         estate->trig_nargs = 0;
2587         estate->trig_argv = NULL;
2588
2589         estate->found_varno = func->found_varno;
2590         estate->ndatums = func->ndatums;
2591         estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2592         /* caller is expected to fill the datums array */
2593
2594         estate->eval_tuptable = NULL;
2595         estate->eval_processed = 0;
2596         estate->eval_lastoid = InvalidOid;
2597
2598         estate->err_func = func;
2599         estate->err_stmt = NULL;
2600         estate->err_text = NULL;
2601
2602         /*
2603          * Create an EState and ExprContext for evaluation of simple expressions.
2604          */
2605         plpgsql_create_econtext(estate);
2606
2607         /*
2608          * Let the plugin see this function before we initialize any local
2609          * PL/pgSQL variables - note that we also give the plugin a few function
2610          * pointers so it can call back into PL/pgSQL for doing things like
2611          * variable assignments and stack traces
2612          */
2613         if (*plugin_ptr)
2614         {
2615                 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2616                 (*plugin_ptr)->assign_expr = exec_assign_expr;
2617
2618                 if ((*plugin_ptr)->func_setup)
2619                         ((*plugin_ptr)->func_setup) (estate, func);
2620         }
2621 }
2622
2623 /* ----------
2624  * Release temporary memory used by expression/subselect evaluation
2625  *
2626  * NB: the result of the evaluation is no longer valid after this is done,
2627  * unless it is a pass-by-value datatype.
2628  * ----------
2629  */
2630 static void
2631 exec_eval_cleanup(PLpgSQL_execstate *estate)
2632 {
2633         /* Clear result of a full SPI_execute */
2634         if (estate->eval_tuptable != NULL)
2635                 SPI_freetuptable(estate->eval_tuptable);
2636         estate->eval_tuptable = NULL;
2637
2638         /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2639         if (estate->eval_econtext != NULL)
2640                 ResetExprContext(estate->eval_econtext);
2641 }
2642
2643
2644 /* ----------
2645  * Generate a prepared plan
2646  * ----------
2647  */
2648 static void
2649 exec_prepare_plan(PLpgSQL_execstate *estate,
2650                                   PLpgSQL_expr *expr, int cursorOptions)
2651 {
2652         int                     i;
2653         SPIPlanPtr      plan;
2654         Oid                *argtypes;
2655
2656         /*
2657          * We need a temporary argtypes array to load with data. (The finished
2658          * plan structure will contain a copy of it.)
2659          */
2660         argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2661
2662         for (i = 0; i < expr->nparams; i++)
2663         {
2664                 Datum           paramval;
2665                 bool            paramisnull;
2666
2667                 exec_eval_datum(estate, estate->datums[expr->params[i]],
2668                                                 InvalidOid,
2669                                                 &argtypes[i], &paramval, &paramisnull);
2670         }
2671
2672         /*
2673          * Generate and save the plan
2674          */
2675         plan = SPI_prepare_cursor(expr->query, expr->nparams, argtypes,
2676                                                           cursorOptions);
2677         if (plan == NULL)
2678         {
2679                 /* Some SPI errors deserve specific error messages */
2680                 switch (SPI_result)
2681                 {
2682                         case SPI_ERROR_COPY:
2683                                 ereport(ERROR,
2684                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2685                                                  errmsg("cannot COPY to/from client in PL/pgSQL")));
2686                         case SPI_ERROR_TRANSACTION:
2687                                 ereport(ERROR,
2688                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2689                                                  errmsg("cannot begin/end transactions in PL/pgSQL"),
2690                                                  errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2691                         default:
2692                                 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
2693                                          expr->query, SPI_result_code_string(SPI_result));
2694                 }
2695         }
2696         expr->plan = SPI_saveplan(plan);
2697         SPI_freeplan(plan);
2698         plan = expr->plan;
2699         expr->plan_argtypes = plan->argtypes;
2700         exec_simple_check_plan(expr);
2701
2702         pfree(argtypes);
2703 }
2704
2705
2706 /* ----------
2707  * exec_stmt_execsql                    Execute an SQL statement (possibly with INTO).
2708  * ----------
2709  */
2710 static int
2711 exec_stmt_execsql(PLpgSQL_execstate *estate,
2712                                   PLpgSQL_stmt_execsql *stmt)
2713 {
2714         Datum      *values;
2715         char       *nulls;
2716         long            tcount;
2717         int                     rc;
2718         PLpgSQL_expr *expr = stmt->sqlstmt;
2719
2720         /*
2721          * On the first call for this statement generate the plan, and detect
2722          * whether the statement is INSERT/UPDATE/DELETE
2723          */
2724         if (expr->plan == NULL)
2725         {
2726                 ListCell   *l;
2727
2728                 exec_prepare_plan(estate, expr, 0);
2729                 stmt->mod_stmt = false;
2730                 foreach(l, expr->plan->plancache_list)
2731                 {
2732                         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2733                         ListCell   *l2;
2734
2735                         foreach(l2, plansource->plan->stmt_list)
2736                         {
2737                                 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2738
2739                                 if (IsA(p, PlannedStmt) &&
2740                                         p->canSetTag)
2741                                 {
2742                                         if (p->commandType == CMD_INSERT ||
2743                                                 p->commandType == CMD_UPDATE ||
2744                                                 p->commandType == CMD_DELETE)
2745                                                 stmt->mod_stmt = true;
2746                                 }
2747                         }
2748                 }
2749         }
2750
2751         /*
2752          * Now build up the values and nulls arguments for SPI_execute_plan()
2753          */
2754         eval_expr_params(estate, expr, &values, &nulls);
2755
2756         /*
2757          * If we have INTO, then we only need one row back ... but if we have INTO
2758          * STRICT, ask for two rows, so that we can verify the statement returns
2759          * only one.  INSERT/UPDATE/DELETE are always treated strictly. Without
2760          * INTO, just run the statement to completion (tcount = 0).
2761          *
2762          * We could just ask for two rows always when using INTO, but there are
2763          * some cases where demanding the extra row costs significant time, eg by
2764          * forcing completion of a sequential scan.  So don't do it unless we need
2765          * to enforce strictness.
2766          */
2767         if (stmt->into)
2768         {
2769                 if (stmt->strict || stmt->mod_stmt)
2770                         tcount = 2;
2771                 else
2772                         tcount = 1;
2773         }
2774         else
2775                 tcount = 0;
2776
2777         /*
2778          * Execute the plan
2779          */
2780         rc = SPI_execute_plan(expr->plan, values, nulls,
2781                                                   estate->readonly_func, tcount);
2782
2783         /*
2784          * Check for error, and set FOUND if appropriate (for historical reasons
2785          * we set FOUND only for certain query types).  Also Assert that we
2786          * identified the statement type the same as SPI did.
2787          */
2788         switch (rc)
2789         {
2790                 case SPI_OK_SELECT:
2791                         Assert(!stmt->mod_stmt);
2792                         exec_set_found(estate, (SPI_processed != 0));
2793                         break;
2794
2795                 case SPI_OK_INSERT:
2796                 case SPI_OK_UPDATE:
2797                 case SPI_OK_DELETE:
2798                 case SPI_OK_INSERT_RETURNING:
2799                 case SPI_OK_UPDATE_RETURNING:
2800                 case SPI_OK_DELETE_RETURNING:
2801                         Assert(stmt->mod_stmt);
2802                         exec_set_found(estate, (SPI_processed != 0));
2803                         break;
2804
2805                 case SPI_OK_SELINTO:
2806                 case SPI_OK_UTILITY:
2807                         Assert(!stmt->mod_stmt);
2808                         break;
2809
2810                 default:
2811                         elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2812                                  expr->query, SPI_result_code_string(rc));
2813         }
2814
2815         /* All variants should save result info for GET DIAGNOSTICS */
2816         estate->eval_processed = SPI_processed;
2817         estate->eval_lastoid = SPI_lastoid;
2818
2819         /* Process INTO if present */
2820         if (stmt->into)
2821         {
2822                 SPITupleTable *tuptab = SPI_tuptable;
2823                 uint32          n = SPI_processed;
2824                 PLpgSQL_rec *rec = NULL;
2825                 PLpgSQL_row *row = NULL;
2826
2827                 /* If the statement did not return a tuple table, complain */
2828                 if (tuptab == NULL)
2829                         ereport(ERROR,
2830                                         (errcode(ERRCODE_SYNTAX_ERROR),
2831                                 errmsg("INTO used with a command that cannot return data")));
2832
2833                 /* Determine if we assign to a record or a row */
2834                 if (stmt->rec != NULL)
2835                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2836                 else if (stmt->row != NULL)
2837                         row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2838                 else
2839                         elog(ERROR, "unsupported target");
2840
2841                 /*
2842                  * If SELECT ... INTO specified STRICT, and the query didn't find
2843                  * exactly one row, throw an error.  If STRICT was not specified, then
2844                  * allow the query to find any number of rows.
2845                  */
2846                 if (n == 0)
2847                 {
2848                         if (stmt->strict)
2849                                 ereport(ERROR,
2850                                                 (errcode(ERRCODE_NO_DATA_FOUND),
2851                                                  errmsg("query returned no rows")));
2852                         /* set the target to NULL(s) */
2853                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2854                 }
2855                 else
2856                 {
2857                         if (n > 1 && (stmt->strict || stmt->mod_stmt))
2858                                 ereport(ERROR,
2859                                                 (errcode(ERRCODE_TOO_MANY_ROWS),
2860                                                  errmsg("query returned more than one row")));
2861                         /* Put the first result row into the target */
2862                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2863                 }
2864
2865                 /* Clean up */
2866                 SPI_freetuptable(SPI_tuptable);
2867         }
2868         else
2869         {
2870                 /* If the statement returned a tuple table, complain */
2871                 if (SPI_tuptable != NULL)
2872                         ereport(ERROR,
2873                                         (errcode(ERRCODE_SYNTAX_ERROR),
2874                                          errmsg("query has no destination for result data"),
2875                                          (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2876         }
2877
2878         pfree(values);
2879         pfree(nulls);
2880
2881         return PLPGSQL_RC_OK;
2882 }
2883
2884
2885 /* ----------
2886  * exec_stmt_dynexecute                 Execute a dynamic SQL query
2887  *                                      (possibly with INTO).
2888  * ----------
2889  */
2890 static int
2891 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2892                                          PLpgSQL_stmt_dynexecute *stmt)
2893 {
2894         Datum           query;
2895         bool            isnull = false;
2896         Oid                     restype;
2897         char       *querystr;
2898         int                     exec_res;
2899
2900         /*
2901          * First we evaluate the string expression after the EXECUTE keyword. Its
2902          * result is the querystring we have to execute.
2903          */
2904         query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2905         if (isnull)
2906                 ereport(ERROR,
2907                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2908                                  errmsg("cannot EXECUTE a null querystring")));
2909
2910         /* Get the C-String representation */
2911         querystr = convert_value_to_string(query, restype);
2912
2913         exec_eval_cleanup(estate);
2914
2915         /*
2916          * Execute the query without preparing a saved plan.
2917          */
2918         if (stmt->params)
2919         {
2920                 PreparedParamsData *ppd;
2921
2922                 ppd = exec_eval_using_params(estate, stmt->params);
2923                 exec_res = SPI_execute_with_args(querystr,
2924                                                                                  ppd->nargs, ppd->types,
2925                                                                                  ppd->values, ppd->nulls,
2926                                                                                  estate->readonly_func, 0);
2927                 free_params_data(ppd);
2928         }
2929         else
2930                 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2931
2932         switch (exec_res)
2933         {
2934                 case SPI_OK_SELECT:
2935                 case SPI_OK_INSERT:
2936                 case SPI_OK_UPDATE:
2937                 case SPI_OK_DELETE:
2938                 case SPI_OK_INSERT_RETURNING:
2939                 case SPI_OK_UPDATE_RETURNING:
2940                 case SPI_OK_DELETE_RETURNING:
2941                 case SPI_OK_UTILITY:
2942                         break;
2943
2944                 case 0:
2945
2946                         /*
2947                          * Also allow a zero return, which implies the querystring
2948                          * contained no commands.
2949                          */
2950                         break;
2951
2952                 case SPI_OK_SELINTO:
2953
2954                         /*
2955                          * We want to disallow SELECT INTO for now, because its behavior
2956                          * is not consistent with SELECT INTO in a normal plpgsql context.
2957                          * (We need to reimplement EXECUTE to parse the string as a
2958                          * plpgsql command, not just feed it to SPI_execute.) However,
2959                          * CREATE AS should be allowed ... and since it produces the same
2960                          * parsetree as SELECT INTO, there's no way to tell the difference
2961                          * except to look at the source text.  Wotta kluge!
2962                          */
2963                         {
2964                                 char       *ptr;
2965
2966                                 for (ptr = querystr; *ptr; ptr++)
2967                                         if (!scanner_isspace(*ptr))
2968                                                 break;
2969                                 if (*ptr == 'S' || *ptr == 's')
2970                                         ereport(ERROR,
2971                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2972                                                          errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2973                                 break;
2974                         }
2975
2976                         /* Some SPI errors deserve specific error messages */
2977                 case SPI_ERROR_COPY:
2978                         ereport(ERROR,
2979                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2980                                          errmsg("cannot COPY to/from client in PL/pgSQL")));
2981                 case SPI_ERROR_TRANSACTION:
2982                         ereport(ERROR,
2983                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2984                                          errmsg("cannot begin/end transactions in PL/pgSQL"),
2985                         errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2986
2987                 default:
2988                         elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2989                                  querystr, SPI_result_code_string(exec_res));
2990                         break;
2991         }
2992
2993         /* Save result info for GET DIAGNOSTICS */
2994         estate->eval_processed = SPI_processed;
2995         estate->eval_lastoid = SPI_lastoid;
2996
2997         /* Process INTO if present */
2998         if (stmt->into)
2999         {
3000                 SPITupleTable *tuptab = SPI_tuptable;
3001                 uint32          n = SPI_processed;
3002                 PLpgSQL_rec *rec = NULL;
3003                 PLpgSQL_row *row = NULL;
3004
3005                 /* If the statement did not return a tuple table, complain */
3006                 if (tuptab == NULL)
3007                         ereport(ERROR,
3008                                         (errcode(ERRCODE_SYNTAX_ERROR),
3009                                 errmsg("INTO used with a command that cannot return data")));
3010
3011                 /* Determine if we assign to a record or a row */
3012                 if (stmt->rec != NULL)
3013                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3014                 else if (stmt->row != NULL)
3015                         row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3016                 else
3017                         elog(ERROR, "unsupported target");
3018
3019                 /*
3020                  * If SELECT ... INTO specified STRICT, and the query didn't find
3021                  * exactly one row, throw an error.  If STRICT was not specified, then
3022                  * allow the query to find any number of rows.
3023                  */
3024                 if (n == 0)
3025                 {
3026                         if (stmt->strict)
3027                                 ereport(ERROR,
3028                                                 (errcode(ERRCODE_NO_DATA_FOUND),
3029                                                  errmsg("query returned no rows")));
3030                         /* set the target to NULL(s) */
3031                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3032                 }
3033                 else
3034                 {
3035                         if (n > 1 && stmt->strict)
3036                                 ereport(ERROR,
3037                                                 (errcode(ERRCODE_TOO_MANY_ROWS),
3038                                                  errmsg("query returned more than one row")));
3039                         /* Put the first result row into the target */
3040                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3041                 }
3042         }
3043         else
3044         {
3045                 /*
3046                  * It might be a good idea to raise an error if the query returned
3047                  * tuples that are being ignored, but historically we have not done
3048                  * that.
3049                  */
3050         }
3051
3052         /* Release any result from SPI_execute, as well as the querystring */
3053         SPI_freetuptable(SPI_tuptable);
3054         pfree(querystr);
3055
3056         return PLPGSQL_RC_OK;
3057 }
3058
3059
3060 /* ----------
3061  * exec_stmt_dynfors                    Execute a dynamic query, assign each
3062  *                                      tuple to a record or row and
3063  *                                      execute a group of statements
3064  *                                      for it.
3065  * ----------
3066  */
3067 static int
3068 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3069 {
3070         Portal          portal;
3071         int                     rc;
3072
3073         portal = exec_dynquery_with_params(estate, stmt->query, stmt->params);
3074
3075         /*
3076          * Execute the loop
3077          */
3078         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3079
3080         /*
3081          * Close the implicit cursor
3082          */
3083         SPI_cursor_close(portal);
3084
3085         return rc;
3086 }
3087
3088
3089 /* ----------
3090  * exec_stmt_open                       Execute an OPEN cursor statement
3091  * ----------
3092  */
3093 static int
3094 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3095 {
3096         PLpgSQL_var *curvar;
3097         char       *curname = NULL;
3098         PLpgSQL_expr *query;
3099         Portal          portal;
3100         Datum      *values;
3101         char       *nulls;
3102         bool            isnull;
3103
3104         /* ----------
3105          * Get the cursor variable and if it has an assigned name, check
3106          * that it's not in use currently.
3107          * ----------
3108          */
3109         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3110         if (!curvar->isnull)
3111         {
3112                 curname = TextDatumGetCString(curvar->value);
3113                 if (SPI_cursor_find(curname) != NULL)
3114                         ereport(ERROR,
3115                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
3116                                          errmsg("cursor \"%s\" already in use", curname)));
3117         }
3118
3119         /* ----------
3120          * Process the OPEN according to it's type.
3121          * ----------
3122          */
3123         if (stmt->query != NULL)
3124         {
3125                 /* ----------
3126                  * This is an OPEN refcursor FOR SELECT ...
3127                  *
3128                  * We just make sure the query is planned. The real work is
3129                  * done downstairs.
3130                  * ----------
3131                  */
3132                 query = stmt->query;
3133                 if (query->plan == NULL)
3134                         exec_prepare_plan(estate, query, stmt->cursor_options);
3135         }
3136         else if (stmt->dynquery != NULL)
3137         {
3138                 /* ----------
3139                  * This is an OPEN refcursor FOR EXECUTE ...
3140                  * ----------
3141                  */
3142                 Datum           queryD;
3143                 Oid                     restype;
3144                 char       *querystr;
3145                 SPIPlanPtr      curplan;
3146
3147                 /* ----------
3148                  * We evaluate the string expression after the
3149                  * EXECUTE keyword. It's result is the querystring we have
3150                  * to execute.
3151                  * ----------
3152                  */
3153                 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
3154                 if (isnull)
3155                         ereport(ERROR,
3156                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3157                                          errmsg("cannot EXECUTE a null querystring")));
3158
3159                 /* Get the C-String representation */
3160                 querystr = convert_value_to_string(queryD, restype);
3161
3162                 exec_eval_cleanup(estate);
3163
3164                 /* ----------
3165                  * Now we prepare a query plan for it and open a cursor
3166                  * ----------
3167                  */
3168                 curplan = SPI_prepare_cursor(querystr, 0, NULL, stmt->cursor_options);
3169                 if (curplan == NULL)
3170                         elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
3171                                  querystr, SPI_result_code_string(SPI_result));
3172                 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
3173                                                                  estate->readonly_func);
3174                 if (portal == NULL)
3175                         elog(ERROR, "could not open cursor for query \"%s\": %s",
3176                                  querystr, SPI_result_code_string(SPI_result));
3177                 pfree(querystr);
3178                 SPI_freeplan(curplan);
3179
3180                 /*
3181                  * If cursor variable was NULL, store the generated portal name in it
3182                  */
3183                 if (curname == NULL)
3184                         assign_text_var(curvar, portal->name);
3185
3186                 return PLPGSQL_RC_OK;
3187         }
3188         else
3189         {
3190                 /* ----------
3191                  * This is an OPEN cursor
3192                  *
3193                  * Note: parser should already have checked that statement supplies
3194                  * args iff cursor needs them, but we check again to be safe.
3195                  * ----------
3196                  */
3197                 if (stmt->argquery != NULL)
3198                 {
3199                         /* ----------
3200                          * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
3201                          * statement to evaluate the args and put 'em into the
3202                          * internal row.
3203                          * ----------
3204                          */
3205                         PLpgSQL_stmt_execsql set_args;
3206
3207                         if (curvar->cursor_explicit_argrow < 0)
3208                                 ereport(ERROR,
3209                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3210                                         errmsg("arguments given for cursor without arguments")));
3211
3212                         memset(&set_args, 0, sizeof(set_args));
3213                         set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3214                         set_args.lineno = stmt->lineno;
3215                         set_args.sqlstmt = stmt->argquery;
3216                         set_args.into = true;
3217                         /* XXX historically this has not been STRICT */
3218                         set_args.row = (PLpgSQL_row *)
3219                                 (estate->datums[curvar->cursor_explicit_argrow]);
3220
3221                         if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3222                                 elog(ERROR, "open cursor failed during argument processing");
3223                 }
3224                 else
3225                 {
3226                         if (curvar->cursor_explicit_argrow >= 0)
3227                                 ereport(ERROR,
3228                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3229                                                  errmsg("arguments required for cursor")));
3230                 }
3231
3232                 query = curvar->cursor_explicit_expr;
3233                 if (query->plan == NULL)
3234                         exec_prepare_plan(estate, query, curvar->cursor_options);
3235         }
3236
3237         /*
3238          * Now build up the values and nulls arguments for SPI_execute_plan()
3239          */
3240         eval_expr_params(estate, query, &values, &nulls);
3241
3242         /*
3243          * Open the cursor
3244          */
3245         portal = SPI_cursor_open(curname, query->plan, values, nulls,
3246                                                          estate->readonly_func);
3247         if (portal == NULL)
3248                 elog(ERROR, "could not open cursor: %s",
3249                          SPI_result_code_string(SPI_result));
3250
3251         /*
3252          * If cursor variable was NULL, store the generated portal name in it
3253          */
3254         if (curname == NULL)
3255                 assign_text_var(curvar, portal->name);
3256
3257         pfree(values);
3258         pfree(nulls);
3259         if (curname)
3260                 pfree(curname);
3261
3262         return PLPGSQL_RC_OK;
3263 }
3264
3265
3266 /* ----------
3267  * exec_stmt_fetch                      Fetch from a cursor into a target, or just
3268  *                                                      move the current position of the cursor
3269  * ----------
3270  */
3271 static int
3272 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3273 {
3274         PLpgSQL_var *curvar = NULL;
3275         PLpgSQL_rec *rec = NULL;
3276         PLpgSQL_row *row = NULL;
3277         long            how_many = stmt->how_many;
3278         SPITupleTable *tuptab;
3279         Portal          portal;
3280         char       *curname;
3281         int                     n;
3282
3283         /* ----------
3284          * Get the portal of the cursor by name
3285          * ----------
3286          */
3287         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3288         if (curvar->isnull)
3289                 ereport(ERROR,
3290                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3291                                  errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3292         curname = TextDatumGetCString(curvar->value);
3293
3294         portal = SPI_cursor_find(curname);
3295         if (portal == NULL)
3296                 ereport(ERROR,
3297                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
3298                                  errmsg("cursor \"%s\" does not exist", curname)));
3299         pfree(curname);
3300
3301         /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3302         if (stmt->expr)
3303         {
3304                 bool            isnull;
3305
3306                 /* XXX should be doing this in LONG not INT width */
3307                 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3308
3309                 if (isnull)
3310                         ereport(ERROR,
3311                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3312                                          errmsg("relative or absolute cursor position is NULL")));
3313
3314                 exec_eval_cleanup(estate);
3315         }
3316
3317         if (!stmt->is_move)
3318         {
3319                 /* ----------
3320                  * Determine if we fetch into a record or a row
3321                  * ----------
3322                  */
3323                 if (stmt->rec != NULL)
3324                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3325                 else if (stmt->row != NULL)
3326                         row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3327                 else
3328                         elog(ERROR, "unsupported target");
3329
3330                 /* ----------
3331                  * Fetch 1 tuple from the cursor
3332                  * ----------
3333                  */
3334                 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3335                 tuptab = SPI_tuptable;
3336                 n = SPI_processed;
3337
3338                 /* ----------
3339                  * Set the target and the global FOUND variable appropriately.
3340                  * ----------
3341                  */
3342                 if (n == 0)
3343                 {
3344                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3345                         exec_set_found(estate, false);
3346                 }
3347                 else
3348                 {
3349                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3350                         exec_set_found(estate, true);
3351                 }
3352
3353                 SPI_freetuptable(tuptab);
3354         }
3355         else
3356         {
3357                 /* Move the cursor */
3358                 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3359                 n = SPI_processed;
3360
3361                 /* Set the global FOUND variable appropriately. */
3362                 exec_set_found(estate, n != 0);
3363         }
3364
3365         return PLPGSQL_RC_OK;
3366 }
3367
3368 /*&nb