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