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