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