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