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