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