OSDN Git Service

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