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