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