]> granicus.if.org Git - postgresql/blob - src/pl/plpgsql/src/pl_exec.c
Simplify ParamListInfo data structure to support only numbered parameters,
[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-2006, 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.164 2006/04/22 01:26:01 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "plpgsql.h"
17 #include "pl.tab.h"
18
19 #include <ctype.h>
20
21 #include "access/heapam.h"
22 #include "catalog/pg_proc.h"
23 #include "catalog/pg_type.h"
24 #include "executor/spi_priv.h"
25 #include "funcapi.h"
26 #include "optimizer/clauses.h"
27 #include "parser/parse_expr.h"
28 #include "tcop/tcopprot.h"
29 #include "utils/array.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/memutils.h"
33 #include "utils/typcache.h"
34
35
36 static const char *const raise_skip_msg = "RAISE";
37
38
39 /*
40  * All plpgsql function executions within a single transaction share
41  * the same executor EState for evaluating "simple" expressions.  Each
42  * function call creates its own "eval_econtext" ExprContext within this
43  * estate.      We destroy the estate at transaction shutdown to ensure there
44  * is no permanent leakage of memory (especially for xact abort case).
45  */
46 static EState *simple_eval_estate = NULL;
47
48 /************************************************************
49  * Local function forward declarations
50  ************************************************************/
51 static void plpgsql_exec_error_callback(void *arg);
52 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
53
54 static int exec_stmt_block(PLpgSQL_execstate *estate,
55                                 PLpgSQL_stmt_block *block);
56 static int exec_stmts(PLpgSQL_execstate *estate,
57                    List *stmts);
58 static int exec_stmt(PLpgSQL_execstate *estate,
59                   PLpgSQL_stmt *stmt);
60 static int exec_stmt_assign(PLpgSQL_execstate *estate,
61                                  PLpgSQL_stmt_assign *stmt);
62 static int exec_stmt_perform(PLpgSQL_execstate *estate,
63                                   PLpgSQL_stmt_perform *stmt);
64 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
65                                   PLpgSQL_stmt_getdiag *stmt);
66 static int exec_stmt_if(PLpgSQL_execstate *estate,
67                          PLpgSQL_stmt_if *stmt);
68 static int exec_stmt_loop(PLpgSQL_execstate *estate,
69                            PLpgSQL_stmt_loop *stmt);
70 static int exec_stmt_while(PLpgSQL_execstate *estate,
71                                 PLpgSQL_stmt_while *stmt);
72 static int exec_stmt_fori(PLpgSQL_execstate *estate,
73                            PLpgSQL_stmt_fori *stmt);
74 static int exec_stmt_fors(PLpgSQL_execstate *estate,
75                            PLpgSQL_stmt_fors *stmt);
76 static int exec_stmt_select(PLpgSQL_execstate *estate,
77                                  PLpgSQL_stmt_select *stmt);
78 static int exec_stmt_open(PLpgSQL_execstate *estate,
79                            PLpgSQL_stmt_open *stmt);
80 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
81                                 PLpgSQL_stmt_fetch *stmt);
82 static int exec_stmt_close(PLpgSQL_execstate *estate,
83                                 PLpgSQL_stmt_close *stmt);
84 static int exec_stmt_exit(PLpgSQL_execstate *estate,
85                            PLpgSQL_stmt_exit *stmt);
86 static int exec_stmt_return(PLpgSQL_execstate *estate,
87                                  PLpgSQL_stmt_return *stmt);
88 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
89                                           PLpgSQL_stmt_return_next *stmt);
90 static int exec_stmt_raise(PLpgSQL_execstate *estate,
91                                 PLpgSQL_stmt_raise *stmt);
92 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
93                                   PLpgSQL_stmt_execsql *stmt);
94 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
95                                          PLpgSQL_stmt_dynexecute *stmt);
96 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
97                                   PLpgSQL_stmt_dynfors *stmt);
98
99 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
100                                          PLpgSQL_function *func,
101                                          ReturnSetInfo *rsi);
102 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
103
104 static void exec_prepare_plan(PLpgSQL_execstate *estate,
105                                   PLpgSQL_expr *expr);
106 static bool exec_simple_check_node(Node *node);
107 static void exec_simple_check_plan(PLpgSQL_expr *expr);
108 static Datum exec_eval_simple_expr(PLpgSQL_execstate *estate,
109                                           PLpgSQL_expr *expr,
110                                           bool *isNull,
111                                           Oid *rettype);
112
113 static void exec_assign_expr(PLpgSQL_execstate *estate,
114                                  PLpgSQL_datum *target,
115                                  PLpgSQL_expr *expr);
116 static void exec_assign_value(PLpgSQL_execstate *estate,
117                                   PLpgSQL_datum *target,
118                                   Datum value, Oid valtype, bool *isNull);
119 static void exec_eval_datum(PLpgSQL_execstate *estate,
120                                 PLpgSQL_datum *datum,
121                                 Oid expectedtypeid,
122                                 Oid *typeid,
123                                 Datum *value,
124                                 bool *isnull);
125 static int exec_eval_integer(PLpgSQL_execstate *estate,
126                                   PLpgSQL_expr *expr,
127                                   bool *isNull);
128 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
129                                   PLpgSQL_expr *expr,
130                                   bool *isNull);
131 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
132                            PLpgSQL_expr *expr,
133                            bool *isNull,
134                            Oid *rettype);
135 static int exec_run_select(PLpgSQL_execstate *estate,
136                                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
137 static void exec_move_row(PLpgSQL_execstate *estate,
138                           PLpgSQL_rec *rec,
139                           PLpgSQL_row *row,
140                           HeapTuple tup, TupleDesc tupdesc);
141 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
142                                         PLpgSQL_row *row,
143                                         TupleDesc tupdesc);
144 static char *convert_value_to_string(Datum value, Oid valtype);
145 static Datum exec_cast_value(Datum value, Oid valtype,
146                                 Oid reqtype,
147                                 FmgrInfo *reqinput,
148                                 Oid reqtypioparam,
149                                 int32 reqtypmod,
150                                 bool isnull);
151 static Datum exec_simple_cast_value(Datum value, Oid valtype,
152                                            Oid reqtype, int32 reqtypmod,
153                                            bool isnull);
154 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
155 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
156 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
157 static void free_var(PLpgSQL_var *var);
158
159
160 /* ----------
161  * plpgsql_exec_function        Called by the call handler for
162  *                              function execution.
163  * ----------
164  */
165 Datum
166 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
167 {
168         PLpgSQL_execstate estate;
169         ErrorContextCallback plerrcontext;
170         int                     i;
171         int                     rc;
172
173         /*
174          * Setup the execution state
175          */
176         plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
177
178         /*
179          * Setup error traceback support for ereport()
180          */
181         plerrcontext.callback = plpgsql_exec_error_callback;
182         plerrcontext.arg = &estate;
183         plerrcontext.previous = error_context_stack;
184         error_context_stack = &plerrcontext;
185
186         /*
187          * Make local execution copies of all the datums
188          */
189         estate.err_text = gettext_noop("during initialization of execution state");
190         for (i = 0; i < estate.ndatums; i++)
191                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
192
193         /*
194          * Store the actual call argument values into the appropriate variables
195          */
196         estate.err_text = gettext_noop("while storing call arguments into local variables");
197         for (i = 0; i < func->fn_nargs; i++)
198         {
199                 int                     n = func->fn_argvarnos[i];
200
201                 switch (estate.datums[n]->dtype)
202                 {
203                         case PLPGSQL_DTYPE_VAR:
204                                 {
205                                         PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
206
207                                         var->value = fcinfo->arg[i];
208                                         var->isnull = fcinfo->argnull[i];
209                                         var->freeval = false;
210                                 }
211                                 break;
212
213                         case PLPGSQL_DTYPE_ROW:
214                                 {
215                                         PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
216
217                                         if (!fcinfo->argnull[i])
218                                         {
219                                                 HeapTupleHeader td;
220                                                 Oid                     tupType;
221                                                 int32           tupTypmod;
222                                                 TupleDesc       tupdesc;
223                                                 HeapTupleData tmptup;
224
225                                                 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
226                                                 /* Extract rowtype info and find a tupdesc */
227                                                 tupType = HeapTupleHeaderGetTypeId(td);
228                                                 tupTypmod = HeapTupleHeaderGetTypMod(td);
229                                                 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
230                                                 /* Build a temporary HeapTuple control structure */
231                                                 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
232                                                 ItemPointerSetInvalid(&(tmptup.t_self));
233                                                 tmptup.t_tableOid = InvalidOid;
234                                                 tmptup.t_data = td;
235                                                 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
236                                         }
237                                         else
238                                         {
239                                                 /* If arg is null, treat it as an empty row */
240                                                 exec_move_row(&estate, NULL, row, NULL, NULL);
241                                         }
242                                 }
243                                 break;
244
245                         default:
246                                 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
247                 }
248         }
249
250         /*
251          * Set the magic variable FOUND to false
252          */
253         exec_set_found(&estate, false);
254
255         /*
256          * Now call the toplevel block of statements
257          */
258         estate.err_text = NULL;
259         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
260         rc = exec_stmt_block(&estate, func->action);
261         if (rc != PLPGSQL_RC_RETURN)
262         {
263                 estate.err_stmt = NULL;
264                 estate.err_text = NULL;
265
266                 /*
267                  * Provide a more helpful message if a CONTINUE has been used outside
268                  * a loop.
269                  */
270                 if (rc == PLPGSQL_RC_CONTINUE)
271                         ereport(ERROR,
272                                         (errcode(ERRCODE_SYNTAX_ERROR),
273                                          errmsg("CONTINUE cannot be used outside a loop")));
274                 else
275                         ereport(ERROR,
276                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
277                                 errmsg("control reached end of function without RETURN")));
278         }
279
280         /*
281          * We got a return value - process it
282          */
283         estate.err_stmt = NULL;
284         estate.err_text = gettext_noop("while casting return value to function's return type");
285
286         fcinfo->isnull = estate.retisnull;
287
288         if (estate.retisset)
289         {
290                 ReturnSetInfo *rsi = estate.rsi;
291
292                 /* Check caller can handle a set result */
293                 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
294                         (rsi->allowedModes & SFRM_Materialize) == 0)
295                         ereport(ERROR,
296                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
297                                          errmsg("set-valued function called in context that cannot accept a set")));
298                 rsi->returnMode = SFRM_Materialize;
299
300                 /* If we produced any tuples, send back the result */
301                 if (estate.tuple_store)
302                 {
303                         rsi->setResult = estate.tuple_store;
304                         if (estate.rettupdesc)
305                         {
306                                 MemoryContext oldcxt;
307
308                                 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
309                                 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
310                                 MemoryContextSwitchTo(oldcxt);
311                         }
312                 }
313                 estate.retval = (Datum) 0;
314                 fcinfo->isnull = true;
315         }
316         else if (!estate.retisnull)
317         {
318                 if (estate.retistuple)
319                 {
320                         /*
321                          * We have to check that the returned tuple actually matches
322                          * the expected result type.  XXX would be better to cache the
323                          * tupdesc instead of repeating get_call_result_type()
324                          */
325                         TupleDesc       tupdesc;
326
327                         switch (get_call_result_type(fcinfo, NULL, &tupdesc))
328                         {
329                                 case TYPEFUNC_COMPOSITE:
330                                         /* got the expected result rowtype, now check it */
331                                         if (estate.rettupdesc == NULL ||
332                                                 !compatible_tupdesc(estate.rettupdesc, tupdesc))
333                                                 ereport(ERROR,
334                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
335                                                                  errmsg("returned record type does not match expected record type")));
336                                         break;
337                                 case TYPEFUNC_RECORD:
338                                         /*
339                                          * Failed to determine actual type of RECORD.  We could
340                                          * raise an error here, but what this means in practice
341                                          * is that the caller is expecting any old generic
342                                          * rowtype, so we don't really need to be restrictive.
343                                          * Pass back the generated result type, instead.
344                                          */
345                                         tupdesc = estate.rettupdesc;
346                                         if (tupdesc == NULL)            /* shouldn't happen */
347                                                 elog(ERROR, "return type must be a row type");
348                                         break;
349                                 default:
350                                         /* shouldn't get here if retistuple is true ... */
351                                         elog(ERROR, "return type must be a row type");
352                                         break;
353                         }
354
355                         /*
356                          * Copy tuple to upper executor memory, as a tuple Datum.
357                          * Make sure it is labeled with the caller-supplied tuple type.
358                          */
359                         estate.retval =
360                                 PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
361                                                                                                 tupdesc));
362                 }
363                 else
364                 {
365                         /* Cast value to proper type */
366                         estate.retval = exec_cast_value(estate.retval, estate.rettype,
367                                                                                         func->fn_rettype,
368                                                                                         &(func->fn_retinput),
369                                                                                         func->fn_rettypioparam,
370                                                                                         -1,
371                                                                                         fcinfo->isnull);
372
373                         /*
374                          * If the function's return type isn't by value, copy the value
375                          * into upper executor memory context.
376                          */
377                         if (!fcinfo->isnull && !func->fn_retbyval)
378                         {
379                                 Size            len;
380                                 void       *tmp;
381
382                                 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
383                                 tmp = (void *) SPI_palloc(len);
384                                 memcpy(tmp, DatumGetPointer(estate.retval), len);
385                                 estate.retval = PointerGetDatum(tmp);
386                         }
387                 }
388         }
389
390         /* Clean up any leftover temporary memory */
391         FreeExprContext(estate.eval_econtext);
392         estate.eval_econtext = NULL;
393         exec_eval_cleanup(&estate);
394
395         /*
396          * Pop the error context stack
397          */
398         error_context_stack = plerrcontext.previous;
399
400         /*
401          * Return the function's result
402          */
403         return estate.retval;
404 }
405
406
407 /* ----------
408  * plpgsql_exec_trigger         Called by the call handler for
409  *                              trigger execution.
410  * ----------
411  */
412 HeapTuple
413 plpgsql_exec_trigger(PLpgSQL_function *func,
414                                          TriggerData *trigdata)
415 {
416         PLpgSQL_execstate estate;
417         ErrorContextCallback plerrcontext;
418         int                     i;
419         int                     rc;
420         PLpgSQL_var *var;
421         PLpgSQL_rec *rec_new,
422                            *rec_old;
423         HeapTuple       rettup;
424
425         /*
426          * Setup the execution state
427          */
428         plpgsql_estate_setup(&estate, func, NULL);
429
430         /*
431          * Setup error traceback support for ereport()
432          */
433         plerrcontext.callback = plpgsql_exec_error_callback;
434         plerrcontext.arg = &estate;
435         plerrcontext.previous = error_context_stack;
436         error_context_stack = &plerrcontext;
437
438         /*
439          * Make local execution copies of all the datums
440          */
441         estate.err_text = gettext_noop("during initialization of execution state");
442         for (i = 0; i < estate.ndatums; i++)
443                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
444
445         /*
446          * Put the OLD and NEW tuples into record variables
447          */
448         rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
449         rec_new->freetup = false;
450         rec_new->freetupdesc = false;
451         rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
452         rec_old->freetup = false;
453         rec_old->freetupdesc = false;
454
455         if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
456         {
457                 /*
458                  * Per-statement triggers don't use OLD/NEW variables
459                  */
460                 rec_new->tup = NULL;
461                 rec_new->tupdesc = NULL;
462                 rec_old->tup = NULL;
463                 rec_old->tupdesc = NULL;
464         }
465         else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
466         {
467                 rec_new->tup = trigdata->tg_trigtuple;
468                 rec_new->tupdesc = trigdata->tg_relation->rd_att;
469                 rec_old->tup = NULL;
470                 rec_old->tupdesc = NULL;
471         }
472         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
473         {
474                 rec_new->tup = trigdata->tg_newtuple;
475                 rec_new->tupdesc = trigdata->tg_relation->rd_att;
476                 rec_old->tup = trigdata->tg_trigtuple;
477                 rec_old->tupdesc = trigdata->tg_relation->rd_att;
478         }
479         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
480         {
481                 rec_new->tup = NULL;
482                 rec_new->tupdesc = NULL;
483                 rec_old->tup = trigdata->tg_trigtuple;
484                 rec_old->tupdesc = trigdata->tg_relation->rd_att;
485         }
486         else
487                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
488
489         /*
490          * Assign the special tg_ variables
491          */
492
493         var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
494         if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
495                 var->value = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
496         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
497                 var->value = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
498         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
499                 var->value = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
500         else
501                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
502         var->isnull = false;
503         var->freeval = true;
504
505         var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
506         var->value = DirectFunctionCall1(namein,
507                                                           CStringGetDatum(trigdata->tg_trigger->tgname));
508         var->isnull = false;
509         var->freeval = true;
510
511         var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
512         if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
513                 var->value = DirectFunctionCall1(textin, CStringGetDatum("BEFORE"));
514         else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
515                 var->value = DirectFunctionCall1(textin, CStringGetDatum("AFTER"));
516         else
517                 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
518         var->isnull = false;
519         var->freeval = true;
520
521         var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
522         if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
523                 var->value = DirectFunctionCall1(textin, CStringGetDatum("ROW"));
524         else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
525                 var->value = DirectFunctionCall1(textin, CStringGetDatum("STATEMENT"));
526         else
527                 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
528         var->isnull = false;
529         var->freeval = true;
530
531         var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
532         var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
533         var->isnull = false;
534         var->freeval = false;
535
536         var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
537         var->value = DirectFunctionCall1(namein,
538                         CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
539         var->isnull = false;
540         var->freeval = true;
541
542         var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
543         var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
544         var->isnull = false;
545         var->freeval = false;
546
547         /*
548          * Store the trigger argument values into the special execution state
549          * variables
550          */
551         estate.err_text = gettext_noop("while storing call arguments into local variables");
552         estate.trig_nargs = trigdata->tg_trigger->tgnargs;
553         if (estate.trig_nargs == 0)
554                 estate.trig_argv = NULL;
555         else
556         {
557                 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
558                 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
559                         estate.trig_argv[i] = DirectFunctionCall1(textin,
560                                                    CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
561         }
562
563         /*
564          * Set the magic variable FOUND to false
565          */
566         exec_set_found(&estate, false);
567
568         /*
569          * Now call the toplevel block of statements
570          */
571         estate.err_text = NULL;
572         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
573         rc = exec_stmt_block(&estate, func->action);
574         if (rc != PLPGSQL_RC_RETURN)
575         {
576                 estate.err_stmt = NULL;
577                 estate.err_text = NULL;
578
579                 /*
580                  * Provide a more helpful message if a CONTINUE has been used outside
581                  * a loop.
582                  */
583                 if (rc == PLPGSQL_RC_CONTINUE)
584                         ereport(ERROR,
585                                         (errcode(ERRCODE_SYNTAX_ERROR),
586                                          errmsg("CONTINUE cannot be used outside a loop")));
587                 else
588                         ereport(ERROR,
589                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
590                                 errmsg("control reached end of trigger procedure without RETURN")));
591         }
592
593         if (estate.retisset)
594                 ereport(ERROR,
595                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
596                                  errmsg("trigger procedure cannot return a set")));
597
598         /*
599          * Check that the returned tuple structure has the same attributes, the
600          * relation that fired the trigger has. A per-statement trigger always
601          * needs to return NULL, so we ignore any return value the function itself
602          * produces (XXX: is this a good idea?)
603          *
604          * XXX This way it is possible, that the trigger returns a tuple where
605          * attributes don't have the correct atttypmod's length. It's up to the
606          * trigger's programmer to ensure that this doesn't happen. Jan
607          */
608         if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
609                 rettup = NULL;
610         else
611         {
612                 if (!compatible_tupdesc(estate.rettupdesc,
613                                                                 trigdata->tg_relation->rd_att))
614                         ereport(ERROR,
615                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
616                                          errmsg("returned tuple structure does not match table of trigger event")));
617                 /* Copy tuple to upper executor memory */
618                 rettup = SPI_copytuple((HeapTuple) (estate.retval));
619         }
620
621         /* Clean up any leftover temporary memory */
622         FreeExprContext(estate.eval_econtext);
623         estate.eval_econtext = NULL;
624         exec_eval_cleanup(&estate);
625
626         /*
627          * Pop the error context stack
628          */
629         error_context_stack = plerrcontext.previous;
630
631         /*
632          * Return the trigger's result
633          */
634         return rettup;
635 }
636
637
638 /*
639  * error context callback to let us supply a call-stack traceback
640  */
641 static void
642 plpgsql_exec_error_callback(void *arg)
643 {
644         PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
645
646         /* safety check, shouldn't happen */
647         if (estate->err_func == NULL)
648                 return;
649
650         /* if we are doing RAISE, don't report its location */
651         if (estate->err_text == raise_skip_msg)
652                 return;
653
654         if (estate->err_stmt != NULL)
655         {
656                 /* translator: last %s is a plpgsql statement type name */
657                 errcontext("PL/pgSQL function \"%s\" line %d at %s",
658                                    estate->err_func->fn_name,
659                                    estate->err_stmt->lineno,
660                                    plpgsql_stmt_typename(estate->err_stmt));
661         }
662         else if (estate->err_text != NULL)
663         {
664                 /*
665                  * We don't expend the cycles to run gettext() on err_text unless we
666                  * actually need it.  Therefore, places that set up err_text should
667                  * use gettext_noop() to ensure the strings get recorded in the
668                  * message dictionary.
669                  */
670
671                 /*
672                  * translator: last %s is a phrase such as "while storing call
673                  * arguments into local variables"
674                  */
675                 errcontext("PL/pgSQL function \"%s\" %s",
676                                    estate->err_func->fn_name,
677                                    gettext(estate->err_text));
678         }
679         else
680                 errcontext("PL/pgSQL function \"%s\"",
681                                    estate->err_func->fn_name);
682 }
683
684
685 /* ----------
686  * Support function for initializing local execution variables
687  * ----------
688  */
689 static PLpgSQL_datum *
690 copy_plpgsql_datum(PLpgSQL_datum *datum)
691 {
692         PLpgSQL_datum *result;
693
694         switch (datum->dtype)
695         {
696                 case PLPGSQL_DTYPE_VAR:
697                         {
698                                 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
699
700                                 memcpy(new, datum, sizeof(PLpgSQL_var));
701                                 /* Ensure the value is null (possibly not needed?) */
702                                 new->value = 0;
703                                 new->isnull = true;
704                                 new->freeval = false;
705
706                                 result = (PLpgSQL_datum *) new;
707                         }
708                         break;
709
710                 case PLPGSQL_DTYPE_REC:
711                         {
712                                 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
713
714                                 memcpy(new, datum, sizeof(PLpgSQL_rec));
715                                 /* Ensure the value is null (possibly not needed?) */
716                                 new->tup = NULL;
717                                 new->tupdesc = NULL;
718                                 new->freetup = false;
719                                 new->freetupdesc = false;
720
721                                 result = (PLpgSQL_datum *) new;
722                         }
723                         break;
724
725                 case PLPGSQL_DTYPE_ROW:
726                 case PLPGSQL_DTYPE_RECFIELD:
727                 case PLPGSQL_DTYPE_ARRAYELEM:
728                 case PLPGSQL_DTYPE_TRIGARG:
729
730                         /*
731                          * These datum records are read-only at runtime, so no need to
732                          * copy them
733                          */
734                         result = datum;
735                         break;
736
737                 default:
738                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
739                         result = NULL;          /* keep compiler quiet */
740                         break;
741         }
742
743         return result;
744 }
745
746
747 static bool
748 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
749 {
750         for (; cond != NULL; cond = cond->next)
751         {
752                 int                     sqlerrstate = cond->sqlerrstate;
753
754                 /*
755                  * OTHERS matches everything *except* query-canceled; if you're
756                  * foolish enough, you can match that explicitly.
757                  */
758                 if (sqlerrstate == 0)
759                 {
760                         if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
761                                 return true;
762                 }
763                 /* Exact match? */
764                 else if (edata->sqlerrcode == sqlerrstate)
765                         return true;
766                 /* Category match? */
767                 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
768                                  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
769                         return true;
770         }
771         return false;
772 }
773
774
775 /* ----------
776  * exec_stmt_block                      Execute a block of statements
777  * ----------
778  */
779 static int
780 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
781 {
782         volatile int rc = -1;
783         int                     i;
784         int                     n;
785
786         /*
787          * First initialize all variables declared in this block
788          */
789         for (i = 0; i < block->n_initvars; i++)
790         {
791                 n = block->initvarnos[i];
792
793                 switch (estate->datums[n]->dtype)
794                 {
795                         case PLPGSQL_DTYPE_VAR:
796                                 {
797                                         PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
798
799                                         free_var(var);
800                                         if (!var->isconst || var->isnull)
801                                         {
802                                                 if (var->default_val == NULL)
803                                                 {
804                                                         var->value = (Datum) 0;
805                                                         var->isnull = true;
806                                                         if (var->notnull)
807                                                                 ereport(ERROR,
808                                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
809                                                                          errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
810                                                                                         var->refname)));
811                                                 }
812                                                 else
813                                                 {
814                                                         exec_assign_expr(estate, (PLpgSQL_datum *) var,
815                                                                                          var->default_val);
816                                                 }
817                                         }
818                                 }
819                                 break;
820
821                         case PLPGSQL_DTYPE_REC:
822                                 {
823                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
824
825                                         if (rec->freetup)
826                                         {
827                                                 heap_freetuple(rec->tup);
828                                                 FreeTupleDesc(rec->tupdesc);
829                                                 rec->freetup = false;
830                                         }
831
832                                         rec->tup = NULL;
833                                         rec->tupdesc = NULL;
834                                 }
835                                 break;
836
837                         case PLPGSQL_DTYPE_RECFIELD:
838                         case PLPGSQL_DTYPE_ARRAYELEM:
839                                 break;
840
841                         default:
842                                 elog(ERROR, "unrecognized dtype: %d",
843                                          estate->datums[n]->dtype);
844                 }
845         }
846
847         if (block->exceptions)
848         {
849                 /*
850                  * Execute the statements in the block's body inside a sub-transaction
851                  */
852                 MemoryContext oldcontext = CurrentMemoryContext;
853                 ResourceOwner oldowner = CurrentResourceOwner;
854
855                 BeginInternalSubTransaction(NULL);
856                 /* Want to run statements inside function's memory context */
857                 MemoryContextSwitchTo(oldcontext);
858
859                 PG_TRY();
860                 {
861                         rc = exec_stmts(estate, block->body);
862
863                         /* Commit the inner transaction, return to outer xact context */
864                         ReleaseCurrentSubTransaction();
865                         MemoryContextSwitchTo(oldcontext);
866                         CurrentResourceOwner = oldowner;
867
868                         /*
869                          * AtEOSubXact_SPI() should not have popped any SPI context, but
870                          * just in case it did, make sure we remain connected.
871                          */
872                         SPI_restore_connection();
873                 }
874                 PG_CATCH();
875                 {
876                         ErrorData  *edata;
877                         ListCell   *e;
878
879                         /* Save error info */
880                         MemoryContextSwitchTo(oldcontext);
881                         edata = CopyErrorData();
882                         FlushErrorState();
883
884                         /* Abort the inner transaction */
885                         RollbackAndReleaseCurrentSubTransaction();
886                         MemoryContextSwitchTo(oldcontext);
887                         CurrentResourceOwner = oldowner;
888
889                         /*
890                          * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
891                          * will have left us in a disconnected state.  We need this hack
892                          * to return to connected state.
893                          */
894                         SPI_restore_connection();
895
896                         /* Look for a matching exception handler */
897                         foreach(e, block->exceptions->exc_list)
898                         {
899                                 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
900
901                                 if (exception_matches_conditions(edata, exception->conditions))
902                                 {
903                                         /*
904                                          * Initialize the magic SQLSTATE and SQLERRM variables for
905                                          * the exception block. We needn't do this until we have
906                                          * found a matching exception.
907                                          */
908                                         PLpgSQL_var *state_var;
909                                         PLpgSQL_var *errm_var;
910
911                                         state_var = (PLpgSQL_var *)
912                                                 estate->datums[block->exceptions->sqlstate_varno];
913                                         state_var->value = DirectFunctionCall1(textin,
914                                            CStringGetDatum(unpack_sql_state(edata->sqlerrcode)));
915                                         state_var->freeval = true;
916                                         state_var->isnull = false;
917
918                                         errm_var = (PLpgSQL_var *)
919                                                 estate->datums[block->exceptions->sqlerrm_varno];
920                                         errm_var->value = DirectFunctionCall1(textin,
921                                                                                         CStringGetDatum(edata->message));
922                                         errm_var->freeval = true;
923                                         errm_var->isnull = false;
924
925                                         rc = exec_stmts(estate, exception->action);
926
927                                         free_var(state_var);
928                                         free_var(errm_var);
929                                         break;
930                                 }
931                         }
932
933                         /* If no match found, re-throw the error */
934                         if (e == NULL)
935                                 ReThrowError(edata);
936                         else
937                                 FreeErrorData(edata);
938                 }
939                 PG_END_TRY();
940         }
941         else
942         {
943                 /*
944                  * Just execute the statements in the block's body
945                  */
946                 rc = exec_stmts(estate, block->body);
947         }
948
949         /*
950          * Handle the return code.
951          */
952         switch (rc)
953         {
954                 case PLPGSQL_RC_OK:
955                 case PLPGSQL_RC_CONTINUE:
956                 case PLPGSQL_RC_RETURN:
957                         return rc;
958
959                 case PLPGSQL_RC_EXIT:
960                         if (estate->exitlabel == NULL)
961                                 return PLPGSQL_RC_OK;
962                         if (block->label == NULL)
963                                 return PLPGSQL_RC_EXIT;
964                         if (strcmp(block->label, estate->exitlabel))
965                                 return PLPGSQL_RC_EXIT;
966                         estate->exitlabel = NULL;
967                         return PLPGSQL_RC_OK;
968
969                 default:
970                         elog(ERROR, "unrecognized rc: %d", rc);
971         }
972
973         return PLPGSQL_RC_OK;
974 }
975
976
977 /* ----------
978  * exec_stmts                   Iterate over a list of statements
979  *                              as long as their return code is OK
980  * ----------
981  */
982 static int
983 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
984 {
985         ListCell   *s;
986
987         if (stmts == NIL)
988         {
989                 /*
990                  * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
991                  * statement.  This prevents hangup in a tight loop if, for instance,
992                  * there is a LOOP construct with an empty body.
993                  */
994                 CHECK_FOR_INTERRUPTS();
995                 return PLPGSQL_RC_OK;
996         }
997
998         foreach(s, stmts)
999         {
1000                 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1001                 int                     rc = exec_stmt(estate, stmt);
1002
1003                 if (rc != PLPGSQL_RC_OK)
1004                         return rc;
1005         }
1006
1007         return PLPGSQL_RC_OK;
1008 }
1009
1010
1011 /* ----------
1012  * exec_stmt                    Distribute one statement to the statements
1013  *                              type specific execution function.
1014  * ----------
1015  */
1016 static int
1017 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1018 {
1019         PLpgSQL_stmt *save_estmt;
1020         int                     rc = -1;
1021
1022         save_estmt = estate->err_stmt;
1023         estate->err_stmt = stmt;
1024
1025         CHECK_FOR_INTERRUPTS();
1026
1027         switch (stmt->cmd_type)
1028         {
1029                 case PLPGSQL_STMT_BLOCK:
1030                         rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1031                         break;
1032
1033                 case PLPGSQL_STMT_ASSIGN:
1034                         rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1035                         break;
1036
1037                 case PLPGSQL_STMT_PERFORM:
1038                         rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1039                         break;
1040
1041                 case PLPGSQL_STMT_GETDIAG:
1042                         rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1043                         break;
1044
1045                 case PLPGSQL_STMT_IF:
1046                         rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1047                         break;
1048
1049                 case PLPGSQL_STMT_LOOP:
1050                         rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1051                         break;
1052
1053                 case PLPGSQL_STMT_WHILE:
1054                         rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1055                         break;
1056
1057                 case PLPGSQL_STMT_FORI:
1058                         rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1059                         break;
1060
1061                 case PLPGSQL_STMT_FORS:
1062                         rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1063                         break;
1064
1065                 case PLPGSQL_STMT_SELECT:
1066                         rc = exec_stmt_select(estate, (PLpgSQL_stmt_select *) stmt);
1067                         break;
1068
1069                 case PLPGSQL_STMT_EXIT:
1070                         rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1071                         break;
1072
1073                 case PLPGSQL_STMT_RETURN:
1074                         rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1075                         break;
1076
1077                 case PLPGSQL_STMT_RETURN_NEXT:
1078                         rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1079                         break;
1080
1081                 case PLPGSQL_STMT_RAISE:
1082                         rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1083                         break;
1084
1085                 case PLPGSQL_STMT_EXECSQL:
1086                         rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1087                         break;
1088
1089                 case PLPGSQL_STMT_DYNEXECUTE:
1090                         rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1091                         break;
1092
1093                 case PLPGSQL_STMT_DYNFORS:
1094                         rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1095                         break;
1096
1097                 case PLPGSQL_STMT_OPEN:
1098                         rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1099                         break;
1100
1101                 case PLPGSQL_STMT_FETCH:
1102                         rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1103                         break;
1104
1105                 case PLPGSQL_STMT_CLOSE:
1106                         rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1107                         break;
1108
1109                 default:
1110                         estate->err_stmt = save_estmt;
1111                         elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1112         }
1113
1114         estate->err_stmt = save_estmt;
1115
1116         return rc;
1117 }
1118
1119
1120 /* ----------
1121  * exec_stmt_assign                     Evaluate an expression and
1122  *                                      put the result into a variable.
1123  * ----------
1124  */
1125 static int
1126 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1127 {
1128         Assert(stmt->varno >= 0);
1129
1130         exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1131
1132         return PLPGSQL_RC_OK;
1133 }
1134
1135 /* ----------
1136  * exec_stmt_perform            Evaluate query and discard result (but set
1137  *                                                      FOUND depending on whether at least one row
1138  *                                                      was returned).
1139  * ----------
1140  */
1141 static int
1142 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1143 {
1144         PLpgSQL_expr *expr = stmt->expr;
1145
1146         (void) exec_run_select(estate, expr, 0, NULL);
1147         exec_set_found(estate, (estate->eval_processed != 0));
1148         exec_eval_cleanup(estate);
1149
1150         return PLPGSQL_RC_OK;
1151 }
1152
1153 /* ----------
1154  * exec_stmt_getdiag                                    Put internal PG information into
1155  *                                                                              specified variables.
1156  * ----------
1157  */
1158 static int
1159 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1160 {
1161         ListCell   *lc;
1162
1163         foreach(lc, stmt->diag_items)
1164         {
1165                 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1166                 PLpgSQL_datum *var;
1167                 bool            isnull = false;
1168
1169                 if (diag_item->target <= 0)
1170                         continue;
1171
1172                 var = estate->datums[diag_item->target];
1173
1174                 if (var == NULL)
1175                         continue;
1176
1177                 switch (diag_item->kind)
1178                 {
1179                         case PLPGSQL_GETDIAG_ROW_COUNT:
1180
1181                                 exec_assign_value(estate, var,
1182                                                                   UInt32GetDatum(estate->eval_processed),
1183                                                                   INT4OID, &isnull);
1184                                 break;
1185
1186                         case PLPGSQL_GETDIAG_RESULT_OID:
1187
1188                                 exec_assign_value(estate, var,
1189                                                                   ObjectIdGetDatum(estate->eval_lastoid),
1190                                                                   OIDOID, &isnull);
1191                                 break;
1192
1193                         default:
1194                                 elog(ERROR, "unrecognized attribute request: %d",
1195                                          diag_item->kind);
1196                 }
1197         }
1198
1199         return PLPGSQL_RC_OK;
1200 }
1201
1202 /* ----------
1203  * exec_stmt_if                         Evaluate a bool expression and
1204  *                                      execute the true or false body
1205  *                                      conditionally.
1206  * ----------
1207  */
1208 static int
1209 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1210 {
1211         bool            value;
1212         bool            isnull;
1213
1214         value = exec_eval_boolean(estate, stmt->cond, &isnull);
1215         exec_eval_cleanup(estate);
1216
1217         if (!isnull && value)
1218         {
1219                 if (stmt->true_body != NIL)
1220                         return exec_stmts(estate, stmt->true_body);
1221         }
1222         else
1223         {
1224                 if (stmt->false_body != NIL)
1225                         return exec_stmts(estate, stmt->false_body);
1226         }
1227
1228         return PLPGSQL_RC_OK;
1229 }
1230
1231
1232 /* ----------
1233  * exec_stmt_loop                       Loop over statements until
1234  *                                      an exit occurs.
1235  * ----------
1236  */
1237 static int
1238 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1239 {
1240         for (;;)
1241         {
1242                 int                     rc = exec_stmts(estate, stmt->body);
1243
1244                 switch (rc)
1245                 {
1246                         case PLPGSQL_RC_OK:
1247                                 break;
1248
1249                         case PLPGSQL_RC_EXIT:
1250                                 if (estate->exitlabel == NULL)
1251                                         return PLPGSQL_RC_OK;
1252                                 if (stmt->label == NULL)
1253                                         return PLPGSQL_RC_EXIT;
1254                                 if (strcmp(stmt->label, estate->exitlabel) != 0)
1255                                         return PLPGSQL_RC_EXIT;
1256                                 estate->exitlabel = NULL;
1257                                 return PLPGSQL_RC_OK;
1258
1259                         case PLPGSQL_RC_CONTINUE:
1260                                 if (estate->exitlabel == NULL)
1261                                         /* anonymous continue, so re-run the loop */
1262                                         break;
1263                                 else if (stmt->label != NULL &&
1264                                                  strcmp(stmt->label, estate->exitlabel) == 0)
1265                                         /* label matches named continue, so re-run loop */
1266                                         estate->exitlabel = NULL;
1267                                 else
1268                                         /* label doesn't match named continue, so propagate upward */
1269                                         return PLPGSQL_RC_CONTINUE;
1270                                 break;
1271
1272                         case PLPGSQL_RC_RETURN:
1273                                 return PLPGSQL_RC_RETURN;
1274
1275                         default:
1276                                 elog(ERROR, "unrecognized rc: %d", rc);
1277                 }
1278         }
1279
1280         return PLPGSQL_RC_OK;
1281 }
1282
1283
1284 /* ----------
1285  * exec_stmt_while                      Loop over statements as long
1286  *                                      as an expression evaluates to
1287  *                                      true or an exit occurs.
1288  * ----------
1289  */
1290 static int
1291 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1292 {
1293         for (;;)
1294         {
1295                 int                     rc;
1296                 bool            value;
1297                 bool            isnull;
1298
1299                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1300                 exec_eval_cleanup(estate);
1301
1302                 if (isnull || !value)
1303                         break;
1304
1305                 rc = exec_stmts(estate, stmt->body);
1306
1307                 switch (rc)
1308                 {
1309                         case PLPGSQL_RC_OK:
1310                                 break;
1311
1312                         case PLPGSQL_RC_EXIT:
1313                                 if (estate->exitlabel == NULL)
1314                                         return PLPGSQL_RC_OK;
1315                                 if (stmt->label == NULL)
1316                                         return PLPGSQL_RC_EXIT;
1317                                 if (strcmp(stmt->label, estate->exitlabel))
1318                                         return PLPGSQL_RC_EXIT;
1319                                 estate->exitlabel = NULL;
1320                                 return PLPGSQL_RC_OK;
1321
1322                         case PLPGSQL_RC_CONTINUE:
1323                                 if (estate->exitlabel == NULL)
1324                                         /* anonymous continue, so re-run loop */
1325                                         break;
1326                                 else if (stmt->label != NULL &&
1327                                                  strcmp(stmt->label, estate->exitlabel) == 0)
1328                                         /* label matches named continue, so re-run loop */
1329                                         estate->exitlabel = NULL;
1330                                 else
1331                                         /* label doesn't match named continue, propagate upward */
1332                                         return PLPGSQL_RC_CONTINUE;
1333                                 break;
1334
1335                         case PLPGSQL_RC_RETURN:
1336                                 return PLPGSQL_RC_RETURN;
1337
1338                         default:
1339                                 elog(ERROR, "unrecognized rc: %d", rc);
1340                 }
1341         }
1342
1343         return PLPGSQL_RC_OK;
1344 }
1345
1346
1347 /* ----------
1348  * exec_stmt_fori                       Iterate an integer variable
1349  *                                      from a lower to an upper value.
1350  *                                      Loop can be left with exit.
1351  * ----------
1352  */
1353 static int
1354 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1355 {
1356         PLpgSQL_var *var;
1357         Datum           value;
1358         Oid                     valtype;
1359         bool            isnull;
1360         bool            found = false;
1361         int                     rc = PLPGSQL_RC_OK;
1362
1363         var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1364
1365         /*
1366          * Get the value of the lower bound into the loop var
1367          */
1368         value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1369         value = exec_cast_value(value, valtype, var->datatype->typoid,
1370                                                         &(var->datatype->typinput),
1371                                                         var->datatype->typioparam,
1372                                                         var->datatype->atttypmod, isnull);
1373         if (isnull)
1374                 ereport(ERROR,
1375                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1376                                  errmsg("lower bound of FOR loop cannot be NULL")));
1377         var->value = value;
1378         var->isnull = false;
1379         exec_eval_cleanup(estate);
1380
1381         /*
1382          * Get the value of the upper bound
1383          */
1384         value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1385         value = exec_cast_value(value, valtype, var->datatype->typoid,
1386                                                         &(var->datatype->typinput),
1387                                                         var->datatype->typioparam,
1388                                                         var->datatype->atttypmod, isnull);
1389         if (isnull)
1390                 ereport(ERROR,
1391                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1392                                  errmsg("upper bound of FOR loop cannot be NULL")));
1393         exec_eval_cleanup(estate);
1394
1395         /*
1396          * Now do the loop
1397          */
1398         for (;;)
1399         {
1400                 /*
1401                  * Check bounds
1402                  */
1403                 if (stmt->reverse)
1404                 {
1405                         if ((int4) (var->value) < (int4) value)
1406                                 break;
1407                 }
1408                 else
1409                 {
1410                         if ((int4) (var->value) > (int4) value)
1411                                 break;
1412                 }
1413
1414                 found = true;                   /* looped at least once */
1415
1416                 /*
1417                  * Execute the statements
1418                  */
1419                 rc = exec_stmts(estate, stmt->body);
1420
1421                 if (rc == PLPGSQL_RC_RETURN)
1422                         break;                          /* return from function */
1423                 else if (rc == PLPGSQL_RC_EXIT)
1424                 {
1425                         if (estate->exitlabel == NULL)
1426                                 /* unlabelled exit, finish the current loop */
1427                                 rc = PLPGSQL_RC_OK;
1428                         else if (stmt->label != NULL &&
1429                                          strcmp(stmt->label, estate->exitlabel) == 0)
1430                         {
1431                                 /* labelled exit, matches the current stmt's label */
1432                                 estate->exitlabel = NULL;
1433                                 rc = PLPGSQL_RC_OK;
1434                         }
1435
1436                         /*
1437                          * otherwise, this is a labelled exit that does not match the
1438                          * current statement's label, if any: return RC_EXIT so that the
1439                          * EXIT continues to propagate up the stack.
1440                          */
1441
1442                         break;
1443                 }
1444                 else if (rc == PLPGSQL_RC_CONTINUE)
1445                 {
1446                         if (estate->exitlabel == NULL)
1447                                 /* anonymous continue, so re-run the current loop */
1448                                 rc = PLPGSQL_RC_OK;
1449                         else if (stmt->label != NULL &&
1450                                          strcmp(stmt->label, estate->exitlabel) == 0)
1451                         {
1452                                 /* label matches named continue, so re-run loop */
1453                                 estate->exitlabel = NULL;
1454                                 rc = PLPGSQL_RC_OK;
1455                         }
1456                         else
1457                         {
1458                                 /*
1459                                  * otherwise, this is a named continue that does not match the
1460                                  * current statement's label, if any: return RC_CONTINUE so
1461                                  * that the CONTINUE will propagate up the stack.
1462                                  */
1463                                 break;
1464                         }
1465                 }
1466
1467                 /*
1468                  * Increase/decrease loop var
1469                  */
1470                 if (stmt->reverse)
1471                         var->value--;
1472                 else
1473                         var->value++;
1474         }
1475
1476         /*
1477          * Set the FOUND variable to indicate the result of executing the loop
1478          * (namely, whether we looped one or more times). This must be set here so
1479          * that it does not interfere with the value of the FOUND variable inside
1480          * the loop processing itself.
1481          */
1482         exec_set_found(estate, found);
1483
1484         return rc;
1485 }
1486
1487
1488 /* ----------
1489  * exec_stmt_fors                       Execute a query, assign each
1490  *                                      tuple to a record or row and
1491  *                                      execute a group of statements
1492  *                                      for it.
1493  * ----------
1494  */
1495 static int
1496 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1497 {
1498         PLpgSQL_rec *rec = NULL;
1499         PLpgSQL_row *row = NULL;
1500         SPITupleTable *tuptab;
1501         Portal          portal;
1502         bool            found = false;
1503         int                     rc = PLPGSQL_RC_OK;
1504         int                     i;
1505         int                     n;
1506
1507         /*
1508          * Determine if we assign to a record or a row
1509          */
1510         if (stmt->rec != NULL)
1511                 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1512         else if (stmt->row != NULL)
1513                 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1514         else
1515                 elog(ERROR, "unsupported target");
1516
1517         /*
1518          * Open the implicit cursor for the statement and fetch the initial 10
1519          * rows.
1520          */
1521         exec_run_select(estate, stmt->query, 0, &portal);
1522
1523         SPI_cursor_fetch(portal, true, 10);
1524         tuptab = SPI_tuptable;
1525         n = SPI_processed;
1526
1527         /*
1528          * If the query didn't return any rows, set the target to NULL and return
1529          * with FOUND = false.
1530          */
1531         if (n == 0)
1532                 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1533         else
1534                 found = true;                   /* processed at least one tuple */
1535
1536         /*
1537          * Now do the loop
1538          */
1539         while (n > 0)
1540         {
1541                 for (i = 0; i < n; i++)
1542                 {
1543                         /*
1544                          * Assign the tuple to the target
1545                          */
1546                         exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
1547
1548                         /*
1549                          * Execute the statements
1550                          */
1551                         rc = exec_stmts(estate, stmt->body);
1552                         if (rc != PLPGSQL_RC_OK)
1553                         {
1554                                 if (rc == PLPGSQL_RC_EXIT)
1555                                 {
1556                                         if (estate->exitlabel == NULL)
1557                                                 /* unlabelled exit, finish the current loop */
1558                                                 rc = PLPGSQL_RC_OK;
1559                                         else if (stmt->label != NULL &&
1560                                                          strcmp(stmt->label, estate->exitlabel) == 0)
1561                                         {
1562                                                 /* labelled exit, matches the current stmt's label */
1563                                                 estate->exitlabel = NULL;
1564                                                 rc = PLPGSQL_RC_OK;
1565                                         }
1566
1567                                         /*
1568                                          * otherwise, we processed a labelled exit that does not
1569                                          * match the current statement's label, if any: return
1570                                          * RC_EXIT so that the EXIT continues to recurse upward.
1571                                          */
1572                                 }
1573                                 else if (rc == PLPGSQL_RC_CONTINUE)
1574                                 {
1575                                         if (estate->exitlabel == NULL)
1576                                         {
1577                                                 /* anonymous continue, so re-run the current loop */
1578                                                 rc = PLPGSQL_RC_OK;
1579                                                 continue;
1580                                         }
1581                                         else if (stmt->label != NULL &&
1582                                                          strcmp(stmt->label, estate->exitlabel) == 0)
1583                                         {
1584                                                 /* label matches named continue, so re-run loop */
1585                                                 rc = PLPGSQL_RC_OK;
1586                                                 estate->exitlabel = NULL;
1587                                                 continue;
1588                                         }
1589
1590                                         /*
1591                                          * otherwise, we processed a named continue that does not
1592                                          * match the current statement's label, if any: return
1593                                          * RC_CONTINUE so that the CONTINUE will propagate up the
1594                                          * stack.
1595                                          */
1596                                 }
1597
1598                                 /*
1599                                  * We're aborting the loop, so cleanup and set FOUND. (This
1600                                  * code should match the code after the loop.)
1601                                  */
1602                                 SPI_freetuptable(tuptab);
1603                                 SPI_cursor_close(portal);
1604                                 exec_set_found(estate, found);
1605
1606                                 return rc;
1607                         }
1608                 }
1609
1610                 SPI_freetuptable(tuptab);
1611
1612                 /*
1613                  * Fetch the next 50 tuples
1614                  */
1615                 SPI_cursor_fetch(portal, true, 50);
1616                 n = SPI_processed;
1617                 tuptab = SPI_tuptable;
1618         }
1619
1620         /*
1621          * Release last group of tuples
1622          */
1623         SPI_freetuptable(tuptab);
1624
1625         /*
1626          * Close the implicit cursor
1627          */
1628         SPI_cursor_close(portal);
1629
1630         /*
1631          * Set the FOUND variable to indicate the result of executing the loop
1632          * (namely, whether we looped one or more times). This must be set here so
1633          * that it does not interfere with the value of the FOUND variable inside
1634          * the loop processing itself.
1635          */
1636         exec_set_found(estate, found);
1637
1638         return rc;
1639 }
1640
1641
1642 /* ----------
1643  * exec_stmt_select                     Run a query and assign the first
1644  *                                      row to a record or rowtype.
1645  * ----------
1646  */
1647 static int
1648 exec_stmt_select(PLpgSQL_execstate *estate, PLpgSQL_stmt_select *stmt)
1649 {
1650         PLpgSQL_rec *rec = NULL;
1651         PLpgSQL_row *row = NULL;
1652         SPITupleTable *tuptab;
1653         uint32          n;
1654
1655         /*
1656          * Initialize the global found variable to false
1657          */
1658         exec_set_found(estate, false);
1659
1660         /*
1661          * Determine if we assign to a record or a row
1662          */
1663         if (stmt->rec != NULL)
1664                 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1665         else if (stmt->row != NULL)
1666                 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1667         else
1668                 elog(ERROR, "unsupported target");
1669
1670         /*
1671          * Run the query
1672          */
1673         exec_run_select(estate, stmt->query, 1, NULL);
1674         tuptab = estate->eval_tuptable;
1675         n = estate->eval_processed;
1676
1677         /*
1678          * If the query didn't return any rows, set the target to NULL and return.
1679          */
1680         if (n == 0)
1681         {
1682                 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1683                 exec_eval_cleanup(estate);
1684                 return PLPGSQL_RC_OK;
1685         }
1686
1687         /*
1688          * Put the result into the target and set found to true
1689          */
1690         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
1691         exec_set_found(estate, true);
1692
1693         exec_eval_cleanup(estate);
1694
1695         return PLPGSQL_RC_OK;
1696 }
1697
1698
1699 /* ----------
1700  * exec_stmt_exit                       Implements EXIT and CONTINUE
1701  *
1702  * This begins the process of exiting / restarting a loop.
1703  * ----------
1704  */
1705 static int
1706 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1707 {
1708         /*
1709          * If the exit / continue has a condition, evaluate it
1710          */
1711         if (stmt->cond != NULL)
1712         {
1713                 bool            value;
1714                 bool            isnull;
1715
1716                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1717                 exec_eval_cleanup(estate);
1718                 if (isnull || value == false)
1719                         return PLPGSQL_RC_OK;
1720         }
1721
1722         estate->exitlabel = stmt->label;
1723         if (stmt->is_exit)
1724                 return PLPGSQL_RC_EXIT;
1725         else
1726                 return PLPGSQL_RC_CONTINUE;
1727 }
1728
1729
1730 /* ----------
1731  * exec_stmt_return                     Evaluate an expression and start
1732  *                                      returning from the function.
1733  * ----------
1734  */
1735 static int
1736 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1737 {
1738         /*
1739          * If processing a set-returning PL/PgSQL function, the final RETURN
1740          * indicates that the function is finished producing tuples.  The rest of
1741          * the work will be done at the top level.
1742          */
1743         if (estate->retisset)
1744                 return PLPGSQL_RC_RETURN;
1745
1746         /* initialize for null result (possibly a tuple) */
1747         estate->retval = (Datum) 0;
1748         estate->rettupdesc = NULL;
1749         estate->retisnull = true;
1750
1751         if (stmt->retvarno >= 0)
1752         {
1753                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1754
1755                 switch (retvar->dtype)
1756                 {
1757                         case PLPGSQL_DTYPE_VAR:
1758                                 {
1759                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1760
1761                                         estate->retval = var->value;
1762                                         estate->retisnull = var->isnull;
1763                                         estate->rettype = var->datatype->typoid;
1764                                 }
1765                                 break;
1766
1767                         case PLPGSQL_DTYPE_REC:
1768                                 {
1769                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1770
1771                                         if (HeapTupleIsValid(rec->tup))
1772                                         {
1773                                                 estate->retval = (Datum) rec->tup;
1774                                                 estate->rettupdesc = rec->tupdesc;
1775                                                 estate->retisnull = false;
1776                                         }
1777                                 }
1778                                 break;
1779
1780                         case PLPGSQL_DTYPE_ROW:
1781                                 {
1782                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1783
1784                                         Assert(row->rowtupdesc);
1785                                         estate->retval = (Datum) make_tuple_from_row(estate, row,
1786                                                                                                                         row->rowtupdesc);
1787                                         if (estate->retval == (Datum) NULL) /* should not happen */
1788                                                 elog(ERROR, "row not compatible with its own tupdesc");
1789                                         estate->rettupdesc = row->rowtupdesc;
1790                                         estate->retisnull = false;
1791                                 }
1792                                 break;
1793
1794                         default:
1795                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1796                 }
1797
1798                 return PLPGSQL_RC_RETURN;
1799         }
1800
1801         if (stmt->expr != NULL)
1802         {
1803                 if (estate->retistuple)
1804                 {
1805                         exec_run_select(estate, stmt->expr, 1, NULL);
1806                         if (estate->eval_processed > 0)
1807                         {
1808                                 estate->retval = (Datum) estate->eval_tuptable->vals[0];
1809                                 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1810                                 estate->retisnull = false;
1811                         }
1812                 }
1813                 else
1814                 {
1815                         /* Normal case for scalar results */
1816                         estate->retval = exec_eval_expr(estate, stmt->expr,
1817                                                                                         &(estate->retisnull),
1818                                                                                         &(estate->rettype));
1819                 }
1820
1821                 return PLPGSQL_RC_RETURN;
1822         }
1823
1824         /*
1825          * Special hack for function returning VOID: instead of NULL, return a
1826          * non-null VOID value.  This is of dubious importance but is kept for
1827          * backwards compatibility.  Note that the only other way to get here is
1828          * to have written "RETURN NULL" in a function returning tuple.
1829          */
1830         if (estate->fn_rettype == VOIDOID)
1831         {
1832                 estate->retval = (Datum) 0;
1833                 estate->retisnull = false;
1834                 estate->rettype = VOIDOID;
1835         }
1836
1837         return PLPGSQL_RC_RETURN;
1838 }
1839
1840 /* ----------
1841  * exec_stmt_return_next                Evaluate an expression and add it to the
1842  *                                                              list of tuples returned by the current
1843  *                                                              SRF.
1844  * ----------
1845  */
1846 static int
1847 exec_stmt_return_next(PLpgSQL_execstate *estate,
1848                                           PLpgSQL_stmt_return_next *stmt)
1849 {
1850         TupleDesc       tupdesc;
1851         int                     natts;
1852         HeapTuple       tuple;
1853         bool            free_tuple = false;
1854
1855         if (!estate->retisset)
1856                 ereport(ERROR,
1857                                 (errcode(ERRCODE_SYNTAX_ERROR),
1858                                  errmsg("cannot use RETURN NEXT in a non-SETOF function")));
1859
1860         if (estate->tuple_store == NULL)
1861                 exec_init_tuple_store(estate);
1862
1863         /* rettupdesc will be filled by exec_init_tuple_store */
1864         tupdesc = estate->rettupdesc;
1865         natts = tupdesc->natts;
1866
1867         if (stmt->retvarno >= 0)
1868         {
1869                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1870
1871                 switch (retvar->dtype)
1872                 {
1873                         case PLPGSQL_DTYPE_VAR:
1874                                 {
1875                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1876                                         Datum           retval = var->value;
1877                                         bool            isNull = var->isnull;
1878
1879                                         if (natts != 1)
1880                                                 ereport(ERROR,
1881                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1882                                                 errmsg("wrong result type supplied in RETURN NEXT")));
1883
1884                                         /* coerce type if needed */
1885                                         retval = exec_simple_cast_value(retval,
1886                                                                                                         var->datatype->typoid,
1887                                                                                                  tupdesc->attrs[0]->atttypid,
1888                                                                                                 tupdesc->attrs[0]->atttypmod,
1889                                                                                                         isNull);
1890
1891                                         tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1892
1893                                         free_tuple = true;
1894                                 }
1895                                 break;
1896
1897                         case PLPGSQL_DTYPE_REC:
1898                                 {
1899                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1900
1901                                         if (!HeapTupleIsValid(rec->tup))
1902                                                 ereport(ERROR,
1903                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1904                                                    errmsg("record \"%s\" is not assigned yet",
1905                                                                   rec->refname),
1906                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
1907                                         if (!compatible_tupdesc(tupdesc, rec->tupdesc))
1908                                                 ereport(ERROR,
1909                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1910                                                 errmsg("wrong record type supplied in RETURN NEXT")));
1911                                         tuple = rec->tup;
1912                                 }
1913                                 break;
1914
1915                         case PLPGSQL_DTYPE_ROW:
1916                                 {
1917                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1918
1919                                         tuple = make_tuple_from_row(estate, row, tupdesc);
1920                                         if (tuple == NULL)
1921                                                 ereport(ERROR,
1922                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1923                                                 errmsg("wrong record type supplied in RETURN NEXT")));
1924                                         free_tuple = true;
1925                                 }
1926                                 break;
1927
1928                         default:
1929                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1930                                 tuple = NULL;   /* keep compiler quiet */
1931                                 break;
1932                 }
1933         }
1934         else if (stmt->expr)
1935         {
1936                 Datum           retval;
1937                 bool            isNull;
1938                 Oid                     rettype;
1939
1940                 if (natts != 1)
1941                         ereport(ERROR,
1942                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1943                                          errmsg("wrong result type supplied in RETURN NEXT")));
1944
1945                 retval = exec_eval_expr(estate,
1946                                                                 stmt->expr,
1947                                                                 &isNull,
1948                                                                 &rettype);
1949
1950                 /* coerce type if needed */
1951                 retval = exec_simple_cast_value(retval,
1952                                                                                 rettype,
1953                                                                                 tupdesc->attrs[0]->atttypid,
1954                                                                                 tupdesc->attrs[0]->atttypmod,
1955                                                                                 isNull);
1956
1957                 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1958
1959                 free_tuple = true;
1960
1961                 exec_eval_cleanup(estate);
1962         }
1963         else
1964         {
1965                 ereport(ERROR,
1966                                 (errcode(ERRCODE_SYNTAX_ERROR),
1967                                  errmsg("RETURN NEXT must have a parameter")));
1968                 tuple = NULL;                   /* keep compiler quiet */
1969         }
1970
1971         if (HeapTupleIsValid(tuple))
1972         {
1973                 MemoryContext oldcxt;
1974
1975                 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1976                 tuplestore_puttuple(estate->tuple_store, tuple);
1977                 MemoryContextSwitchTo(oldcxt);
1978
1979                 if (free_tuple)
1980                         heap_freetuple(tuple);
1981         }
1982
1983         return PLPGSQL_RC_OK;
1984 }
1985
1986 static void
1987 exec_init_tuple_store(PLpgSQL_execstate *estate)
1988 {
1989         ReturnSetInfo *rsi = estate->rsi;
1990         MemoryContext oldcxt;
1991
1992         /*
1993          * Check caller can handle a set result in the way we want
1994          */
1995         if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1996                 (rsi->allowedModes & SFRM_Materialize) == 0 ||
1997                 rsi->expectedDesc == NULL)
1998                 ereport(ERROR,
1999                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2000                                  errmsg("set-valued function called in context that cannot accept a set")));
2001
2002         estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2003
2004         oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2005         estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
2006         MemoryContextSwitchTo(oldcxt);
2007
2008         estate->rettupdesc = rsi->expectedDesc;
2009 }
2010
2011 /* ----------
2012  * exec_stmt_raise                      Build a message and throw it with elog()
2013  * ----------
2014  */
2015 static int
2016 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2017 {
2018         char       *cp;
2019         PLpgSQL_dstring ds;
2020         ListCell   *current_param;
2021
2022         plpgsql_dstring_init(&ds);
2023         current_param = list_head(stmt->params);
2024
2025         for (cp = stmt->message; *cp; cp++)
2026         {
2027                 /*
2028                  * Occurrences of a single % are replaced by the next parameter's
2029                  * external representation. Double %'s are converted to one %.
2030                  */
2031                 if (cp[0] == '%')
2032                 {
2033                         Oid                     paramtypeid;
2034                         Datum           paramvalue;
2035                         bool            paramisnull;
2036                         char       *extval;
2037
2038                         if (cp[1] == '%')
2039                         {
2040                                 plpgsql_dstring_append_char(&ds, cp[1]);
2041                                 cp++;
2042                                 continue;
2043                         }
2044
2045                         if (current_param == NULL)
2046                                 ereport(ERROR,
2047                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2048                                                  errmsg("too few parameters specified for RAISE")));
2049
2050                         paramvalue = exec_eval_expr(estate,
2051                                                                           (PLpgSQL_expr *) lfirst(current_param),
2052                                                                                 &paramisnull,
2053                                                                                 &paramtypeid);
2054
2055                         if (paramisnull)
2056                                 extval = "<NULL>";
2057                         else
2058                                 extval = convert_value_to_string(paramvalue, paramtypeid);
2059                         plpgsql_dstring_append(&ds, extval);
2060                         current_param = lnext(current_param);
2061                         exec_eval_cleanup(estate);
2062                         continue;
2063                 }
2064
2065                 plpgsql_dstring_append_char(&ds, cp[0]);
2066         }
2067
2068         /*
2069          * If more parameters were specified than were required to process the
2070          * format string, throw an error
2071          */
2072         if (current_param != NULL)
2073                 ereport(ERROR,
2074                                 (errcode(ERRCODE_SYNTAX_ERROR),
2075                                  errmsg("too many parameters specified for RAISE")));
2076
2077         /*
2078          * Throw the error (may or may not come back)
2079          */
2080         estate->err_text = raise_skip_msg;      /* suppress traceback of raise */
2081
2082         ereport(stmt->elog_level,
2083                  ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
2084                   errmsg_internal("%s", plpgsql_dstring_get(&ds))));
2085
2086         estate->err_text = NULL;        /* un-suppress... */
2087
2088         plpgsql_dstring_free(&ds);
2089
2090         return PLPGSQL_RC_OK;
2091 }
2092
2093
2094 /* ----------
2095  * Initialize a mostly empty execution state
2096  * ----------
2097  */
2098 static void
2099 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2100                                          PLpgSQL_function *func,
2101                                          ReturnSetInfo *rsi)
2102 {
2103         estate->retval = (Datum) 0;
2104         estate->retisnull = true;
2105         estate->rettype = InvalidOid;
2106
2107         estate->fn_rettype = func->fn_rettype;
2108         estate->retistuple = func->fn_retistuple;
2109         estate->retisset = func->fn_retset;
2110
2111         estate->readonly_func = func->fn_readonly;
2112
2113         estate->rettupdesc = NULL;
2114         estate->exitlabel = NULL;
2115
2116         estate->tuple_store = NULL;
2117         estate->tuple_store_cxt = NULL;
2118         estate->rsi = rsi;
2119
2120         estate->trig_nargs = 0;
2121         estate->trig_argv = NULL;
2122
2123         estate->found_varno = func->found_varno;
2124         estate->ndatums = func->ndatums;
2125         estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2126         /* caller is expected to fill the datums array */
2127
2128         estate->eval_tuptable = NULL;
2129         estate->eval_processed = 0;
2130         estate->eval_lastoid = InvalidOid;
2131
2132         estate->err_func = func;
2133         estate->err_stmt = NULL;
2134         estate->err_text = NULL;
2135
2136         /*
2137          * Create an EState for evaluation of simple expressions, if there's not
2138          * one already in the current transaction.      The EState is made a child of
2139          * TopTransactionContext so it will have the right lifespan.
2140          */
2141         if (simple_eval_estate == NULL)
2142         {
2143                 MemoryContext oldcontext;
2144
2145                 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
2146                 simple_eval_estate = CreateExecutorState();
2147                 MemoryContextSwitchTo(oldcontext);
2148         }
2149
2150         /*
2151          * Create an expression context for simple expressions. This must be a
2152          * child of simple_eval_estate.
2153          */
2154         estate->eval_econtext = CreateExprContext(simple_eval_estate);
2155 }
2156
2157 /* ----------
2158  * Release temporary memory used by expression/subselect evaluation
2159  *
2160  * NB: the result of the evaluation is no longer valid after this is done,
2161  * unless it is a pass-by-value datatype.
2162  * ----------
2163  */
2164 static void
2165 exec_eval_cleanup(PLpgSQL_execstate *estate)
2166 {
2167         /* Clear result of a full SPI_execute */
2168         if (estate->eval_tuptable != NULL)
2169                 SPI_freetuptable(estate->eval_tuptable);
2170         estate->eval_tuptable = NULL;
2171
2172         /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2173         if (estate->eval_econtext != NULL)
2174                 ResetExprContext(estate->eval_econtext);
2175 }
2176
2177
2178 /* ----------
2179  * Generate a prepared plan
2180  * ----------
2181  */
2182 static void
2183 exec_prepare_plan(PLpgSQL_execstate *estate,
2184                                   PLpgSQL_expr *expr)
2185 {
2186         int                     i;
2187         _SPI_plan  *spi_plan;
2188         void       *plan;
2189         Oid                *argtypes;
2190
2191         /*
2192          * We need a temporary argtypes array to load with data. (The finished
2193          * plan structure will contain a copy of it.)
2194          */
2195         argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2196
2197         for (i = 0; i < expr->nparams; i++)
2198         {
2199                 Datum           paramval;
2200                 bool            paramisnull;
2201
2202                 exec_eval_datum(estate, estate->datums[expr->params[i]],
2203                                                 InvalidOid,
2204                                                 &argtypes[i], &paramval, &paramisnull);
2205         }
2206
2207         /*
2208          * Generate and save the plan
2209          */
2210         plan = SPI_prepare(expr->query, expr->nparams, argtypes);
2211         if (plan == NULL)
2212         {
2213                 /* Some SPI errors deserve specific error messages */
2214                 switch (SPI_result)
2215                 {
2216                         case SPI_ERROR_COPY:
2217                                 ereport(ERROR,
2218                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2219                                                  errmsg("cannot COPY to/from client in PL/pgSQL")));
2220                         case SPI_ERROR_CURSOR:
2221                                 ereport(ERROR,
2222                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2223                                         errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2224                                                  errhint("Use PL/pgSQL's cursor features instead.")));
2225                         case SPI_ERROR_TRANSACTION:
2226                                 ereport(ERROR,
2227                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2228                                                  errmsg("cannot begin/end transactions in PL/pgSQL"),
2229                                                  errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2230                         default:
2231                                 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2232                                          expr->query, SPI_result_code_string(SPI_result));
2233                 }
2234         }
2235         expr->plan = SPI_saveplan(plan);
2236         spi_plan = (_SPI_plan *) expr->plan;
2237         expr->plan_argtypes = spi_plan->argtypes;
2238         expr->expr_simple_expr = NULL;
2239         exec_simple_check_plan(expr);
2240
2241         SPI_freeplan(plan);
2242         pfree(argtypes);
2243 }
2244
2245
2246 /* ----------
2247  * exec_stmt_execsql                    Execute an SQL statement not
2248  *                                      returning any data.
2249  * ----------
2250  */
2251 static int
2252 exec_stmt_execsql(PLpgSQL_execstate *estate,
2253                                   PLpgSQL_stmt_execsql *stmt)
2254 {
2255         int                     i;
2256         Datum      *values;
2257         char       *nulls;
2258         int                     rc;
2259         PLpgSQL_expr *expr = stmt->sqlstmt;
2260
2261         /*
2262          * On the first call for this expression generate the plan
2263          */
2264         if (expr->plan == NULL)
2265                 exec_prepare_plan(estate, expr);
2266
2267         /*
2268          * Now build up the values and nulls arguments for SPI_execute_plan()
2269          */
2270         values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2271         nulls = (char *) palloc(expr->nparams * sizeof(char));
2272
2273         for (i = 0; i < expr->nparams; i++)
2274         {
2275                 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2276                 Oid                     paramtypeid;
2277                 bool            paramisnull;
2278
2279                 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2280                                                 &paramtypeid, &values[i], &paramisnull);
2281                 if (paramisnull)
2282                         nulls[i] = 'n';
2283                 else
2284                         nulls[i] = ' ';
2285         }
2286
2287         /*
2288          * Execute the plan
2289          */
2290         rc = SPI_execute_plan(expr->plan, values, nulls,
2291                                                   estate->readonly_func, 0);
2292         switch (rc)
2293         {
2294                 case SPI_OK_UTILITY:
2295                 case SPI_OK_SELINTO:
2296                         break;
2297
2298                 case SPI_OK_INSERT:
2299                 case SPI_OK_DELETE:
2300                 case SPI_OK_UPDATE:
2301
2302                         /*
2303                          * If the INSERT, DELETE, or UPDATE query affected at least one
2304                          * tuple, set the magic 'FOUND' variable to true. This conforms
2305                          * with the behavior of PL/SQL.
2306                          */
2307                         exec_set_found(estate, (SPI_processed != 0));
2308                         break;
2309
2310                 case SPI_OK_SELECT:
2311                         ereport(ERROR,
2312                                         (errcode(ERRCODE_SYNTAX_ERROR),
2313                                    errmsg("SELECT query has no destination for result data"),
2314                                          errhint("If you want to discard the results, use PERFORM instead.")));
2315
2316                 default:
2317                         elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2318                                  expr->query, SPI_result_code_string(rc));
2319         }
2320
2321         /*
2322          * Release any result tuples from SPI_execute_plan (probably shouldn't be
2323          * any)
2324          */
2325         SPI_freetuptable(SPI_tuptable);
2326
2327         /* Save result info for GET DIAGNOSTICS */
2328         estate->eval_processed = SPI_processed;
2329         estate->eval_lastoid = SPI_lastoid;
2330
2331         pfree(values);
2332         pfree(nulls);
2333
2334         return PLPGSQL_RC_OK;
2335 }
2336
2337
2338 /* ----------
2339  * exec_stmt_dynexecute                 Execute a dynamic SQL query not
2340  *                                      returning any data.
2341  * ----------
2342  */
2343 static int
2344 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2345                                          PLpgSQL_stmt_dynexecute *stmt)
2346 {
2347         Datum           query;
2348         bool            isnull = false;
2349         Oid                     restype;
2350         char       *querystr;
2351         int                     exec_res;
2352         PLpgSQL_rec *rec = NULL;
2353         PLpgSQL_row *row = NULL;
2354
2355         if (stmt->rec != NULL)
2356                 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2357         else if (stmt->row != NULL)
2358                 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2359
2360         /*
2361          * First we evaluate the string expression after the EXECUTE keyword. It's
2362          * result is the querystring we have to execute.
2363          */
2364         query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2365         if (isnull)
2366                 ereport(ERROR,
2367                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2368                                  errmsg("cannot EXECUTE a null querystring")));
2369
2370         /* Get the C-String representation */
2371         querystr = convert_value_to_string(query, restype);
2372
2373         exec_eval_cleanup(estate);
2374
2375         /*
2376          * Call SPI_execute() without preparing a saved plan. The returncode can
2377          * be any standard OK.  Note that while a SELECT is allowed, its results
2378          * will be discarded unless an INTO clause is specified.
2379          */
2380         exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2381
2382         /* Assign to INTO variable */
2383         if (rec || row)
2384         {
2385                 if (exec_res != SPI_OK_SELECT)
2386                         ereport(ERROR,
2387                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2388                                          errmsg("EXECUTE ... INTO is only for SELECT")));
2389                 else
2390                 {
2391                         if (SPI_processed == 0)
2392                                 exec_move_row(estate, rec, row, NULL, SPI_tuptable->tupdesc);
2393                         else
2394                                 exec_move_row(estate, rec, row,
2395                                                           SPI_tuptable->vals[0], SPI_tuptable->tupdesc);
2396                 }
2397         }
2398
2399         switch (exec_res)
2400         {
2401                 case SPI_OK_SELECT:
2402                 case SPI_OK_INSERT:
2403                 case SPI_OK_UPDATE:
2404                 case SPI_OK_DELETE:
2405                 case SPI_OK_UTILITY:
2406                         break;
2407
2408                 case 0:
2409
2410                         /*
2411                          * Also allow a zero return, which implies the querystring
2412                          * contained no commands.
2413                          */
2414                         break;
2415
2416                 case SPI_OK_SELINTO:
2417
2418                         /*
2419                          * We want to disallow SELECT INTO for now, because its behavior
2420                          * is not consistent with SELECT INTO in a normal plpgsql context.
2421                          * (We need to reimplement EXECUTE to parse the string as a
2422                          * plpgsql command, not just feed it to SPI_execute.) However,
2423                          * CREATE AS should be allowed ... and since it produces the same
2424                          * parsetree as SELECT INTO, there's no way to tell the difference
2425                          * except to look at the source text.  Wotta kluge!
2426                          */
2427                         {
2428                                 char       *ptr;
2429
2430                                 for (ptr = querystr; *ptr; ptr++)
2431                                         if (!isspace((unsigned char) *ptr))
2432                                                 break;
2433                                 if (*ptr == 'S' || *ptr == 's')
2434                                         ereport(ERROR,
2435                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2436                                                          errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2437                                 break;
2438                         }
2439
2440                         /* Some SPI errors deserve specific error messages */
2441                 case SPI_ERROR_COPY:
2442                         ereport(ERROR,
2443                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2444                                          errmsg("cannot COPY to/from client in PL/pgSQL")));
2445                 case SPI_ERROR_CURSOR:
2446                         ereport(ERROR,
2447                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2448                                          errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2449                                          errhint("Use PL/pgSQL's cursor features instead.")));
2450                 case SPI_ERROR_TRANSACTION:
2451                         ereport(ERROR,
2452                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2453                                          errmsg("cannot begin/end transactions in PL/pgSQL"),
2454                         errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2455
2456                 default:
2457                         elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2458                                  querystr, SPI_result_code_string(exec_res));
2459                         break;
2460         }
2461
2462         /* Release any result from SPI_execute, as well as the querystring */
2463         SPI_freetuptable(SPI_tuptable);
2464         pfree(querystr);
2465
2466         /* Save result info for GET DIAGNOSTICS */
2467         estate->eval_processed = SPI_processed;
2468         estate->eval_lastoid = SPI_lastoid;
2469
2470         return PLPGSQL_RC_OK;
2471 }
2472
2473
2474 /* ----------
2475  * exec_stmt_dynfors                    Execute a dynamic query, assign each
2476  *                                      tuple to a record or row and
2477  *                                      execute a group of statements
2478  *                                      for it.
2479  * ----------
2480  */
2481 static int
2482 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2483 {
2484         Datum           query;
2485         bool            isnull;
2486         Oid                     restype;
2487         char       *querystr;
2488         PLpgSQL_rec *rec = NULL;
2489         PLpgSQL_row *row = NULL;
2490         SPITupleTable *tuptab;
2491         int                     n;
2492         void       *plan;
2493         Portal          portal;
2494         bool            found = false;
2495
2496         /*
2497          * Determine if we assign to a record or a row
2498          */
2499         if (stmt->rec != NULL)
2500                 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2501         else if (stmt->row != NULL)
2502                 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2503         else
2504                 elog(ERROR, "unsupported target");
2505
2506         /*
2507          * Evaluate the string expression after the EXECUTE keyword. It's result
2508          * is the querystring we have to execute.
2509          */
2510         query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2511         if (isnull)
2512                 ereport(ERROR,
2513                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2514                                  errmsg("cannot EXECUTE a null querystring")));
2515
2516         /* Get the C-String representation */
2517         querystr = convert_value_to_string(query, restype);
2518
2519         exec_eval_cleanup(estate);
2520
2521         /*
2522          * Prepare a plan and open an implicit cursor for the query
2523          */
2524         plan = SPI_prepare(querystr, 0, NULL);
2525         if (plan == NULL)
2526                 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2527                          querystr, SPI_result_code_string(SPI_result));
2528         portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2529                                                          estate->readonly_func);
2530         if (portal == NULL)
2531                 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2532                          querystr, SPI_result_code_string(SPI_result));
2533         pfree(querystr);
2534         SPI_freeplan(plan);
2535
2536         /*
2537          * Fetch the initial 10 tuples
2538          */
2539         SPI_cursor_fetch(portal, true, 10);
2540         tuptab = SPI_tuptable;
2541         n = SPI_processed;
2542
2543         /*
2544          * If the query didn't return any rows, set the target to NULL and return
2545          * with FOUND = false.
2546          */
2547         if (n == 0)
2548                 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2549         else
2550                 found = true;                   /* processed at least one tuple */
2551
2552         /*
2553          * Now do the loop
2554          */
2555         while (n > 0)
2556         {
2557                 int                     i;
2558
2559                 for (i = 0; i < n; i++)
2560                 {
2561                         int                     rc;
2562
2563                         /*
2564                          * Assign the tuple to the target
2565                          */
2566                         exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2567
2568                         /*
2569                          * Execute the statements
2570                          */
2571                         rc = exec_stmts(estate, stmt->body);
2572
2573                         if (rc != PLPGSQL_RC_OK)
2574                         {
2575                                 if (rc == PLPGSQL_RC_EXIT)
2576                                 {
2577                                         if (estate->exitlabel == NULL)
2578                                                 /* unlabelled exit, finish the current loop */
2579                                                 rc = PLPGSQL_RC_OK;
2580                                         else if (stmt->label != NULL &&
2581                                                          strcmp(stmt->label, estate->exitlabel) == 0)
2582                                         {
2583                                                 /* labelled exit, matches the current stmt's label */
2584                                                 estate->exitlabel = NULL;
2585                                                 rc = PLPGSQL_RC_OK;
2586                                         }
2587
2588                                         /*
2589                                          * otherwise, we processed a labelled exit that does not
2590                                          * match the current statement's label, if any: return
2591                                          * RC_EXIT so that the EXIT continues to recurse upward.
2592                                          */
2593                                 }
2594                                 else if (rc == PLPGSQL_RC_CONTINUE)
2595                                 {
2596                                         if (estate->exitlabel == NULL)
2597                                                 /* unlabelled continue, continue the current loop */
2598                                                 continue;
2599                                         else if (stmt->label != NULL &&
2600                                                          strcmp(stmt->label, estate->exitlabel) == 0)
2601                                         {
2602                                                 /* labelled continue, matches the current stmt's label */
2603                                                 estate->exitlabel = NULL;
2604                                                 continue;
2605                                         }
2606
2607                                         /*
2608                                          * otherwise, we process a labelled continue that does not
2609                                          * match the current statement's label, so propagate
2610                                          * RC_CONTINUE upward in the stack.
2611                                          */
2612                                 }
2613
2614                                 /*
2615                                  * We're aborting the loop, so cleanup and set FOUND. (This
2616                                  * code should match the code after the loop.)
2617                                  */
2618                                 SPI_freetuptable(tuptab);
2619                                 SPI_cursor_close(portal);
2620                                 exec_set_found(estate, found);
2621
2622                                 return rc;
2623                         }
2624                 }
2625
2626                 SPI_freetuptable(tuptab);
2627
2628                 /*
2629                  * Fetch the next 50 tuples
2630                  */
2631                 SPI_cursor_fetch(portal, true, 50);
2632                 n = SPI_processed;
2633                 tuptab = SPI_tuptable;
2634         }
2635
2636         /*
2637          * Release last group of tuples
2638          */
2639         SPI_freetuptable(tuptab);
2640
2641         /*
2642          * Close the implicit cursor
2643          */
2644         SPI_cursor_close(portal);
2645
2646         /*
2647          * Set the FOUND variable to indicate the result of executing the loop
2648          * (namely, whether we looped one or more times). This must be set here so
2649          * that it does not interfere with the value of the FOUND variable inside
2650          * the loop processing itself.
2651          */
2652         exec_set_found(estate, found);
2653
2654         return PLPGSQL_RC_OK;
2655 }
2656
2657
2658 /* ----------
2659  * exec_stmt_open                       Execute an OPEN cursor statement
2660  * ----------
2661  */
2662 static int
2663 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
2664 {
2665         PLpgSQL_var *curvar = NULL;
2666         char       *curname = NULL;
2667         PLpgSQL_expr *query = NULL;
2668         Portal          portal;
2669         int                     i;
2670         Datum      *values;
2671         char       *nulls;
2672         bool            isnull;
2673
2674
2675         /* ----------
2676          * Get the cursor variable and if it has an assigned name, check
2677          * that it's not in use currently.
2678          * ----------
2679          */
2680         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2681         if (!curvar->isnull)
2682         {
2683                 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2684                 if (SPI_cursor_find(curname) != NULL)
2685                         ereport(ERROR,
2686                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
2687                                          errmsg("cursor \"%s\" already in use", curname)));
2688         }
2689
2690         /* ----------
2691          * Process the OPEN according to it's type.
2692          * ----------
2693          */
2694         if (stmt->query != NULL)
2695         {
2696                 /* ----------
2697                  * This is an OPEN refcursor FOR SELECT ...
2698                  *
2699                  * We just make sure the query is planned. The real work is
2700                  * done downstairs.
2701                  * ----------
2702                  */
2703                 query = stmt->query;
2704                 if (query->plan == NULL)
2705                         exec_prepare_plan(estate, query);
2706         }
2707         else if (stmt->dynquery != NULL)
2708         {
2709                 /* ----------
2710                  * This is an OPEN refcursor FOR EXECUTE ...
2711                  * ----------
2712                  */
2713                 Datum           queryD;
2714                 Oid                     restype;
2715                 char       *querystr;
2716                 void       *curplan;
2717
2718                 /* ----------
2719                  * We evaluate the string expression after the
2720                  * EXECUTE keyword. It's result is the querystring we have
2721                  * to execute.
2722                  * ----------
2723                  */
2724                 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
2725                 if (isnull)
2726                         ereport(ERROR,
2727                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2728                                          errmsg("cannot EXECUTE a null querystring")));
2729
2730                 /* Get the C-String representation */
2731                 querystr = convert_value_to_string(queryD, restype);
2732
2733                 exec_eval_cleanup(estate);
2734
2735                 /* ----------
2736                  * Now we prepare a query plan for it and open a cursor
2737                  * ----------
2738                  */
2739                 curplan = SPI_prepare(querystr, 0, NULL);
2740                 if (curplan == NULL)
2741                         elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2742                                  querystr, SPI_result_code_string(SPI_result));
2743                 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
2744                                                                  estate->readonly_func);
2745                 if (portal == NULL)
2746                         elog(ERROR, "could not open cursor for query \"%s\": %s",
2747                                  querystr, SPI_result_code_string(SPI_result));
2748                 pfree(querystr);
2749                 SPI_freeplan(curplan);
2750
2751                 /* ----------
2752                  * Store the eventually assigned cursor name in the cursor variable
2753                  * ----------
2754                  */
2755                 free_var(curvar);
2756                 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2757                 curvar->isnull = false;
2758                 curvar->freeval = true;
2759
2760                 return PLPGSQL_RC_OK;
2761         }
2762         else
2763         {
2764                 /* ----------
2765                  * This is an OPEN cursor
2766                  *
2767                  * Note: parser should already have checked that statement supplies
2768                  * args iff cursor needs them, but we check again to be safe.
2769                  * ----------
2770                  */
2771                 if (stmt->argquery != NULL)
2772                 {
2773                         /* ----------
2774                          * Er - OPEN CURSOR (args). We fake a SELECT ... INTO ...
2775                          * statement to evaluate the args and put 'em into the
2776                          * internal row.
2777                          * ----------
2778                          */
2779                         PLpgSQL_stmt_select set_args;
2780
2781                         if (curvar->cursor_explicit_argrow < 0)
2782                                 ereport(ERROR,
2783                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2784                                         errmsg("arguments given for cursor without arguments")));
2785
2786                         memset(&set_args, 0, sizeof(set_args));
2787                         set_args.cmd_type = PLPGSQL_STMT_SELECT;
2788                         set_args.lineno = stmt->lineno;
2789                         set_args.row = (PLpgSQL_row *)
2790                                 (estate->datums[curvar->cursor_explicit_argrow]);
2791                         set_args.query = stmt->argquery;
2792
2793                         if (exec_stmt_select(estate, &set_args) != PLPGSQL_RC_OK)
2794                                 elog(ERROR, "open cursor failed during argument processing");
2795                 }
2796                 else
2797                 {
2798                         if (curvar->cursor_explicit_argrow >= 0)
2799                                 ereport(ERROR,
2800                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2801                                                  errmsg("arguments required for cursor")));
2802                 }
2803
2804                 query = curvar->cursor_explicit_expr;
2805                 if (query->plan == NULL)
2806                         exec_prepare_plan(estate, query);
2807         }
2808
2809         /* ----------
2810          * Here we go if we have a saved plan where we have to put
2811          * values into, either from an explicit cursor or from a
2812          * refcursor opened with OPEN ... FOR SELECT ...;
2813          * ----------
2814          */
2815         values = (Datum *) palloc(query->nparams * sizeof(Datum));
2816         nulls = (char *) palloc(query->nparams * sizeof(char));
2817
2818         for (i = 0; i < query->nparams; i++)
2819         {
2820                 PLpgSQL_datum *datum = estate->datums[query->params[i]];
2821                 Oid                     paramtypeid;
2822                 bool            paramisnull;
2823
2824                 exec_eval_datum(estate, datum, query->plan_argtypes[i],
2825                                                 &paramtypeid, &values[i], &paramisnull);
2826                 if (paramisnull)
2827                         nulls[i] = 'n';
2828                 else
2829                         nulls[i] = ' ';
2830         }
2831
2832         /* ----------
2833          * Open the cursor
2834          * ----------
2835          */
2836         portal = SPI_cursor_open(curname, query->plan, values, nulls,
2837                                                          estate->readonly_func);
2838         if (portal == NULL)
2839                 elog(ERROR, "could not open cursor: %s",
2840                          SPI_result_code_string(SPI_result));
2841
2842         pfree(values);
2843         pfree(nulls);
2844         if (curname)
2845                 pfree(curname);
2846
2847         /* ----------
2848          * Store the eventually assigned portal name in the cursor variable
2849          * ----------
2850          */
2851         free_var(curvar);
2852         curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2853         curvar->isnull = false;
2854         curvar->freeval = true;
2855
2856         return PLPGSQL_RC_OK;
2857 }
2858
2859
2860 /* ----------
2861  * exec_stmt_fetch                      Fetch from a cursor into a target
2862  * ----------
2863  */
2864 static int
2865 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
2866 {
2867         PLpgSQL_var *curvar = NULL;
2868         PLpgSQL_rec *rec = NULL;
2869         PLpgSQL_row *row = NULL;
2870         SPITupleTable *tuptab;
2871         Portal          portal;
2872         char       *curname;
2873         int                     n;
2874
2875         /* ----------
2876          * Get the portal of the cursor by name
2877          * ----------
2878          */
2879         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2880         if (curvar->isnull)
2881                 ereport(ERROR,
2882                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2883                                  errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2884         curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2885
2886         portal = SPI_cursor_find(curname);
2887         if (portal == NULL)
2888                 ereport(ERROR,
2889                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
2890                                  errmsg("cursor \"%s\" does not exist", curname)));
2891         pfree(curname);
2892
2893         /* ----------
2894          * Determine if we fetch into a record or a row
2895          * ----------
2896          */
2897         if (stmt->rec != NULL)
2898                 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2899         else if (stmt->row != NULL)
2900                 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2901         else
2902                 elog(ERROR, "unsupported target");
2903
2904         /* ----------
2905          * Fetch 1 tuple from the cursor
2906          * ----------
2907          */
2908         SPI_cursor_fetch(portal, true, 1);
2909         tuptab = SPI_tuptable;
2910         n = SPI_processed;
2911
2912         /* ----------
2913          * Set the target and the global FOUND variable appropriately.
2914          * ----------
2915          */
2916         if (n == 0)
2917         {
2918                 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2919                 exec_set_found(estate, false);
2920         }
2921         else
2922         {
2923                 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2924                 exec_set_found(estate, true);
2925         }
2926
2927         SPI_freetuptable(tuptab);
2928
2929         return PLPGSQL_RC_OK;
2930 }
2931
2932
2933 /* ----------
2934  * exec_stmt_close                      Close a cursor
2935  * ----------
2936  */
2937 static int
2938 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
2939 {
2940         PLpgSQL_var *curvar = NULL;
2941         Portal          portal;
2942         char       *curname;
2943
2944         /* ----------
2945          * Get the portal of the cursor by name
2946          * ----------
2947          */
2948         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2949         if (curvar->isnull)
2950                 ereport(ERROR,
2951                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2952                                  errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2953         curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2954
2955         portal = SPI_cursor_find(curname);
2956         if (portal == NULL)
2957                 ereport(ERROR,
2958                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
2959                                  errmsg("cursor \"%s\" does not exist", curname)));
2960         pfree(curname);
2961
2962         /* ----------
2963          * And close it.
2964          * ----------
2965          */
2966         SPI_cursor_close(portal);
2967
2968         return PLPGSQL_RC_OK;
2969 }
2970
2971
2972 /* ----------
2973  * exec_assign_expr                     Put an expression's result into
2974  *                                      a variable.
2975  * ----------
2976  */
2977 static void
2978 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
2979                                  PLpgSQL_expr *expr)
2980 {
2981         Datum           value;
2982         Oid                     valtype;
2983         bool            isnull = false;
2984
2985         value = exec_eval_expr(estate, expr, &isnull, &valtype);
2986         exec_assign_value(estate, target, value, valtype, &isnull);
2987         exec_eval_cleanup(estate);
2988 }
2989
2990
2991 /* ----------
2992  * exec_assign_value                    Put a value into a target field
2993  * ----------
2994  */
2995 static void
2996 exec_assign_value(PLpgSQL_execstate *estate,
2997                                   PLpgSQL_datum *target,
2998                                   Datum value, Oid valtype, bool *isNull)
2999 {
3000         switch (target->dtype)
3001         {
3002                 case PLPGSQL_DTYPE_VAR:
3003                         {
3004                                 /*
3005                                  * Target is a variable
3006                                  */
3007                                 PLpgSQL_var *var = (PLpgSQL_var *) target;
3008                                 Datum           newvalue;
3009
3010                                 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3011                                                                                    &(var->datatype->typinput),
3012                                                                                    var->datatype->typioparam,
3013                                                                                    var->datatype->atttypmod,
3014                                                                                    *isNull);
3015
3016                                 if (*isNull && var->notnull)
3017                                         ereport(ERROR,
3018                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3019                                                          errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3020                                                                         var->refname)));
3021
3022                                 /*
3023                                  * If type is by-reference, make sure we have a freshly
3024                                  * palloc'd copy; the originally passed value may not live as
3025                                  * long as the variable!  But we don't need to re-copy if
3026                                  * exec_cast_value performed a conversion; its output must
3027                                  * already be palloc'd.
3028                                  */
3029                                 if (!var->datatype->typbyval && !*isNull)
3030                                 {
3031                                         if (newvalue == value)
3032                                                 newvalue = datumCopy(newvalue,
3033                                                                                          false,
3034                                                                                          var->datatype->typlen);
3035                                 }
3036
3037                                 /*
3038                                  * Now free the old value.      (We can't do this any earlier
3039                                  * because of the possibility that we are assigning the var's
3040                                  * old value to it, eg "foo := foo".  We could optimize out
3041                                  * the assignment altogether in such cases, but it's too
3042                                  * infrequent to be worth testing for.)
3043                                  */
3044                                 free_var(var);
3045
3046                                 var->value = newvalue;
3047                                 var->isnull = *isNull;
3048                                 if (!var->datatype->typbyval && !*isNull)
3049                                         var->freeval = true;
3050                                 break;
3051                         }
3052
3053                 case PLPGSQL_DTYPE_ROW:
3054                         {
3055                                 /*
3056                                  * Target is a row variable
3057                                  */
3058                                 PLpgSQL_row *row = (PLpgSQL_row *) target;
3059
3060                                 /* Source must be of RECORD or composite type */
3061                                 if (!(valtype == RECORDOID ||
3062                                           get_typtype(valtype) == 'c'))
3063                                         ereport(ERROR,
3064                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3065                                                          errmsg("cannot assign non-composite value to a row variable")));
3066                                 if (*isNull)
3067                                 {
3068                                         /* If source is null, just assign nulls to the row */
3069                                         exec_move_row(estate, NULL, row, NULL, NULL);
3070                                 }
3071                                 else
3072                                 {
3073                                         HeapTupleHeader td;
3074                                         Oid                     tupType;
3075                                         int32           tupTypmod;
3076                                         TupleDesc       tupdesc;
3077                                         HeapTupleData tmptup;
3078
3079                                         /* Else source is a tuple Datum, safe to do this: */
3080                                         td = DatumGetHeapTupleHeader(value);
3081                                         /* Extract rowtype info and find a tupdesc */
3082                                         tupType = HeapTupleHeaderGetTypeId(td);
3083                                         tupTypmod = HeapTupleHeaderGetTypMod(td);
3084                                         tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3085                                         /* Build a temporary HeapTuple control structure */
3086                                         tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3087                                         ItemPointerSetInvalid(&(tmptup.t_self));
3088                                         tmptup.t_tableOid = InvalidOid;
3089                                         tmptup.t_data = td;
3090                                         exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3091                                 }
3092                                 break;
3093                         }
3094
3095                 case PLPGSQL_DTYPE_REC:
3096                         {
3097                                 /*
3098                                  * Target is a record variable
3099                                  */
3100                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3101
3102                                 /* Source must be of RECORD or composite type */
3103                                 if (!(valtype == RECORDOID ||
3104                                           get_typtype(valtype) == 'c'))
3105                                         ereport(ERROR,
3106                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3107                                                          errmsg("cannot assign non-composite value to a record variable")));
3108                                 if (*isNull)
3109                                 {
3110                                         /* If source is null, just assign nulls to the record */
3111                                         exec_move_row(estate, rec, NULL, NULL, NULL);
3112                                 }
3113                                 else
3114                                 {
3115                                         HeapTupleHeader td;
3116                                         Oid                     tupType;
3117                                         int32           tupTypmod;
3118                                         TupleDesc       tupdesc;
3119                                         HeapTupleData tmptup;
3120
3121                                         /* Else source is a tuple Datum, safe to do this: */
3122                                         td = DatumGetHeapTupleHeader(value);
3123                                         /* Extract rowtype info and find a tupdesc */
3124                                         tupType = HeapTupleHeaderGetTypeId(td);
3125                                         tupTypmod = HeapTupleHeaderGetTypMod(td);
3126                                         tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3127                                         /* Build a temporary HeapTuple control structure */
3128                                         tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3129                                         ItemPointerSetInvalid(&(tmptup.t_self));
3130                                         tmptup.t_tableOid = InvalidOid;
3131                                         tmptup.t_data = td;
3132                                         exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3133                                 }
3134                                 break;
3135                         }
3136
3137                 case PLPGSQL_DTYPE_RECFIELD:
3138                         {
3139                                 /*
3140                                  * Target is a field of a record
3141                                  */
3142                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3143                                 PLpgSQL_rec *rec;
3144                                 int                     fno;
3145                                 HeapTuple       newtup;
3146                                 int                     natts;
3147                                 int                     i;
3148                                 Datum      *values;
3149                                 char       *nulls;
3150                                 void       *mustfree;
3151                                 bool            attisnull;
3152                                 Oid                     atttype;
3153                                 int32           atttypmod;
3154
3155                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3156
3157                                 /*
3158                                  * Check that there is already a tuple in the record. We need
3159                                  * that because records don't have any predefined field
3160                                  * structure.
3161                                  */
3162                                 if (!HeapTupleIsValid(rec->tup))
3163                                         ereport(ERROR,
3164                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3165                                                    errmsg("record \"%s\" is not assigned yet",
3166                                                                   rec->refname),
3167                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3168
3169                                 /*
3170                                  * Get the number of the records field to change and the
3171                                  * number of attributes in the tuple.
3172                                  */
3173                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3174                                 if (fno == SPI_ERROR_NOATTRIBUTE)
3175                                         ereport(ERROR,
3176                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
3177                                                          errmsg("record \"%s\" has no field \"%s\"",
3178                                                                         rec->refname, recfield->fieldname)));
3179                                 fno--;
3180                                 natts = rec->tupdesc->natts;
3181
3182                                 /*
3183                                  * Set up values/datums arrays for heap_formtuple.      For all
3184                                  * the attributes except the one we want to replace, use the
3185                                  * value that's in the old tuple.
3186                                  */
3187                                 values = palloc(sizeof(Datum) * natts);
3188                                 nulls = palloc(natts);
3189
3190                                 for (i = 0; i < natts; i++)
3191                                 {
3192                                         if (i == fno)
3193                                                 continue;
3194                                         values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3195                                                                                           i + 1, &attisnull);
3196                                         if (attisnull)
3197                                                 nulls[i] = 'n';
3198                                         else
3199                                                 nulls[i] = ' ';
3200                                 }
3201
3202                                 /*
3203                                  * Now insert the new value, being careful to cast it to the
3204                                  * right type.
3205                                  */
3206                                 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3207                                 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3208                                 attisnull = *isNull;
3209                                 values[fno] = exec_simple_cast_value(value,
3210                                                                                                          valtype,
3211                                                                                                          atttype,
3212                                                                                                          atttypmod,
3213                                                                                                          attisnull);
3214                                 if (attisnull)
3215                                         nulls[fno] = 'n';
3216                                 else
3217                                         nulls[fno] = ' ';
3218
3219                                 /*
3220                                  * Avoid leaking the result of exec_simple_cast_value, if it
3221                                  * performed a conversion to a pass-by-ref type.
3222                                  */
3223                                 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3224                                         mustfree = DatumGetPointer(values[fno]);
3225                                 else
3226                                         mustfree = NULL;
3227
3228                                 /*
3229                                  * Now call heap_formtuple() to create a new tuple that
3230                                  * replaces the old one in the record.
3231                                  */
3232                                 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3233
3234                                 if (rec->freetup)
3235                                         heap_freetuple(rec->tup);
3236
3237                                 rec->tup = newtup;
3238                                 rec->freetup = true;
3239
3240                                 pfree(values);
3241                                 pfree(nulls);
3242                                 if (mustfree)
3243                                         pfree(mustfree);
3244
3245                                 break;
3246                         }
3247
3248                 case PLPGSQL_DTYPE_ARRAYELEM:
3249                         {
3250                                 int                     nsubscripts;
3251                                 int                     i;
3252                                 PLpgSQL_expr *subscripts[MAXDIM];
3253                                 int                     subscriptvals[MAXDIM];
3254                                 bool            oldarrayisnull;
3255                                 Oid                     arraytypeid,
3256                                                         arrayelemtypeid;
3257                                 int16           arraytyplen,
3258                                                         elemtyplen;
3259                                 bool            elemtypbyval;
3260                                 char            elemtypalign;
3261                                 Datum           oldarraydatum,
3262                                                         coerced_value;
3263                                 ArrayType  *oldarrayval;
3264                                 ArrayType  *newarrayval;
3265
3266                                 /*
3267                                  * Target is an element of an array
3268                                  *
3269                                  * To handle constructs like x[1][2] := something, we have to
3270                                  * be prepared to deal with a chain of arrayelem datums. Chase
3271                                  * back to find the base array datum, and save the subscript
3272                                  * expressions as we go.  (We are scanning right to left here,
3273                                  * but want to evaluate the subscripts left-to-right to
3274                                  * minimize surprises.)
3275                                  */
3276                                 nsubscripts = 0;
3277                                 do
3278                                 {
3279                                         PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3280
3281                                         if (nsubscripts >= MAXDIM)
3282                                                 ereport(ERROR,
3283                                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3284                                                                  errmsg("number of array dimensions exceeds the maximum allowed, %d",
3285                                                                                 MAXDIM)));
3286                                         subscripts[nsubscripts++] = arrayelem->subscript;
3287                                         target = estate->datums[arrayelem->arrayparentno];
3288                                 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3289
3290                                 /* Fetch current value of array datum */
3291                                 exec_eval_datum(estate, target, InvalidOid,
3292                                                           &arraytypeid, &oldarraydatum, &oldarrayisnull);
3293
3294                                 arrayelemtypeid = get_element_type(arraytypeid);
3295                                 if (!OidIsValid(arrayelemtypeid))
3296                                         ereport(ERROR,
3297                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3298                                                          errmsg("subscripted object is not an array")));
3299
3300                                 get_typlenbyvalalign(arrayelemtypeid,
3301                                                                          &elemtyplen,
3302                                                                          &elemtypbyval,
3303                                                                          &elemtypalign);
3304                                 arraytyplen = get_typlen(arraytypeid);
3305
3306                                 /*
3307                                  * Evaluate the subscripts, switch into left-to-right order.
3308                                  * Like ExecEvalArrayRef(), complain if any subscript is null.
3309                                  */
3310                                 for (i = 0; i < nsubscripts; i++)
3311                                 {
3312                                         bool            subisnull;
3313
3314                                         subscriptvals[i] =
3315                                                 exec_eval_integer(estate,
3316                                                                                   subscripts[nsubscripts - 1 - i],
3317                                                                                   &subisnull);
3318                                         if (subisnull)
3319                                                 ereport(ERROR,
3320                                                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3321                                                                  errmsg("array subscript in assignment must not be NULL")));
3322                                 }
3323
3324                                 /* Coerce source value to match array element type. */
3325                                 coerced_value = exec_simple_cast_value(value,
3326                                                                                                            valtype,
3327                                                                                                            arrayelemtypeid,
3328                                                                                                            -1,
3329                                                                                                            *isNull);
3330
3331                                 /*
3332                                  * If the original array is null, cons up an empty array so
3333                                  * that the assignment can proceed; we'll end with a
3334                                  * one-element array containing just the assigned-to
3335                                  * subscript.  This only works for varlena arrays, though; for
3336                                  * fixed-length array types we skip the assignment.  We can't
3337                                  * support assignment of a null entry into a fixed-length
3338                                  * array, either, so that's a no-op too.  This is all ugly but
3339                                  * corresponds to the current behavior of ExecEvalArrayRef().
3340                                  */
3341                                 if (arraytyplen > 0 &&  /* fixed-length array? */
3342                                         (oldarrayisnull || *isNull))
3343                                         return;
3344
3345                                 if (oldarrayisnull)
3346                                         oldarrayval = construct_empty_array(arrayelemtypeid);
3347                                 else
3348                                         oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3349
3350                                 /*
3351                                  * Build the modified array value.
3352                                  */
3353                                 newarrayval = array_set(oldarrayval,
3354                                                                                 nsubscripts,
3355                                                                                 subscriptvals,
3356                                                                                 coerced_value,
3357                                                                                 *isNull,
3358                                                                                 arraytyplen,
3359                                                                                 elemtyplen,
3360                                                                                 elemtypbyval,
3361                                                                                 elemtypalign);
3362
3363                                 /*
3364                                  * Avoid leaking the result of exec_simple_cast_value, if it
3365                                  * performed a conversion to a pass-by-ref type.
3366                                  */
3367                                 if (!*isNull && coerced_value != value && !elemtypbyval)
3368                                         pfree(DatumGetPointer(coerced_value));
3369
3370                                 /*
3371                                  * Assign the new array to the base variable.  It's never NULL
3372                                  * at this point.
3373                                  */
3374                                 *isNull = false;
3375                                 exec_assign_value(estate, target,
3376                                                                   PointerGetDatum(newarrayval),
3377                                                                   arraytypeid, isNull);
3378
3379                                 /*
3380                                  * Avoid leaking the modified array value, too.
3381                                  */
3382                                 pfree(newarrayval);
3383                                 break;
3384                         }
3385
3386                 default:
3387                         elog(ERROR, "unrecognized dtype: %d", target->dtype);
3388         }
3389 }
3390
3391 /*
3392  * exec_eval_datum                              Get current value of a PLpgSQL_datum
3393  *
3394  * The type oid, value in Datum format, and null flag are returned.
3395  *
3396  * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3397  *
3398  * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3399  *
3400  * NOTE: caller must not modify the returned value, since it points right
3401  * at the stored value in the case of pass-by-reference datatypes.      In some
3402  * cases we have to palloc a return value, and in such cases we put it into
3403  * the estate's short-term memory context.
3404  */
3405 static void
3406 exec_eval_datum(PLpgSQL_execstate *estate,
3407                                 PLpgSQL_datum *datum,
3408                                 Oid expectedtypeid,
3409                                 Oid *typeid,
3410                                 Datum *value,
3411                                 bool *isnull)
3412 {
3413         MemoryContext oldcontext;
3414
3415         switch (datum->dtype)
3416         {
3417                 case PLPGSQL_DTYPE_VAR:
3418                         {
3419                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3420
3421                                 *typeid = var->datatype->typoid;
3422                                 *value = var->value;
3423                                 *isnull = var->isnull;
3424                                 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3425                                         ereport(ERROR,
3426                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3427                                                          errmsg("type of \"%s\" does not match that when preparing the plan",
3428                                                                         var->refname)));
3429                                 break;
3430                         }
3431
3432                 case PLPGSQL_DTYPE_ROW:
3433                         {
3434                                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3435                                 HeapTuple       tup;
3436
3437                                 if (!row->rowtupdesc)   /* should not happen */
3438                                         elog(ERROR, "row variable has no tupdesc");
3439                                 /* Make sure we have a valid type/typmod setting */
3440                                 BlessTupleDesc(row->rowtupdesc);
3441                                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3442                                 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3443                                 if (tup == NULL)        /* should not happen */
3444                                         elog(ERROR, "row not compatible with its own tupdesc");
3445                                 MemoryContextSwitchTo(oldcontext);
3446                                 *typeid = row->rowtupdesc->tdtypeid;
3447                                 *value = HeapTupleGetDatum(tup);
3448                                 *isnull = false;
3449                                 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3450                                         ereport(ERROR,
3451                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3452                                                          errmsg("type of \"%s\" does not match that when preparing the plan",
3453                                                                         row->refname)));
3454                                 break;
3455                         }
3456
3457                 case PLPGSQL_DTYPE_REC:
3458                         {
3459                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3460                                 HeapTupleData worktup;
3461
3462                                 if (!HeapTupleIsValid(rec->tup))
3463                                         ereport(ERROR,
3464                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3465                                                    errmsg("record \"%s\" is not assigned yet",
3466                                                                   rec->refname),
3467                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3468                                 Assert(rec->tupdesc != NULL);
3469                                 /* Make sure we have a valid type/typmod setting */
3470                                 BlessTupleDesc(rec->tupdesc);
3471
3472                                 /*
3473                                  * In a trigger, the NEW and OLD parameters are likely to be
3474                                  * on-disk tuples that don't have the desired Datum fields.
3475                                  * Copy the tuple body and insert the right values.
3476                                  */
3477                                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3478                                 heap_copytuple_with_tuple(rec->tup, &worktup);
3479                                 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3480                                 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3481                                 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3482                                 MemoryContextSwitchTo(oldcontext);
3483                                 *typeid = rec->tupdesc->tdtypeid;
3484                                 *value = HeapTupleGetDatum(&worktup);
3485                                 *isnull = false;
3486                                 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3487                                         ereport(ERROR,
3488                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3489                                                          errmsg("type of \"%s\" does not match that when preparing the plan",
3490                                                                         rec->refname)));
3491                                 break;
3492                         }
3493
3494                 case PLPGSQL_DTYPE_RECFIELD:
3495                         {
3496                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3497                                 PLpgSQL_rec *rec;
3498                                 int                     fno;
3499
3500                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3501                                 if (!HeapTupleIsValid(rec->tup))
3502                                         ereport(ERROR,
3503                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3504                                                    errmsg("record \"%s\" is not assigned yet",
3505                                                                   rec->refname),
3506                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3507                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3508                                 if (fno == SPI_ERROR_NOATTRIBUTE)
3509                                         ereport(ERROR,
3510                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
3511                                                          errmsg("record \"%s\" has no field \"%s\"",
3512                                                                         rec->refname, recfield->fieldname)));
3513                                 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3514                                 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3515                                 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3516                                         ereport(ERROR,
3517                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3518                                                          errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3519                                                                         rec->refname, recfield->fieldname)));
3520                                 break;
3521                         }
3522
3523                 case PLPGSQL_DTYPE_TRIGARG:
3524                         {
3525                                 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3526                                 int                     tgargno;
3527
3528                                 *typeid = TEXTOID;
3529                                 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3530                                 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3531                                 {
3532                                         *value = (Datum) 0;
3533                                         *isnull = true;
3534                                 }
3535                                 else
3536                                 {
3537                                         *value = estate->trig_argv[tgargno];
3538                                         *isnull = false;
3539                                 }
3540                                 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3541                                         ereport(ERROR,
3542                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3543                                                          errmsg("type of tgargv[%d] does not match that when preparing the plan",
3544                                                                         tgargno)));
3545                                 break;
3546                         }
3547
3548                 default:
3549                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3550         }
3551 }
3552
3553 /* ----------
3554  * exec_eval_integer            Evaluate an expression, coerce result to int4
3555  *
3556  * Note we do not do exec_eval_cleanup here; the caller must do it at
3557  * some later point.  (We do this because the caller may be holding the
3558  * results of other, pass-by-reference, expression evaluations, such as
3559  * an array value to be subscripted.  Also see notes in exec_eval_simple_expr
3560  * about allocation of the parameter array.)
3561  * ----------
3562  */
3563 static int
3564 exec_eval_integer(PLpgSQL_execstate *estate,
3565                                   PLpgSQL_expr *expr,
3566                                   bool *isNull)
3567 {
3568         Datum           exprdatum;
3569         Oid                     exprtypeid;
3570
3571         exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3572         exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3573                                                                            INT4OID, -1,
3574                                                                            *isNull);
3575         return DatumGetInt32(exprdatum);
3576 }
3577
3578 /* ----------
3579  * exec_eval_boolean            Evaluate an expression, coerce result to bool
3580  *
3581  * Note we do not do exec_eval_cleanup here; the caller must do it at
3582  * some later point.
3583  * ----------
3584  */
3585 static bool
3586 exec_eval_boolean(PLpgSQL_execstate *estate,
3587                                   PLpgSQL_expr *expr,
3588                                   bool *isNull)
3589 {
3590         Datum           exprdatum;
3591         Oid                     exprtypeid;
3592
3593         exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3594         exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3595                                                                            BOOLOID, -1,
3596                                                                            *isNull);
3597         return DatumGetBool(exprdatum);
3598 }
3599
3600 /* ----------
3601  * exec_eval_expr                       Evaluate an expression and return
3602  *                                      the result Datum.
3603  *
3604  * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3605  * ----------
3606  */
3607 static Datum
3608 exec_eval_expr(PLpgSQL_execstate *estate,
3609                            PLpgSQL_expr *expr,
3610                            bool *isNull,
3611                            Oid *rettype)
3612 {
3613         int                     rc;
3614
3615         /*
3616          * If not already done create a plan for this expression
3617          */
3618         if (expr->plan == NULL)
3619                 exec_prepare_plan(estate, expr);
3620
3621         /*
3622          * If this is a simple expression, bypass SPI and use the executor
3623          * directly
3624          */
3625         if (expr->expr_simple_expr != NULL)
3626                 return exec_eval_simple_expr(estate, expr, isNull, rettype);
3627
3628         rc = exec_run_select(estate, expr, 2, NULL);
3629         if (rc != SPI_OK_SELECT)
3630                 ereport(ERROR,
3631                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3632                                  errmsg("query \"%s\" did not return data", expr->query)));
3633
3634         /*
3635          * If there are no rows selected, the result is NULL.
3636          */
3637         if (estate->eval_processed == 0)
3638         {
3639                 *isNull = true;
3640                 return (Datum) 0;
3641         }
3642
3643         /*
3644          * Check that the expression returned one single Datum
3645          */
3646         if (estate->eval_processed > 1)
3647                 ereport(ERROR,
3648                                 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3649                                  errmsg("query \"%s\" returned more than one row",
3650                                                 expr->query)));
3651         if (estate->eval_tuptable->tupdesc->natts != 1)
3652                 ereport(ERROR,
3653                                 (errcode(ERRCODE_SYNTAX_ERROR),
3654                                  errmsg("query \"%s\" returned %d columns", expr->query,
3655                                                 estate->eval_tuptable->tupdesc->natts)));
3656
3657         /*
3658          * Return the result and its type
3659          */
3660         *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
3661         return SPI_getbinval(estate->eval_tuptable->vals[0],
3662                                                  estate->eval_tuptable->tupdesc, 1, isNull);
3663 }
3664
3665
3666 /* ----------
3667  * exec_run_select                      Execute a select query
3668  * ----------
3669  */
3670 static int
3671 exec_run_select(PLpgSQL_execstate *estate,
3672                                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
3673 {
3674         int                     i;
3675         Datum      *values;
3676         char       *nulls;
3677         int                     rc;
3678
3679         /*
3680          * On the first call for this expression generate the plan
3681          */
3682         if (expr->plan == NULL)
3683                 exec_prepare_plan(estate, expr);
3684
3685         /*
3686          * Now build up the values and nulls arguments for SPI_execute_plan()
3687          */
3688         values = (Datum *) palloc(expr->nparams * sizeof(Datum));
3689         nulls = (char *) palloc(expr->nparams * sizeof(char));
3690
3691         for (i = 0; i < expr->nparams; i++)
3692         {
3693                 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3694                 Oid                     paramtypeid;
3695                 bool            paramisnull;
3696
3697                 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3698                                                 &paramtypeid, &values[i], &paramisnull);
3699                 if (paramisnull)
3700                         nulls[i] = 'n';
3701                 else
3702                         nulls[i] = ' ';
3703         }
3704
3705         /*
3706          * If a portal was requested, put the query into the portal
3707          */
3708         if (portalP != NULL)
3709         {
3710                 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
3711                                                                    estate->readonly_func);
3712                 if (*portalP == NULL)
3713                         elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
3714                                  expr->query, SPI_result_code_string(SPI_result));
3715                 pfree(values);
3716                 pfree(nulls);
3717                 return SPI_OK_CURSOR;
3718         }
3719
3720         /*
3721          * Execute the query
3722          */
3723         rc = SPI_execute_plan(expr->plan, values, nulls,
3724                                                   estate->readonly_func, maxtuples);
3725         if (rc != SPI_OK_SELECT)
3726                 ereport(ERROR,
3727                                 (errcode(ERRCODE_SYNTAX_ERROR),
3728                                  errmsg("query \"%s\" is not a SELECT", expr->query)));
3729
3730         /* Save query results for eventual cleanup */
3731         Assert(estate->eval_tuptable == NULL);
3732         estate->eval_tuptable = SPI_tuptable;
3733         estate->eval_processed = SPI_processed;
3734         estate->eval_lastoid = SPI_lastoid;
3735
3736         pfree(values);
3737         pfree(nulls);
3738
3739         return rc;
3740 }
3741
3742
3743 /* ----------
3744  * exec_eval_simple_expr -              Evaluate a simple expression returning
3745  *                                                              a Datum by directly calling ExecEvalExpr().
3746  *
3747  * Note: if pass-by-reference, the result is in the eval_econtext's
3748  * temporary memory context.  It will be freed when exec_eval_cleanup
3749  * is done.
3750  * ----------
3751  */
3752 static Datum
3753 exec_eval_simple_expr(PLpgSQL_execstate *estate,
3754                                           PLpgSQL_expr *expr,
3755                                           bool *isNull,
3756                                           Oid *rettype)
3757 {
3758         Datum           retval;
3759         ExprContext *econtext = estate->eval_econtext;
3760         TransactionId curxid = GetTopTransactionId();
3761         ParamListInfo paramLI;
3762         int                     i;
3763         Snapshot        saveActiveSnapshot;
3764
3765         /*
3766          * Pass back previously-determined result type.
3767          */
3768         *rettype = expr->expr_simple_type;
3769
3770         /*
3771          * Prepare the expression for execution, if it's not been done already in
3772          * the current transaction.
3773          */
3774         if (expr->expr_simple_xid != curxid)
3775         {
3776                 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
3777                                                                                                   simple_eval_estate);
3778                 expr->expr_simple_xid = curxid;
3779         }
3780
3781         /*
3782          * Param list can live in econtext's temporary memory context.
3783          *
3784          * XXX think about avoiding repeated palloc's for param lists? Beware
3785          * however that this routine is re-entrant: exec_eval_datum() can call it
3786          * back for subscript evaluation, and so there can be a need to have more
3787          * than one active param list.
3788          */
3789         if (expr->nparams > 0)
3790         {
3791                 /* sizeof(ParamListInfoData) includes the first array element */
3792                 paramLI = (ParamListInfo)
3793                         MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
3794                                                            sizeof(ParamListInfoData) +
3795                                                            (expr->nparams - 1) * sizeof(ParamExternData));
3796                 paramLI->numParams = expr->nparams;
3797
3798                 for (i = 0; i < expr->nparams; i++)
3799                 {
3800                         ParamExternData *prm = &paramLI->params[i];
3801                         PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3802
3803                         exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3804                                                         &prm->ptype,
3805                                                         &prm->value, &prm->isnull);
3806                 }
3807         }
3808         else
3809                 paramLI = NULL;
3810
3811         /*
3812          * Now we can safely make the econtext point to the param list.
3813          */
3814         econtext->ecxt_param_list_info = paramLI;
3815
3816         /*
3817          * We have to do some of the things SPI_execute_plan would do, in
3818          * particular advance the snapshot if we are in a non-read-only function.
3819          * Without this, stable functions within the expression would fail to see
3820          * updates made so far by our own function.
3821          */
3822         SPI_push();
3823         saveActiveSnapshot = ActiveSnapshot;
3824
3825         PG_TRY();
3826         {
3827                 MemoryContext oldcontext;
3828
3829                 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3830                 if (!estate->readonly_func)
3831                 {
3832                         CommandCounterIncrement();
3833                         ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
3834                 }
3835
3836                 /*
3837                  * Finally we can call the executor to evaluate the expression
3838                  */
3839                 retval = ExecEvalExpr(expr->expr_simple_state,
3840                                                           econtext,
3841                                                           isNull,
3842                                                           NULL);
3843                 MemoryContextSwitchTo(oldcontext);
3844         }
3845         PG_CATCH();
3846         {
3847                 /* Restore global vars and propagate error */
3848                 ActiveSnapshot = saveActiveSnapshot;
3849                 PG_RE_THROW();
3850         }
3851         PG_END_TRY();
3852
3853         ActiveSnapshot = saveActiveSnapshot;
3854         SPI_pop();
3855
3856         /*
3857          * That's it.
3858          */
3859         return retval;
3860 }
3861
3862
3863 /* ----------
3864  * exec_move_row                        Move one tuple's values into a record or row
3865  * ----------
3866  */
3867 static void
3868 exec_move_row(PLpgSQL_execstate *estate,
3869                           PLpgSQL_rec *rec,
3870                           PLpgSQL_row *row,
3871                           HeapTuple tup, TupleDesc tupdesc)
3872 {
3873         /*
3874          * Record is simple - just copy the tuple and its descriptor into the
3875          * record variable
3876          */
3877         if (rec != NULL)
3878         {
3879                 /*
3880                  * copy input first, just in case it is pointing at variable's value
3881                  */
3882                 if (HeapTupleIsValid(tup))
3883                         tup = heap_copytuple(tup);
3884                 if (tupdesc)
3885                         tupdesc = CreateTupleDescCopy(tupdesc);
3886
3887                 if (rec->freetup)
3888                 {
3889                         heap_freetuple(rec->tup);
3890                         rec->freetup = false;
3891                 }
3892                 if (rec->freetupdesc)
3893                 {
3894                         FreeTupleDesc(rec->tupdesc);
3895                         rec->freetupdesc = false;
3896                 }
3897
3898                 if (HeapTupleIsValid(tup))
3899                 {
3900                         rec->tup = tup;
3901                         rec->freetup = true;
3902                 }
3903                 else if (tupdesc)
3904                 {
3905                         /* If we have a tupdesc but no data, form an all-nulls tuple */
3906                         char       *nulls;
3907
3908                         nulls = (char *) palloc(tupdesc->natts * sizeof(char));
3909                         memset(nulls, 'n', tupdesc->natts * sizeof(char));
3910
3911                         rec->tup = heap_formtuple(tupdesc, NULL, nulls);
3912                         rec->freetup = true;
3913
3914                         pfree(nulls);
3915                 }
3916                 else
3917                         rec->tup = NULL;
3918
3919                 if (tupdesc)
3920                 {
3921                         rec->tupdesc = tupdesc;
3922                         rec->freetupdesc = true;
3923                 }
3924                 else
3925                         rec->tupdesc = NULL;
3926
3927                 return;
3928         }
3929
3930         /*
3931          * Row is a bit more complicated in that we assign the individual
3932          * attributes of the tuple to the variables the row points to.
3933          *
3934          * NOTE: this code used to demand row->nfields == tup->t_data->t_natts,
3935          * but that's wrong.  The tuple might have more fields than we expected if
3936          * it's from an inheritance-child table of the current table, or it might
3937          * have fewer if the table has had columns added by ALTER TABLE. Ignore
3938          * extra columns and assume NULL for missing columns, the same as
3939          * heap_getattr would do.  We also have to skip over dropped columns in
3940          * either the source or destination.
3941          *
3942          * If we have no tuple data at all, we'll assign NULL to all columns of
3943          * the row variable.
3944          */
3945         if (row != NULL)
3946         {
3947                 int                     t_natts;
3948                 int                     fnum;
3949                 int                     anum;
3950
3951                 if (HeapTupleIsValid(tup))
3952                         t_natts = tup->t_data->t_natts;
3953                 else
3954                         t_natts = 0;
3955
3956                 anum = 0;
3957                 for (fnum = 0; fnum < row->nfields; fnum++)
3958                 {
3959                         PLpgSQL_var *var;
3960                         Datum           value;
3961                         bool            isnull;
3962                         Oid                     valtype;
3963
3964                         if (row->varnos[fnum] < 0)
3965                                 continue;               /* skip dropped column in row struct */
3966
3967                         var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
3968
3969                         while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
3970                                 anum++;                 /* skip dropped column in tuple */
3971
3972                         if (anum < t_natts)
3973                         {
3974                                 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
3975                                 valtype = SPI_gettypeid(tupdesc, anum + 1);
3976                                 anum++;
3977                         }
3978                         else
3979                         {
3980                                 value = (Datum) 0;
3981                                 isnull = true;
3982                                 valtype = InvalidOid;
3983                         }
3984
3985                         exec_assign_value(estate, (PLpgSQL_datum *) var,
3986                                                           value, valtype, &isnull);
3987                 }
3988
3989                 return;
3990         }
3991
3992         elog(ERROR, "unsupported target");
3993 }
3994
3995 /* ----------
3996  * make_tuple_from_row          Make a tuple from the values of a row object
3997  *
3998  * A NULL return indicates rowtype mismatch; caller must raise suitable error
3999  * ----------
4000  */
4001 static HeapTuple
4002 make_tuple_from_row(PLpgSQL_execstate *estate,
4003                                         PLpgSQL_row *row,
4004                                         TupleDesc tupdesc)
4005 {
4006         int                     natts = tupdesc->natts;
4007         HeapTuple       tuple;
4008         Datum      *dvalues;
4009         bool       *nulls;
4010         int                     i;
4011
4012         if (natts != row->nfields)
4013                 return NULL;
4014
4015         dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4016         nulls = (bool *) palloc(natts * sizeof(bool));
4017
4018         for (i = 0; i < natts; i++)
4019         {
4020                 Oid                     fieldtypeid;
4021
4022                 if (tupdesc->attrs[i]->attisdropped)
4023                 {
4024                         nulls[i] = true;        /* leave the column as null */
4025                         continue;
4026                 }
4027                 if (row->varnos[i] < 0) /* should not happen */
4028                         elog(ERROR, "dropped rowtype entry for non-dropped column");
4029
4030                 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4031                                                 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4032                 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4033                         return NULL;
4034         }
4035
4036         tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4037
4038         pfree(dvalues);
4039         pfree(nulls);
4040
4041         return tuple;
4042 }
4043
4044 /* ----------
4045  * convert_value_to_string                      Convert a non-null Datum to C string
4046  *
4047  * Note: callers generally assume that the result is a palloc'd string and
4048  * should be pfree'd.  This is not all that safe an assumption ...
4049  *
4050  * Note: not caching the conversion function lookup is bad for performance.
4051  * ----------
4052  */
4053 static char *
4054 convert_value_to_string(Datum value, Oid valtype)
4055 {
4056         Oid                     typoutput;
4057         bool            typIsVarlena;
4058
4059         getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4060
4061         return OidOutputFunctionCall(typoutput, value);
4062 }
4063
4064 /* ----------
4065  * exec_cast_value                      Cast a value if required
4066  * ----------
4067  */
4068 static Datum
4069 exec_cast_value(Datum value, Oid valtype,
4070                                 Oid reqtype,
4071                                 FmgrInfo *reqinput,
4072                                 Oid reqtypioparam,
4073                                 int32 reqtypmod,
4074                                 bool isnull)
4075 {
4076         /*
4077          * If the type of the queries return value isn't that of the variable,
4078          * convert it.
4079          */
4080         if (valtype != reqtype || reqtypmod != -1)
4081         {
4082                 if (!isnull)
4083                 {
4084                         char       *extval;
4085
4086                         extval = convert_value_to_string(value, valtype);
4087                         value = InputFunctionCall(reqinput, extval,
4088                                                                           reqtypioparam, reqtypmod);
4089                         pfree(extval);
4090                 }
4091                 else
4092                 {
4093                         value = InputFunctionCall(reqinput, NULL,
4094                                                                           reqtypioparam, reqtypmod);
4095                 }
4096         }
4097
4098         return value;
4099 }
4100
4101 /* ----------
4102  * exec_simple_cast_value                       Cast a value if required
4103  *
4104  * As above, but need not supply details about target type.  Note that this
4105  * is slower than exec_cast_value with cached type info, and so should be
4106  * avoided in heavily used code paths.
4107  * ----------
4108  */
4109 static Datum
4110 exec_simple_cast_value(Datum value, Oid valtype,
4111                                            Oid reqtype, int32 reqtypmod,
4112                                            bool isnull)
4113 {
4114         if (!isnull)
4115         {
4116                 if (valtype != reqtype || reqtypmod != -1)
4117                 {
4118                         Oid                     typinput;
4119                         Oid                     typioparam;
4120                         FmgrInfo        finfo_input;
4121
4122                         getTypeInputInfo(reqtype, &typinput, &typioparam);
4123
4124                         fmgr_info(typinput, &finfo_input);
4125
4126                         value = exec_cast_value(value,
4127                                                                         valtype,
4128                                                                         reqtype,
4129                                                                         &finfo_input,
4130                                                                         typioparam,
4131                                                                         reqtypmod,
4132                                                                         isnull);
4133                 }
4134         }
4135
4136         return value;
4137 }
4138
4139
4140 /* ----------
4141  * exec_simple_check_node -             Recursively check if an expression
4142  *                                                              is made only of simple things we can
4143  *                                                              hand out directly to ExecEvalExpr()
4144  *                                                              instead of calling SPI.
4145  * ----------
4146  */
4147 static bool
4148 exec_simple_check_node(Node *node)
4149 {
4150         if (node == NULL)
4151                 return TRUE;
4152
4153         switch (nodeTag(node))
4154         {
4155                 case T_Const:
4156                         return TRUE;
4157
4158                 case T_Param:
4159                         return TRUE;
4160
4161                 case T_ArrayRef:
4162                         {
4163                                 ArrayRef   *expr = (ArrayRef *) node;
4164
4165                                 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4166                                         return FALSE;
4167                                 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4168                                         return FALSE;
4169                                 if (!exec_simple_check_node((Node *) expr->refexpr))
4170                                         return FALSE;
4171                                 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4172                                         return FALSE;
4173
4174                                 return TRUE;
4175                         }
4176
4177                 case T_FuncExpr:
4178                         {
4179                                 FuncExpr   *expr = (FuncExpr *) node;
4180
4181                                 if (expr->funcretset)
4182                                         return FALSE;
4183                                 if (!exec_simple_check_node((Node *) expr->args))
4184                                         return FALSE;
4185
4186                                 return TRUE;
4187                         }
4188
4189                 case T_OpExpr:
4190                         {
4191                                 OpExpr     *expr = (OpExpr *) node;
4192
4193                                 if (expr->opretset)
4194                                         return FALSE;
4195                                 if (!exec_simple_check_node((Node *) expr->args))
4196                                         return FALSE;
4197
4198                                 return TRUE;
4199                         }
4200
4201                 case T_DistinctExpr:
4202                         {
4203                                 DistinctExpr *expr = (DistinctExpr *) node;
4204
4205                                 if (expr->opretset)
4206                                         return FALSE;
4207                                 if (!exec_simple_check_node((Node *) expr->args))
4208                                         return FALSE;
4209
4210                                 return TRUE;
4211                         }
4212
4213                 case T_ScalarArrayOpExpr:
4214                         {
4215                                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4216
4217                                 if (!exec_simple_check_node((Node *) expr->args))
4218                                         return FALSE;
4219
4220                                 return TRUE;
4221                         }
4222
4223                 case T_BoolExpr:
4224                         {
4225                                 BoolExpr   *expr = (BoolExpr *) node;
4226
4227                                 if (!exec_simple_check_node((Node *) expr->args))
4228                                         return FALSE;
4229
4230                                 return TRUE;
4231                         }
4232
4233                 case T_FieldSelect:
4234                         return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4235
4236                 case T_FieldStore:
4237                         {
4238                                 FieldStore *expr = (FieldStore *) node;
4239
4240                                 if (!exec_simple_check_node((Node *) expr->arg))
4241                                         return FALSE;
4242                                 if (!exec_simple_check_node((Node *) expr->newvals))
4243                                         return FALSE;
4244
4245                                 return TRUE;
4246                         }
4247
4248                 case T_RelabelType:
4249                         return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4250
4251                 case T_ConvertRowtypeExpr:
4252                         return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4253
4254                 case T_CaseExpr:
4255                         {
4256                                 CaseExpr   *expr = (CaseExpr *) node;
4257
4258                                 if (!exec_simple_check_node((Node *) expr->arg))
4259                                         return FALSE;
4260                                 if (!exec_simple_check_node((Node *) expr->args))
4261                                         return FALSE;
4262                                 if (!exec_simple_check_node((Node *) expr->defresult))
4263                                         return FALSE;
4264
4265                                 return TRUE;
4266                         }
4267
4268                 case T_CaseWhen:
4269                         {
4270                                 CaseWhen   *when = (CaseWhen *) node;
4271
4272                                 if (!exec_simple_check_node((Node *) when->expr))
4273                                         return FALSE;
4274                                 if (!exec_simple_check_node((Node *) when->result))
4275                                         return FALSE;
4276
4277                                 return TRUE;
4278                         }
4279
4280                 case T_CaseTestExpr:
4281                         return TRUE;
4282
4283                 case T_ArrayExpr:
4284                         {
4285                                 ArrayExpr  *expr = (ArrayExpr *) node;
4286
4287                                 if (!exec_simple_check_node((Node *) expr->elements))
4288                                         return FALSE;
4289
4290                                 return TRUE;
4291                         }
4292
4293                 case T_RowExpr:
4294                         {
4295                                 RowExpr    *expr = (RowExpr *) node;
4296
4297                                 if (!exec_simple_check_node((Node *) expr->args))
4298                                         return FALSE;
4299
4300                                 return TRUE;
4301                         }
4302
4303                 case T_RowCompareExpr:
4304                         {
4305                                 RowCompareExpr    *expr = (RowCompareExpr *) node;
4306
4307                                 if (!exec_simple_check_node((Node *) expr->largs))
4308                                         return FALSE;
4309                                 if (!exec_simple_check_node((Node *) expr->rargs))
4310                                         return FALSE;
4311
4312                                 return TRUE;
4313                         }
4314
4315                 case T_CoalesceExpr:
4316                         {
4317                                 CoalesceExpr *expr = (CoalesceExpr *) node;
4318
4319                                 if (!exec_simple_check_node((Node *) expr->args))
4320                                         return FALSE;
4321
4322                                 return TRUE;
4323                         }
4324
4325                 case T_MinMaxExpr:
4326                         {
4327                                 MinMaxExpr *expr = (MinMaxExpr *) node;
4328
4329                                 if (!exec_simple_check_node((Node *) expr->args))
4330                                         return FALSE;
4331
4332                                 return TRUE;
4333                         }
4334
4335                 case T_NullIfExpr:
4336                         {
4337                                 NullIfExpr *expr = (NullIfExpr *) node;
4338
4339                                 if (expr->opretset)
4340                                         return FALSE;
4341                                 if (!exec_simple_check_node((Node *) expr->args))
4342                                         return FALSE;
4343
4344                                 return TRUE;
4345                         }
4346
4347                 case T_NullTest:
4348                         return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4349
4350                 case T_BooleanTest:
4351                         return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4352
4353                 case T_CoerceToDomain:
4354                         return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4355
4356                 case T_CoerceToDomainValue:
4357                         return TRUE;
4358
4359                 case T_List:
4360                         {
4361                                 List       *expr = (List *) node;
4362                                 ListCell   *l;
4363
4364                                 foreach(l, expr)
4365                                 {
4366                                         if (!exec_simple_check_node(lfirst(l)))
4367                                                 return FALSE;
4368                                 }
4369
4370                                 return TRUE;
4371                         }
4372
4373                 default:
4374                         return FALSE;
4375         }
4376 }
4377
4378
4379 /* ----------
4380  * exec_simple_check_plan -             Check if a plan is simple enough to
4381  *                                                              be evaluated by ExecEvalExpr() instead
4382  *                                                              of SPI.
4383  * ----------
4384  */
4385 static void
4386 exec_simple_check_plan(PLpgSQL_expr *expr)
4387 {
4388         _SPI_plan  *spi_plan = (_SPI_plan *) expr->plan;
4389         Plan       *plan;
4390         TargetEntry *tle;
4391
4392         expr->expr_simple_expr = NULL;
4393
4394         /*
4395          * 1. We can only evaluate queries that resulted in one single execution
4396          * plan
4397          */
4398         if (list_length(spi_plan->ptlist) != 1)
4399                 return;
4400
4401         plan = (Plan *) linitial(spi_plan->ptlist);
4402
4403         /*
4404          * 2. It must be a RESULT plan --> no scan's required
4405          */
4406         if (plan == NULL)                       /* utility statement produces this */
4407                 return;
4408
4409         if (!IsA(plan, Result))
4410                 return;
4411
4412         /*
4413          * 3. Can't have any subplan or qual clause, either
4414          */
4415         if (plan->lefttree != NULL ||
4416                 plan->righttree != NULL ||
4417                 plan->initPlan != NULL ||
4418                 plan->qual != NULL ||
4419                 ((Result *) plan)->resconstantqual != NULL)
4420                 return;
4421
4422         /*
4423          * 4. The plan must have a single attribute as result
4424          */
4425         if (list_length(plan->targetlist) != 1)
4426                 return;
4427
4428         tle = (TargetEntry *) linitial(plan->targetlist);
4429
4430         /*
4431          * 5. Check that all the nodes in the expression are non-scary.
4432          */
4433         if (!exec_simple_check_node((Node *) tle->expr))
4434                 return;
4435
4436         /*
4437          * Yes - this is a simple expression.  Mark it as such, and initialize
4438          * state to "not valid in current transaction".
4439          */
4440         expr->expr_simple_expr = tle->expr;
4441         expr->expr_simple_state = NULL;
4442         expr->expr_simple_xid = InvalidTransactionId;
4443         /* Also stash away the expression result type */
4444         expr->expr_simple_type = exprType((Node *) tle->expr);
4445 }
4446
4447 /*
4448  * Check two tupledescs have matching number and types of attributes
4449  */
4450 static bool
4451 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4452 {
4453         int                     i;
4454
4455         if (td1->natts != td2->natts)
4456                 return false;
4457
4458         for (i = 0; i < td1->natts; i++)
4459         {
4460                 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4461                         return false;
4462         }
4463
4464         return true;
4465 }
4466
4467 /* ----------
4468  * exec_set_found                       Set the global found variable
4469  *                                      to true/false
4470  * ----------
4471  */
4472 static void
4473 exec_set_found(PLpgSQL_execstate *estate, bool state)
4474 {
4475         PLpgSQL_var *var;
4476
4477         var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4478         var->value = (Datum) state;
4479         var->isnull = false;
4480 }
4481
4482 /*
4483  * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
4484  *
4485  * If a simple_eval_estate was created in the current transaction,
4486  * it has to be cleaned up.
4487  *
4488  * XXX Do we need to do anything at subtransaction events?
4489  * Maybe subtransactions need to have their own simple_eval_estate?
4490  * It would get a lot messier, so for now let's assume we don't need that.
4491  */
4492 void
4493 plpgsql_xact_cb(XactEvent event, void *arg)
4494 {
4495         /*
4496          * If we are doing a clean transaction shutdown, free the EState (so that
4497          * any remaining resources will be released correctly). In an abort, we
4498          * expect the regular abort recovery procedures to release everything of
4499          * interest.
4500          */
4501         if (event == XACT_EVENT_COMMIT && simple_eval_estate)
4502                 FreeExecutorState(simple_eval_estate);
4503         simple_eval_estate = NULL;
4504 }
4505
4506 static void
4507 free_var(PLpgSQL_var *var)
4508 {
4509         if (var->freeval)
4510         {
4511                 pfree(DatumGetPointer(var->value));
4512                 var->freeval = false;
4513         }
4514 }