]> granicus.if.org Git - postgresql/blobdiff - src/pl/plpgsql/src/pl_exec.c
pgindent run for 9.0, second run
[postgresql] / src / pl / plpgsql / src / pl_exec.c
index 25702f2a8785aaa006c9c8b5242566cdcb816eb1..e1f48e3d75d55cdef7f700b40c0839787923d41c 100644 (file)
@@ -3,67 +3,77 @@
  * pl_exec.c           - Executor for the PL/pgSQL
  *                       procedural language
  *
- * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
  * Portions Copyright (c) 1994, Regents of the University of California
  *
  *
  * IDENTIFICATION
- *       $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.203 2008/03/25 19:26:54 neilc Exp $
+ *       $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.261 2010/07/06 19:19:01 momjian Exp $
  *
  *-------------------------------------------------------------------------
  */
 
 #include "plpgsql.h"
-#include "pl.tab.h"
 
 #include <ctype.h>
 
-#include "access/heapam.h"
 #include "access/transam.h"
+#include "access/tupconvert.h"
 #include "catalog/pg_proc.h"
 #include "catalog/pg_type.h"
 #include "executor/spi_priv.h"
 #include "funcapi.h"
-#include "optimizer/clauses.h"
-#include "parser/parse_expr.h"
+#include "miscadmin.h"
+#include "nodes/nodeFuncs.h"
 #include "parser/scansup.h"
+#include "storage/proc.h"
 #include "tcop/tcopprot.h"
 #include "utils/array.h"
 #include "utils/builtins.h"
+#include "utils/datum.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
+#include "utils/snapmgr.h"
 #include "utils/typcache.h"
 
 
 static const char *const raise_skip_msg = "RAISE";
 
+typedef struct
+{
+       int                     nargs;                  /* number of arguments */
+       Oid                *types;                      /* types of arguments */
+       Datum      *values;                     /* evaluated argument values */
+       char       *nulls;                      /* null markers (' '/'n' style) */
+       bool       *freevals;           /* which arguments are pfree-able */
+} PreparedParamsData;
+
 /*
  * All plpgsql function executions within a single transaction share the same
  * executor EState for evaluating "simple" expressions.  Each function call
  * creates its own "eval_econtext" ExprContext within this estate for
  * per-evaluation workspace.  eval_econtext is freed at normal function exit,
  * and the EState is freed at transaction end (in case of error, we assume
- * that the abort mechanisms clean it all up). In order to be sure
- * ExprContext callbacks are handled properly, each subtransaction has to have
- * its own such EState; hence we need a stack. We use a simple counter to
- * distinguish different instantiations of the EState, so that we can tell
- * whether we have a current copy of a prepared expression.
+ * that the abort mechanisms clean it all up). Furthermore, any exception
+ * block within a function has to have its own eval_econtext separate from
+ * the containing function's, so that we can clean up ExprContext callbacks
+ * properly at subtransaction exit.  We maintain a stack that tracks the
+ * individual econtexts so that we can clean up correctly at subxact exit.
  *
  * This arrangement is a bit tedious to maintain, but it's worth the trouble
  * so that we don't have to re-prepare simple expressions on each trip through
  * a function. (We assume the case to optimize is many repetitions of a
  * function within a transaction.)
  */
-typedef struct SimpleEstateStackEntry
+typedef struct SimpleEcontextStackEntry
 {
-       EState     *xact_eval_estate;           /* EState for current xact level */
-       long int        xact_estate_simple_id;  /* ID for xact_eval_estate */
+       ExprContext *stack_econtext;    /* a stacked econtext */
        SubTransactionId xact_subxid;           /* ID for current subxact */
-       struct SimpleEstateStackEntry *next;            /* next stack entry up */
-} SimpleEstateStackEntry;
+       struct SimpleEcontextStackEntry *next;          /* next stack entry up */
+} SimpleEcontextStackEntry;
 
-static SimpleEstateStackEntry *simple_estate_stack = NULL;
-static long int simple_estate_id_counter = 0;
+static EState *simple_eval_estate = NULL;
+static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
 
 /************************************************************
  * Local function forward declarations
@@ -85,6 +95,8 @@ static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
                                  PLpgSQL_stmt_getdiag *stmt);
 static int exec_stmt_if(PLpgSQL_execstate *estate,
                         PLpgSQL_stmt_if *stmt);
+static int exec_stmt_case(PLpgSQL_execstate *estate,
+                          PLpgSQL_stmt_case *stmt);
 static int exec_stmt_loop(PLpgSQL_execstate *estate,
                           PLpgSQL_stmt_loop *stmt);
 static int exec_stmt_while(PLpgSQL_execstate *estate,
@@ -93,6 +105,8 @@ static int exec_stmt_fori(PLpgSQL_execstate *estate,
                           PLpgSQL_stmt_fori *stmt);
 static int exec_stmt_fors(PLpgSQL_execstate *estate,
                           PLpgSQL_stmt_fors *stmt);
+static int exec_stmt_forc(PLpgSQL_execstate *estate,
+                          PLpgSQL_stmt_forc *stmt);
 static int exec_stmt_open(PLpgSQL_execstate *estate,
                           PLpgSQL_stmt_open *stmt);
 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
@@ -139,7 +153,6 @@ static void exec_assign_value(PLpgSQL_execstate *estate,
                                  Datum value, Oid valtype, bool *isNull);
 static void exec_eval_datum(PLpgSQL_execstate *estate,
                                PLpgSQL_datum *datum,
-                               Oid expectedtypeid,
                                Oid *typeid,
                                Datum *value,
                                bool *isnull);
@@ -155,6 +168,11 @@ static Datum exec_eval_expr(PLpgSQL_execstate *estate,
                           Oid *rettype);
 static int exec_run_select(PLpgSQL_execstate *estate,
                                PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
+static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
+                          Portal portal, bool prefetch_ok);
+static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
+                                PLpgSQL_expr *expr);
+static void plpgsql_param_fetch(ParamListInfo params, int paramid);
 static void exec_move_row(PLpgSQL_execstate *estate,
                          PLpgSQL_rec *rec,
                          PLpgSQL_row *row,
@@ -173,10 +191,17 @@ static Datum exec_simple_cast_value(Datum value, Oid valtype,
                                           Oid reqtype, int32 reqtypmod,
                                           bool isnull);
 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
-static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
+static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
 static void free_var(PLpgSQL_var *var);
+static void assign_text_var(PLpgSQL_var *var, const char *str);
+static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
+                                          List *params);
+static void free_params_data(PreparedParamsData *ppd);
+static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
+                                                 PLpgSQL_expr *dynquery, List *params,
+                                                 const char *portalname, int cursorOptions);
 
 
 /* ----------
@@ -295,13 +320,17 @@ plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
                estate.err_text = NULL;
 
                /*
-                * Provide a more helpful message if a CONTINUE has been used outside
-                * a loop.
+                * Provide a more helpful message if a CONTINUE or RAISE has been used
+                * outside the context it can work in.
                 */
                if (rc == PLPGSQL_RC_CONTINUE)
                        ereport(ERROR,
                                        (errcode(ERRCODE_SYNTAX_ERROR),
                                         errmsg("CONTINUE cannot be used outside a loop")));
+               else if (rc == PLPGSQL_RC_RERAISE)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                        errmsg("RAISE without parameters cannot be used outside an exception handler")));
                else
                        ereport(ERROR,
                           (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
@@ -353,17 +382,21 @@ plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
                         * expected result type.  XXX would be better to cache the tupdesc
                         * instead of repeating get_call_result_type()
                         */
+                       HeapTuple       rettup = (HeapTuple) DatumGetPointer(estate.retval);
                        TupleDesc       tupdesc;
+                       TupleConversionMap *tupmap;
 
                        switch (get_call_result_type(fcinfo, NULL, &tupdesc))
                        {
                                case TYPEFUNC_COMPOSITE:
                                        /* got the expected result rowtype, now check it */
-                                       if (estate.rettupdesc == NULL ||
-                                               !compatible_tupdesc(estate.rettupdesc, tupdesc))
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_DATATYPE_MISMATCH),
-                                                                errmsg("returned record type does not match expected record type")));
+                                       tupmap = convert_tuples_by_position(estate.rettupdesc,
+                                                                                                               tupdesc,
+                                                                                                               gettext_noop("returned record type does not match expected record type"));
+                                       /* it might need conversion */
+                                       if (tupmap)
+                                               rettup = do_convert_tuple(rettup, tupmap);
+                                       /* no need to free map, we're about to return anyway */
                                        break;
                                case TYPEFUNC_RECORD:
 
@@ -388,9 +421,7 @@ plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
                         * Copy tuple to upper executor memory, as a tuple Datum. Make
                         * sure it is labeled with the caller-supplied tuple type.
                         */
-                       estate.retval =
-                               PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
-                                                                                               tupdesc));
+                       estate.retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
                }
                else
                {
@@ -428,8 +459,7 @@ plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
                ((*plugin_ptr)->func_end) (&estate, func);
 
        /* Clean up any leftover temporary memory */
-       FreeExprContext(estate.eval_econtext);
-       estate.eval_econtext = NULL;
+       plpgsql_destroy_econtext(&estate);
        exec_eval_cleanup(&estate);
 
        /*
@@ -484,12 +514,20 @@ plpgsql_exec_trigger(PLpgSQL_function *func,
 
        /*
         * Put the OLD and NEW tuples into record variables
+        *
+        * We make the tupdescs available in both records even though only one may
+        * have a value.  This allows parsing of record references to succeed in
+        * functions that are used for multiple trigger types.  For example, we
+        * might have a test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')",
+        * which should parse regardless of the current trigger type.
         */
        rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
        rec_new->freetup = false;
+       rec_new->tupdesc = trigdata->tg_relation->rd_att;
        rec_new->freetupdesc = false;
        rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
        rec_old->freetup = false;
+       rec_old->tupdesc = trigdata->tg_relation->rd_att;
        rec_old->freetupdesc = false;
 
        if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
@@ -498,30 +536,22 @@ plpgsql_exec_trigger(PLpgSQL_function *func,
                 * Per-statement triggers don't use OLD/NEW variables
                 */
                rec_new->tup = NULL;
-               rec_new->tupdesc = NULL;
                rec_old->tup = NULL;
-               rec_old->tupdesc = NULL;
        }
        else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
        {
                rec_new->tup = trigdata->tg_trigtuple;
-               rec_new->tupdesc = trigdata->tg_relation->rd_att;
                rec_old->tup = NULL;
-               rec_old->tupdesc = NULL;
        }
        else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
        {
                rec_new->tup = trigdata->tg_newtuple;
-               rec_new->tupdesc = trigdata->tg_relation->rd_att;
                rec_old->tup = trigdata->tg_trigtuple;
-               rec_old->tupdesc = trigdata->tg_relation->rd_att;
        }
        else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
        {
                rec_new->tup = NULL;
-               rec_new->tupdesc = NULL;
                rec_old->tup = trigdata->tg_trigtuple;
-               rec_old->tupdesc = trigdata->tg_relation->rd_att;
        }
        else
                elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
@@ -532,13 +562,15 @@ plpgsql_exec_trigger(PLpgSQL_function *func,
 
        var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
        if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
-               var->value = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
+               var->value = CStringGetTextDatum("INSERT");
        else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
-               var->value = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
+               var->value = CStringGetTextDatum("UPDATE");
        else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
-               var->value = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
+               var->value = CStringGetTextDatum("DELETE");
+       else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
+               var->value = CStringGetTextDatum("TRUNCATE");
        else
-               elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
+               elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
        var->isnull = false;
        var->freeval = true;
 
@@ -550,9 +582,9 @@ plpgsql_exec_trigger(PLpgSQL_function *func,
 
        var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
        if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
-               var->value = DirectFunctionCall1(textin, CStringGetDatum("BEFORE"));
+               var->value = CStringGetTextDatum("BEFORE");
        else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
-               var->value = DirectFunctionCall1(textin, CStringGetDatum("AFTER"));
+               var->value = CStringGetTextDatum("AFTER");
        else
                elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
        var->isnull = false;
@@ -560,9 +592,9 @@ plpgsql_exec_trigger(PLpgSQL_function *func,
 
        var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
        if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
-               var->value = DirectFunctionCall1(textin, CStringGetDatum("ROW"));
+               var->value = CStringGetTextDatum("ROW");
        else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
-               var->value = DirectFunctionCall1(textin, CStringGetDatum("STATEMENT"));
+               var->value = CStringGetTextDatum("STATEMENT");
        else
                elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
        var->isnull = false;
@@ -599,20 +631,36 @@ plpgsql_exec_trigger(PLpgSQL_function *func,
        var->isnull = false;
        var->freeval = false;
 
-       /*
-        * Store the trigger argument values into the special execution state
-        * variables
-        */
-       estate.err_text = gettext_noop("while storing call arguments into local variables");
-       estate.trig_nargs = trigdata->tg_trigger->tgnargs;
-       if (estate.trig_nargs == 0)
-               estate.trig_argv = NULL;
+       var = (PLpgSQL_var *) (estate.datums[func->tg_argv_varno]);
+       if (trigdata->tg_trigger->tgnargs > 0)
+       {
+               /*
+                * For historical reasons, tg_argv[] subscripts start at zero not one.
+                * So we can't use construct_array().
+                */
+               int                     nelems = trigdata->tg_trigger->tgnargs;
+               Datum      *elems;
+               int                     dims[1];
+               int                     lbs[1];
+
+               elems = palloc(sizeof(Datum) * nelems);
+               for (i = 0; i < nelems; i++)
+                       elems[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
+               dims[0] = nelems;
+               lbs[0] = 0;
+
+               var->value = PointerGetDatum(construct_md_array(elems, NULL,
+                                                                                                               1, dims, lbs,
+                                                                                                               TEXTOID,
+                                                                                                               -1, false, 'i'));
+               var->isnull = false;
+               var->freeval = true;
+       }
        else
        {
-               estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
-               for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
-                       estate.trig_argv[i] = DirectFunctionCall1(textin,
-                                                  CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
+               var->value = (Datum) 0;
+               var->isnull = true;
+               var->freeval = false;
        }
 
        estate.err_text = gettext_noop("during function entry");
@@ -640,13 +688,17 @@ plpgsql_exec_trigger(PLpgSQL_function *func,
                estate.err_text = NULL;
 
                /*
-                * Provide a more helpful message if a CONTINUE has been used outside
-                * a loop.
+                * Provide a more helpful message if a CONTINUE or RAISE has been used
+                * outside the context it can work in.
                 */
                if (rc == PLPGSQL_RC_CONTINUE)
                        ereport(ERROR,
                                        (errcode(ERRCODE_SYNTAX_ERROR),
                                         errmsg("CONTINUE cannot be used outside a loop")));
+               else if (rc == PLPGSQL_RC_RERAISE)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                        errmsg("RAISE without parameters cannot be used outside an exception handler")));
                else
                        ereport(ERROR,
                           (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
@@ -675,13 +727,20 @@ plpgsql_exec_trigger(PLpgSQL_function *func,
                rettup = NULL;
        else
        {
-               if (!compatible_tupdesc(estate.rettupdesc,
-                                                               trigdata->tg_relation->rd_att))
-                       ereport(ERROR,
-                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
-                                        errmsg("returned tuple structure does not match table of trigger event")));
+               TupleConversionMap *tupmap;
+
+               rettup = (HeapTuple) DatumGetPointer(estate.retval);
+               /* check rowtype compatibility */
+               tupmap = convert_tuples_by_position(estate.rettupdesc,
+                                                                                       trigdata->tg_relation->rd_att,
+                                                                                       gettext_noop("returned row structure does not match the structure of the triggering table"));
+               /* it might need conversion */
+               if (tupmap)
+                       rettup = do_convert_tuple(rettup, tupmap);
+               /* no need to free map, we're about to return anyway */
+
                /* Copy tuple to upper executor memory */
-               rettup = SPI_copytuple((HeapTuple) (estate.retval));
+               rettup = SPI_copytuple(rettup);
        }
 
        /*
@@ -691,8 +750,7 @@ plpgsql_exec_trigger(PLpgSQL_function *func,
                ((*plugin_ptr)->func_end) (&estate, func);
 
        /* Clean up any leftover temporary memory */
-       FreeExprContext(estate.eval_econtext);
-       estate.eval_econtext = NULL;
+       plpgsql_destroy_econtext(&estate);
        exec_eval_cleanup(&estate);
 
        /*
@@ -715,10 +773,6 @@ plpgsql_exec_error_callback(void *arg)
 {
        PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
 
-       /* safety check, shouldn't happen */
-       if (estate->err_func == NULL)
-               return;
-
        /* if we are doing RAISE, don't report its location */
        if (estate->err_text == raise_skip_msg)
                return;
@@ -743,9 +797,9 @@ plpgsql_exec_error_callback(void *arg)
                         * local variable initialization"
                         */
                        errcontext("PL/pgSQL function \"%s\" line %d %s",
-                                          estate->err_func->fn_name,
+                                          estate->func->fn_name,
                                           estate->err_stmt->lineno,
-                                          gettext(estate->err_text));
+                                          _(estate->err_text));
                }
                else
                {
@@ -754,21 +808,21 @@ plpgsql_exec_error_callback(void *arg)
                         * arguments into local variables"
                         */
                        errcontext("PL/pgSQL function \"%s\" %s",
-                                          estate->err_func->fn_name,
-                                          gettext(estate->err_text));
+                                          estate->func->fn_name,
+                                          _(estate->err_text));
                }
        }
        else if (estate->err_stmt != NULL)
        {
                /* translator: last %s is a plpgsql statement type name */
                errcontext("PL/pgSQL function \"%s\" line %d at %s",
-                                  estate->err_func->fn_name,
+                                  estate->func->fn_name,
                                   estate->err_stmt->lineno,
                                   plpgsql_stmt_typename(estate->err_stmt));
        }
        else
                errcontext("PL/pgSQL function \"%s\"",
-                                  estate->err_func->fn_name);
+                                  estate->func->fn_name);
 }
 
 
@@ -815,7 +869,6 @@ copy_plpgsql_datum(PLpgSQL_datum *datum)
                case PLPGSQL_DTYPE_ROW:
                case PLPGSQL_DTYPE_RECFIELD:
                case PLPGSQL_DTYPE_ARRAYELEM:
-               case PLPGSQL_DTYPE_TRIGARG:
 
                        /*
                         * These datum records are read-only at runtime, so no need to
@@ -936,10 +989,13 @@ exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
                                        if (rec->freetup)
                                        {
                                                heap_freetuple(rec->tup);
-                                               FreeTupleDesc(rec->tupdesc);
                                                rec->freetup = false;
                                        }
-
+                                       if (rec->freetupdesc)
+                                       {
+                                               FreeTupleDesc(rec->tupdesc);
+                                               rec->freetupdesc = false;
+                                       }
                                        rec->tup = NULL;
                                        rec->tupdesc = NULL;
                                }
@@ -963,8 +1019,6 @@ exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
                MemoryContext oldcontext = CurrentMemoryContext;
                ResourceOwner oldowner = CurrentResourceOwner;
                ExprContext *old_eval_econtext = estate->eval_econtext;
-               EState     *old_eval_estate = estate->eval_estate;
-               long int        old_eval_estate_simple_id = estate->eval_estate_simple_id;
 
                estate->err_text = gettext_noop("during statement block entry");
 
@@ -1013,10 +1067,11 @@ exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
                        MemoryContextSwitchTo(oldcontext);
                        CurrentResourceOwner = oldowner;
 
-                       /* Revert to outer eval_econtext */
+                       /*
+                        * Revert to outer eval_econtext.  (The inner one was
+                        * automatically cleaned up during subxact exit.)
+                        */
                        estate->eval_econtext = old_eval_econtext;
-                       estate->eval_estate = old_eval_estate;
-                       estate->eval_estate_simple_id = old_eval_estate_simple_id;
 
                        /*
                         * AtEOSubXact_SPI() should not have popped any SPI context, but
@@ -1043,8 +1098,6 @@ exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
 
                        /* Revert to outer eval_econtext */
                        estate->eval_econtext = old_eval_econtext;
-                       estate->eval_estate = old_eval_estate;
-                       estate->eval_estate_simple_id = old_eval_estate_simple_id;
 
                        /*
                         * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
@@ -1070,17 +1123,12 @@ exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
 
                                        state_var = (PLpgSQL_var *)
                                                estate->datums[block->exceptions->sqlstate_varno];
-                                       state_var->value = DirectFunctionCall1(textin,
-                                          CStringGetDatum(unpack_sql_state(edata->sqlerrcode)));
-                                       state_var->freeval = true;
-                                       state_var->isnull = false;
-
                                        errm_var = (PLpgSQL_var *)
                                                estate->datums[block->exceptions->sqlerrm_varno];
-                                       errm_var->value = DirectFunctionCall1(textin,
-                                                                                       CStringGetDatum(edata->message));
-                                       errm_var->freeval = true;
-                                       errm_var->isnull = false;
+
+                                       assign_text_var(state_var,
+                                                                       unpack_sql_state(edata->sqlerrcode));
+                                       assign_text_var(errm_var, edata->message);
 
                                        estate->err_text = NULL;
 
@@ -1088,8 +1136,15 @@ exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
 
                                        free_var(state_var);
                                        state_var->value = (Datum) 0;
+                                       state_var->isnull = true;
                                        free_var(errm_var);
                                        errm_var->value = (Datum) 0;
+                                       errm_var->isnull = true;
+
+                                       /* re-throw error if requested by handler */
+                                       if (rc == PLPGSQL_RC_RERAISE)
+                                               ReThrowError(edata);
+
                                        break;
                                }
                        }
@@ -1120,16 +1175,22 @@ exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
        switch (rc)
        {
                case PLPGSQL_RC_OK:
-               case PLPGSQL_RC_CONTINUE:
                case PLPGSQL_RC_RETURN:
+               case PLPGSQL_RC_CONTINUE:
+               case PLPGSQL_RC_RERAISE:
                        return rc;
 
                case PLPGSQL_RC_EXIT:
+
+                       /*
+                        * This is intentionally different from the handling of RC_EXIT
+                        * for loops: to match a block, we require a match by label.
+                        */
                        if (estate->exitlabel == NULL)
-                               return PLPGSQL_RC_OK;
+                               return PLPGSQL_RC_EXIT;
                        if (block->label == NULL)
                                return PLPGSQL_RC_EXIT;
-                       if (strcmp(block->label, estate->exitlabel))
+                       if (strcmp(block->label, estate->exitlabel) != 0)
                                return PLPGSQL_RC_EXIT;
                        estate->exitlabel = NULL;
                        return PLPGSQL_RC_OK;
@@ -1196,7 +1257,7 @@ exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
 
        CHECK_FOR_INTERRUPTS();
 
-       switch (stmt->cmd_type)
+       switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
        {
                case PLPGSQL_STMT_BLOCK:
                        rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
@@ -1218,6 +1279,10 @@ exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
                        rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
                        break;
 
+               case PLPGSQL_STMT_CASE:
+                       rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
+                       break;
+
                case PLPGSQL_STMT_LOOP:
                        rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
                        break;
@@ -1234,6 +1299,10 @@ exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
                        rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
                        break;
 
+               case PLPGSQL_STMT_FORC:
+                       rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
+                       break;
+
                case PLPGSQL_STMT_EXIT:
                        rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
                        break;
@@ -1405,6 +1474,90 @@ exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
 }
 
 
+/*-----------
+ * exec_stmt_case
+ *-----------
+ */
+static int
+exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
+{
+       PLpgSQL_var *t_var = NULL;
+       bool            isnull;
+       ListCell   *l;
+
+       if (stmt->t_expr != NULL)
+       {
+               /* simple case */
+               Datum           t_val;
+               Oid                     t_oid;
+
+               t_val = exec_eval_expr(estate, stmt->t_expr, &isnull, &t_oid);
+
+               t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
+
+               /*
+                * When expected datatype is different from real, change it. Note that
+                * what we're modifying here is an execution copy of the datum, so
+                * this doesn't affect the originally stored function parse tree.
+                */
+               if (t_var->datatype->typoid != t_oid)
+                       t_var->datatype = plpgsql_build_datatype(t_oid, -1);
+
+               /* now we can assign to the variable */
+               exec_assign_value(estate,
+                                                 (PLpgSQL_datum *) t_var,
+                                                 t_val,
+                                                 t_oid,
+                                                 &isnull);
+
+               exec_eval_cleanup(estate);
+       }
+
+       /* Now search for a successful WHEN clause */
+       foreach(l, stmt->case_when_list)
+       {
+               PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
+               bool            value;
+
+               value = exec_eval_boolean(estate, cwt->expr, &isnull);
+               exec_eval_cleanup(estate);
+               if (!isnull && value)
+               {
+                       /* Found it */
+
+                       /* We can now discard any value we had for the temp variable */
+                       if (t_var != NULL)
+                       {
+                               free_var(t_var);
+                               t_var->value = (Datum) 0;
+                               t_var->isnull = true;
+                       }
+
+                       /* Evaluate the statement(s), and we're done */
+                       return exec_stmts(estate, cwt->stmts);
+               }
+       }
+
+       /* We can now discard any value we had for the temp variable */
+       if (t_var != NULL)
+       {
+               free_var(t_var);
+               t_var->value = (Datum) 0;
+               t_var->isnull = true;
+       }
+
+       /* SQL2003 mandates this error if there was no ELSE clause */
+       if (!stmt->have_else)
+               ereport(ERROR,
+                               (errcode(ERRCODE_CASE_NOT_FOUND),
+                                errmsg("case not found"),
+                                errhint("CASE statement is missing ELSE part.")));
+
+       /* Evaluate the ELSE statements, and we're done */
+       return exec_stmts(estate, stmt->else_stmts);
+}
+
+
 /* ----------
  * exec_stmt_loop                      Loop over statements until
  *                                     an exit occurs.
@@ -1446,7 +1599,8 @@ exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
                                break;
 
                        case PLPGSQL_RC_RETURN:
-                               return PLPGSQL_RC_RETURN;
+                       case PLPGSQL_RC_RERAISE:
+                               return rc;
 
                        default:
                                elog(ERROR, "unrecognized rc: %d", rc);
@@ -1490,7 +1644,7 @@ exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
                                        return PLPGSQL_RC_OK;
                                if (stmt->label == NULL)
                                        return PLPGSQL_RC_EXIT;
-                               if (strcmp(stmt->label, estate->exitlabel))
+                               if (strcmp(stmt->label, estate->exitlabel) != 0)
                                        return PLPGSQL_RC_EXIT;
                                estate->exitlabel = NULL;
                                return PLPGSQL_RC_OK;
@@ -1509,7 +1663,8 @@ exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
                                break;
 
                        case PLPGSQL_RC_RETURN:
-                               return PLPGSQL_RC_RETURN;
+                       case PLPGSQL_RC_RERAISE:
+                               return rc;
 
                        default:
                                elog(ERROR, "unrecognized rc: %d", rc);
@@ -1539,7 +1694,7 @@ exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
        bool            found = false;
        int                     rc = PLPGSQL_RC_OK;
 
-       var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
+       var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
 
        /*
         * Get the value of the lower bound
@@ -1552,7 +1707,7 @@ exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
        if (isnull)
                ereport(ERROR,
                                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                errmsg("lower bound of FOR loop cannot be NULL")));
+                                errmsg("lower bound of FOR loop cannot be null")));
        loop_value = DatumGetInt32(value);
        exec_eval_cleanup(estate);
 
@@ -1567,7 +1722,7 @@ exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
        if (isnull)
                ereport(ERROR,
                                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                errmsg("upper bound of FOR loop cannot be NULL")));
+                                errmsg("upper bound of FOR loop cannot be null")));
        end_value = DatumGetInt32(value);
        exec_eval_cleanup(estate);
 
@@ -1584,7 +1739,7 @@ exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
                if (isnull)
                        ereport(ERROR,
                                        (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                        errmsg("BY value of FOR loop cannot be NULL")));
+                                        errmsg("BY value of FOR loop cannot be null")));
                step_value = DatumGetInt32(value);
                exec_eval_cleanup(estate);
                if (step_value <= 0)
@@ -1627,8 +1782,9 @@ exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
                 */
                rc = exec_stmts(estate, stmt->body);
 
-               if (rc == PLPGSQL_RC_RETURN)
-                       break;                          /* return from function */
+               if (rc == PLPGSQL_RC_RETURN ||
+                       rc == PLPGSQL_RC_RERAISE)
+                       break;                          /* break out of the loop */
                else if (rc == PLPGSQL_RC_EXIT)
                {
                        if (estate->exitlabel == NULL)
@@ -1712,145 +1868,154 @@ exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
 static int
 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
 {
-       PLpgSQL_rec *rec = NULL;
-       PLpgSQL_row *row = NULL;
-       SPITupleTable *tuptab;
        Portal          portal;
-       bool            found = false;
-       int                     rc = PLPGSQL_RC_OK;
-       int                     i;
-       int                     n;
+       int                     rc;
 
        /*
-        * Determine if we assign to a record or a row
+        * Open the implicit cursor for the statement using exec_run_select
         */
-       if (stmt->rec != NULL)
-               rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
-       else if (stmt->row != NULL)
-               row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
-       else
-               elog(ERROR, "unsupported target");
+       exec_run_select(estate, stmt->query, 0, &portal);
 
        /*
-        * Open the implicit cursor for the statement and fetch the initial 10
-        * rows.
+        * Execute the loop
         */
-       exec_run_select(estate, stmt->query, 0, &portal);
-
-       SPI_cursor_fetch(portal, true, 10);
-       tuptab = SPI_tuptable;
-       n = SPI_processed;
+       rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
 
        /*
-        * If the query didn't return any rows, set the target to NULL and return
-        * with FOUND = false.
+        * Close the implicit cursor
         */
-       if (n == 0)
-               exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
-       else
-               found = true;                   /* processed at least one tuple */
+       SPI_cursor_close(portal);
 
-       /*
-        * Now do the loop
+       return rc;
+}
+
+
+/* ----------
+ * exec_stmt_forc                      Execute a loop for each row from a cursor.
+ * ----------
+ */
+static int
+exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
+{
+       PLpgSQL_var *curvar;
+       char       *curname = NULL;
+       const char *portalname;
+       PLpgSQL_expr *query;
+       ParamListInfo paramLI;
+       Portal          portal;
+       int                     rc;
+
+       /* ----------
+        * Get the cursor variable and if it has an assigned name, check
+        * that it's not in use currently.
+        * ----------
         */
-       while (n > 0)
+       curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
+       if (!curvar->isnull)
        {
-               for (i = 0; i < n; i++)
-               {
-                       /*
-                        * Assign the tuple to the target
-                        */
-                       exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
+               curname = TextDatumGetCString(curvar->value);
+               if (SPI_cursor_find(curname) != NULL)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_DUPLICATE_CURSOR),
+                                        errmsg("cursor \"%s\" already in use", curname)));
+       }
 
-                       /*
-                        * Execute the statements
-                        */
-                       rc = exec_stmts(estate, stmt->body);
-                       if (rc != PLPGSQL_RC_OK)
-                       {
-                               if (rc == PLPGSQL_RC_EXIT)
-                               {
-                                       if (estate->exitlabel == NULL)
-                                               /* unlabelled exit, finish the current loop */
-                                               rc = PLPGSQL_RC_OK;
-                                       else if (stmt->label != NULL &&
-                                                        strcmp(stmt->label, estate->exitlabel) == 0)
-                                       {
-                                               /* labelled exit, matches the current stmt's label */
-                                               estate->exitlabel = NULL;
-                                               rc = PLPGSQL_RC_OK;
-                                       }
+       /* ----------
+        * Open the cursor just like an OPEN command
+        *
+        * Note: parser should already have checked that statement supplies
+        * args iff cursor needs them, but we check again to be safe.
+        * ----------
+        */
+       if (stmt->argquery != NULL)
+       {
+               /* ----------
+                * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
+                * statement to evaluate the args and put 'em into the
+                * internal row.
+                * ----------
+                */
+               PLpgSQL_stmt_execsql set_args;
 
-                                       /*
-                                        * otherwise, we processed a labelled exit that does not
-                                        * match the current statement's label, if any: return
-                                        * RC_EXIT so that the EXIT continues to recurse upward.
-                                        */
-                               }
-                               else if (rc == PLPGSQL_RC_CONTINUE)
-                               {
-                                       if (estate->exitlabel == NULL)
-                                       {
-                                               /* anonymous continue, so re-run the current loop */
-                                               rc = PLPGSQL_RC_OK;
-                                               continue;
-                                       }
-                                       else if (stmt->label != NULL &&
-                                                        strcmp(stmt->label, estate->exitlabel) == 0)
-                                       {
-                                               /* label matches named continue, so re-run loop */
-                                               rc = PLPGSQL_RC_OK;
-                                               estate->exitlabel = NULL;
-                                               continue;
-                                       }
+               if (curvar->cursor_explicit_argrow < 0)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                        errmsg("arguments given for cursor without arguments")));
+
+               memset(&set_args, 0, sizeof(set_args));
+               set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
+               set_args.lineno = stmt->lineno;
+               set_args.sqlstmt = stmt->argquery;
+               set_args.into = true;
+               /* XXX historically this has not been STRICT */
+               set_args.row = (PLpgSQL_row *)
+                       (estate->datums[curvar->cursor_explicit_argrow]);
+
+               if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
+                       elog(ERROR, "open cursor failed during argument processing");
+       }
+       else
+       {
+               if (curvar->cursor_explicit_argrow >= 0)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                        errmsg("arguments required for cursor")));
+       }
 
-                                       /*
-                                        * otherwise, we processed a named continue that does not
-                                        * match the current statement's label, if any: return
-                                        * RC_CONTINUE so that the CONTINUE will propagate up the
-                                        * stack.
-                                        */
-                               }
+       query = curvar->cursor_explicit_expr;
+       Assert(query);
 
-                               /*
-                                * We're aborting the loop, so cleanup and set FOUND. (This
-                                * code should match the code after the loop.)
-                                */
-                               SPI_freetuptable(tuptab);
-                               SPI_cursor_close(portal);
-                               exec_set_found(estate, found);
+       if (query->plan == NULL)
+               exec_prepare_plan(estate, query, curvar->cursor_options);
 
-                               return rc;
-                       }
-               }
+       /*
+        * Set up ParamListInfo (note this is only carrying a hook function, not
+        * any actual data values, at this point)
+        */
+       paramLI = setup_param_list(estate, query);
 
-               SPI_freetuptable(tuptab);
+       /*
+        * Open the cursor (the paramlist will get copied into the portal)
+        */
+       portal = SPI_cursor_open_with_paramlist(curname, query->plan,
+                                                                                       paramLI,
+                                                                                       estate->readonly_func);
+       if (portal == NULL)
+               elog(ERROR, "could not open cursor: %s",
+                        SPI_result_code_string(SPI_result));
+       portalname = portal->name;
 
-               /*
-                * Fetch the next 50 tuples
-                */
-               SPI_cursor_fetch(portal, true, 50);
-               n = SPI_processed;
-               tuptab = SPI_tuptable;
-       }
+       /* don't need paramlist any more */
+       if (paramLI)
+               pfree(paramLI);
 
        /*
-        * Release last group of tuples
+        * If cursor variable was NULL, store the generated portal name in it
         */
-       SPI_freetuptable(tuptab);
+       if (curname == NULL)
+               assign_text_var(curvar, portal->name);
 
        /*
-        * Close the implicit cursor
+        * Execute the loop.  We can't prefetch because the cursor is accessible
+        * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
         */
-       SPI_cursor_close(portal);
+       rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
 
-       /*
-        * Set the FOUND variable to indicate the result of executing the loop
-        * (namely, whether we looped one or more times). This must be set here so
-        * that it does not interfere with the value of the FOUND variable inside
-        * the loop processing itself.
+       /* ----------
+        * Close portal, and restore cursor variable if it was initially NULL.
+        * ----------
         */
-       exec_set_found(estate, found);
+       SPI_cursor_close(portal);
+
+       if (curname == NULL)
+       {
+               free_var(curvar);
+               curvar->value = (Datum) 0;
+               curvar->isnull = true;
+       }
+
+       if (curname)
+               pfree(curname);
 
        return rc;
 }
@@ -1930,7 +2095,7 @@ exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
 
                                        if (HeapTupleIsValid(rec->tup))
                                        {
-                                               estate->retval = (Datum) rec->tup;
+                                               estate->retval = PointerGetDatum(rec->tup);
                                                estate->rettupdesc = rec->tupdesc;
                                                estate->retisnull = false;
                                        }
@@ -1942,9 +2107,10 @@ exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
                                        PLpgSQL_row *row = (PLpgSQL_row *) retvar;
 
                                        Assert(row->rowtupdesc);
-                                       estate->retval = (Datum) make_tuple_from_row(estate, row,
-                                                                                                                       row->rowtupdesc);
-                                       if (estate->retval == (Datum) NULL) /* should not happen */
+                                       estate->retval =
+                                               PointerGetDatum(make_tuple_from_row(estate, row,
+                                                                                                                       row->rowtupdesc));
+                                       if (DatumGetPointer(estate->retval) == NULL)            /* should not happen */
                                                elog(ERROR, "row not compatible with its own tupdesc");
                                        estate->rettupdesc = row->rowtupdesc;
                                        estate->retisnull = false;
@@ -1965,7 +2131,7 @@ exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
                        exec_run_select(estate, stmt->expr, 1, NULL);
                        if (estate->eval_processed > 0)
                        {
-                               estate->retval = (Datum) estate->eval_tuptable->vals[0];
+                               estate->retval = PointerGetDatum(estate->eval_tuptable->vals[0]);
                                estate->rettupdesc = estate->eval_tuptable->tupdesc;
                                estate->retisnull = false;
                        }
@@ -2007,11 +2173,10 @@ static int
 exec_stmt_return_next(PLpgSQL_execstate *estate,
                                          PLpgSQL_stmt_return_next *stmt)
 {
-       TupleDesc               tupdesc;
-       int                             natts;
-       MemoryContext   oldcxt;
-       HeapTuple               tuple = NULL;
-       bool                    free_tuple = false;
+       TupleDesc       tupdesc;
+       int                     natts;
+       HeapTuple       tuple = NULL;
+       bool            free_tuple = false;
 
        if (!estate->retisset)
                ereport(ERROR,
@@ -2049,28 +2214,33 @@ exec_stmt_return_next(PLpgSQL_execstate *estate,
                                                                                                tupdesc->attrs[0]->atttypmod,
                                                                                                        isNull);
 
-                                       oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
                                        tuplestore_putvalues(estate->tuple_store, tupdesc,
                                                                                 &retval, &isNull);
-                                       MemoryContextSwitchTo(oldcxt);
                                }
                                break;
 
                        case PLPGSQL_DTYPE_REC:
                                {
                                        PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
+                                       TupleConversionMap *tupmap;
 
                                        if (!HeapTupleIsValid(rec->tup))
                                                ereport(ERROR,
                                                  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                                                   errmsg("record \"%s\" is not assigned yet",
                                                                  rec->refname),
-                                                  errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
-                                       if (!compatible_tupdesc(tupdesc, rec->tupdesc))
-                                               ereport(ERROR,
-                                                               (errcode(ERRCODE_DATATYPE_MISMATCH),
-                                               errmsg("wrong record type supplied in RETURN NEXT")));
+                                               errdetail("The tuple structure of a not-yet-assigned"
+                                                                 " record is indeterminate.")));
+                                       tupmap = convert_tuples_by_position(rec->tupdesc,
+                                                                                                               tupdesc,
+                                                                                                               gettext_noop("wrong record type supplied in RETURN NEXT"));
                                        tuple = rec->tup;
+                                       /* it might need conversion */
+                                       if (tupmap)
+                                       {
+                                               tuple = do_convert_tuple(tuple, tupmap);
+                                               free_conversion_map(tupmap);
+                                       }
                                }
                                break;
 
@@ -2115,10 +2285,8 @@ exec_stmt_return_next(PLpgSQL_execstate *estate,
                                                                                tupdesc->attrs[0]->atttypmod,
                                                                                isNull);
 
-               oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
                tuplestore_putvalues(estate->tuple_store, tupdesc,
                                                         &retval, &isNull);
-               MemoryContextSwitchTo(oldcxt);
 
                exec_eval_cleanup(estate);
        }
@@ -2131,9 +2299,7 @@ exec_stmt_return_next(PLpgSQL_execstate *estate,
 
        if (HeapTupleIsValid(tuple))
        {
-               oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
                tuplestore_puttuple(estate->tuple_store, tuple);
-               MemoryContextSwitchTo(oldcxt);
 
                if (free_tuple)
                        heap_freetuple(tuple);
@@ -2153,6 +2319,8 @@ exec_stmt_return_query(PLpgSQL_execstate *estate,
                                           PLpgSQL_stmt_return_query *stmt)
 {
        Portal          portal;
+       uint32          processed = 0;
+       TupleConversionMap *tupmap;
 
        if (!estate->retisset)
                ereport(ERROR,
@@ -2162,37 +2330,55 @@ exec_stmt_return_query(PLpgSQL_execstate *estate,
        if (estate->tuple_store == NULL)
                exec_init_tuple_store(estate);
 
-       exec_run_select(estate, stmt->query, 0, &portal);
+       if (stmt->query != NULL)
+       {
+               /* static query */
+               exec_run_select(estate, stmt->query, 0, &portal);
+       }
+       else
+       {
+               /* RETURN QUERY EXECUTE */
+               Assert(stmt->dynquery != NULL);
+               portal = exec_dynquery_with_params(estate, stmt->dynquery,
+                                                                                  stmt->params, NULL, 0);
+       }
 
-       if (!compatible_tupdesc(estate->rettupdesc, portal->tupDesc))
-               ereport(ERROR,
-                               (errcode(ERRCODE_DATATYPE_MISMATCH),
-                 errmsg("structure of query does not match function result type")));
+       tupmap = convert_tuples_by_position(portal->tupDesc,
+                                                                               estate->rettupdesc,
+        gettext_noop("structure of query does not match function result type"));
 
        while (true)
        {
-               MemoryContext old_cxt;
                int                     i;
 
                SPI_cursor_fetch(portal, true, 50);
                if (SPI_processed == 0)
                        break;
 
-               old_cxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
                for (i = 0; i < SPI_processed; i++)
                {
                        HeapTuple       tuple = SPI_tuptable->vals[i];
 
+                       if (tupmap)
+                               tuple = do_convert_tuple(tuple, tupmap);
                        tuplestore_puttuple(estate->tuple_store, tuple);
+                       if (tupmap)
+                               heap_freetuple(tuple);
+                       processed++;
                }
-               MemoryContextSwitchTo(old_cxt);
 
                SPI_freetuptable(SPI_tuptable);
        }
 
+       if (tupmap)
+               free_conversion_map(tupmap);
+
        SPI_freetuptable(SPI_tuptable);
        SPI_cursor_close(portal);
 
+       estate->eval_processed = processed;
+       exec_set_found(estate, processed != 0);
+
        return PLPGSQL_RC_OK;
 }
 
@@ -2201,6 +2387,7 @@ exec_init_tuple_store(PLpgSQL_execstate *estate)
 {
        ReturnSetInfo *rsi = estate->rsi;
        MemoryContext oldcxt;
+       ResourceOwner oldowner;
 
        /*
         * Check caller can handle a set result in the way we want
@@ -2212,10 +2399,22 @@ exec_init_tuple_store(PLpgSQL_execstate *estate)
                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                 errmsg("set-valued function called in context that cannot accept a set")));
 
-       estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
-
+       /*
+        * Switch to the right memory context and resource owner for storing the
+        * tuplestore for return set. If we're within a subtransaction opened for
+        * an exception-block, for example, we must still create the tuplestore in
+        * the resource owner that was active when this function was entered, and
+        * not in the subtransaction resource owner.
+        */
        oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
-       estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
+       oldowner = CurrentResourceOwner;
+       CurrentResourceOwner = estate->tuple_store_owner;
+
+       estate->tuple_store =
+               tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
+                                                         false, work_mem);
+
+       CurrentResourceOwner = oldowner;
        MemoryContextSwitchTo(oldcxt);
 
        estate->rettupdesc = rsi->expectedDesc;
@@ -2228,64 +2427,163 @@ exec_init_tuple_store(PLpgSQL_execstate *estate)
 static int
 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
 {
-       char       *cp;
-       PLpgSQL_dstring ds;
-       ListCell   *current_param;
+       int                     err_code = 0;
+       char       *condname = NULL;
+       char       *err_message = NULL;
+       char       *err_detail = NULL;
+       char       *err_hint = NULL;
+       ListCell   *lc;
 
-       plpgsql_dstring_init(&ds);
-       current_param = list_head(stmt->params);
+       /* RAISE with no parameters: re-throw current exception */
+       if (stmt->condname == NULL && stmt->message == NULL &&
+               stmt->options == NIL)
+               return PLPGSQL_RC_RERAISE;
 
-       for (cp = stmt->message; *cp; cp++)
+       if (stmt->condname)
        {
-               /*
-                * Occurrences of a single % are replaced by the next parameter's
-                * external representation. Double %'s are converted to one %.
-                */
-               if (cp[0] == '%')
-               {
-                       Oid                     paramtypeid;
-                       Datum           paramvalue;
-                       bool            paramisnull;
-                       char       *extval;
+               err_code = plpgsql_recognize_err_condition(stmt->condname, true);
+               condname = pstrdup(stmt->condname);
+       }
+
+       if (stmt->message)
+       {
+               StringInfoData ds;
+               ListCell   *current_param;
+               char       *cp;
+
+               initStringInfo(&ds);
+               current_param = list_head(stmt->params);
 
-                       if (cp[1] == '%')
+               for (cp = stmt->message; *cp; cp++)
+               {
+                       /*
+                        * Occurrences of a single % are replaced by the next parameter's
+                        * external representation. Double %'s are converted to one %.
+                        */
+                       if (cp[0] == '%')
                        {
-                               plpgsql_dstring_append_char(&ds, cp[1]);
-                               cp++;
-                               continue;
-                       }
+                               Oid                     paramtypeid;
+                               Datum           paramvalue;
+                               bool            paramisnull;
+                               char       *extval;
 
-                       if (current_param == NULL)
-                               ereport(ERROR,
-                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                errmsg("too few parameters specified for RAISE")));
+                               if (cp[1] == '%')
+                               {
+                                       appendStringInfoChar(&ds, '%');
+                                       cp++;
+                                       continue;
+                               }
 
-                       paramvalue = exec_eval_expr(estate,
+                               if (current_param == NULL)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                 errmsg("too few parameters specified for RAISE")));
+
+                               paramvalue = exec_eval_expr(estate,
                                                                          (PLpgSQL_expr *) lfirst(current_param),
-                                                                               &paramisnull,
-                                                                               &paramtypeid);
+                                                                                       &paramisnull,
+                                                                                       &paramtypeid);
 
-                       if (paramisnull)
-                               extval = "<NULL>";
+                               if (paramisnull)
+                                       extval = "<NULL>";
+                               else
+                                       extval = convert_value_to_string(paramvalue, paramtypeid);
+                               appendStringInfoString(&ds, extval);
+                               current_param = lnext(current_param);
+                               exec_eval_cleanup(estate);
+                       }
                        else
-                               extval = convert_value_to_string(paramvalue, paramtypeid);
-                       plpgsql_dstring_append(&ds, extval);
-                       current_param = lnext(current_param);
-                       exec_eval_cleanup(estate);
-                       continue;
+                               appendStringInfoChar(&ds, cp[0]);
                }
 
-               plpgsql_dstring_append_char(&ds, cp[0]);
+               /*
+                * If more parameters were specified than were required to process the
+                * format string, throw an error
+                */
+               if (current_param != NULL)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                        errmsg("too many parameters specified for RAISE")));
+
+               err_message = ds.data;
+               /* No pfree(ds.data), the pfree(err_message) does it */
        }
 
-       /*
-        * If more parameters were specified than were required to process the
-        * format string, throw an error
-        */
-       if (current_param != NULL)
-               ereport(ERROR,
-                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                errmsg("too many parameters specified for RAISE")));
+       foreach(lc, stmt->options)
+       {
+               PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
+               Datum           optionvalue;
+               bool            optionisnull;
+               Oid                     optiontypeid;
+               char       *extval;
+
+               optionvalue = exec_eval_expr(estate, opt->expr,
+                                                                        &optionisnull,
+                                                                        &optiontypeid);
+               if (optionisnull)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+                                        errmsg("RAISE statement option cannot be null")));
+
+               extval = convert_value_to_string(optionvalue, optiontypeid);
+
+               switch (opt->opt_type)
+               {
+                       case PLPGSQL_RAISEOPTION_ERRCODE:
+                               if (err_code)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("RAISE option already specified: %s",
+                                                                       "ERRCODE")));
+                               err_code = plpgsql_recognize_err_condition(extval, true);
+                               condname = pstrdup(extval);
+                               break;
+                       case PLPGSQL_RAISEOPTION_MESSAGE:
+                               if (err_message)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("RAISE option already specified: %s",
+                                                                       "MESSAGE")));
+                               err_message = pstrdup(extval);
+                               break;
+                       case PLPGSQL_RAISEOPTION_DETAIL:
+                               if (err_detail)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("RAISE option already specified: %s",
+                                                                       "DETAIL")));
+                               err_detail = pstrdup(extval);
+                               break;
+                       case PLPGSQL_RAISEOPTION_HINT:
+                               if (err_hint)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_SYNTAX_ERROR),
+                                                        errmsg("RAISE option already specified: %s",
+                                                                       "HINT")));
+                               err_hint = pstrdup(extval);
+                               break;
+                       default:
+                               elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
+               }
+
+               exec_eval_cleanup(estate);
+       }
+
+       /* Default code if nothing specified */
+       if (err_code == 0 && stmt->elog_level >= ERROR)
+               err_code = ERRCODE_RAISE_EXCEPTION;
+
+       /* Default error message if nothing specified */
+       if (err_message == NULL)
+       {
+               if (condname)
+               {
+                       err_message = condname;
+                       condname = NULL;
+               }
+               else
+                       err_message = pstrdup(unpack_sql_state(err_code));
+       }
 
        /*
         * Throw the error (may or may not come back)
@@ -2293,12 +2591,21 @@ exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
        estate->err_text = raise_skip_msg;      /* suppress traceback of raise */
 
        ereport(stmt->elog_level,
-                ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
-                 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
+                       (err_code ? errcode(err_code) : 0,
+                        errmsg_internal("%s", err_message),
+                        (err_detail != NULL) ? errdetail("%s", err_detail) : 0,
+                        (err_hint != NULL) ? errhint("%s", err_hint) : 0));
 
        estate->err_text = NULL;        /* un-suppress... */
 
-       plpgsql_dstring_free(&ds);
+       if (condname != NULL)
+               pfree(condname);
+       if (err_message != NULL)
+               pfree(err_message);
+       if (err_detail != NULL)
+               pfree(err_detail);
+       if (err_hint != NULL)
+               pfree(err_hint);
 
        return PLPGSQL_RC_OK;
 }
@@ -2313,6 +2620,11 @@ plpgsql_estate_setup(PLpgSQL_execstate *estate,
                                         PLpgSQL_function *func,
                                         ReturnSetInfo *rsi)
 {
+       /* this link will be restored at exit from plpgsql_call_handler */
+       func->cur_estate = estate;
+
+       estate->func = func;
+
        estate->retval = (Datum) 0;
        estate->retisnull = true;
        estate->rettype = InvalidOid;
@@ -2327,12 +2639,18 @@ plpgsql_estate_setup(PLpgSQL_execstate *estate,
        estate->exitlabel = NULL;
 
        estate->tuple_store = NULL;
-       estate->tuple_store_cxt = NULL;
+       if (rsi)
+       {
+               estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
+               estate->tuple_store_owner = CurrentResourceOwner;
+       }
+       else
+       {
+               estate->tuple_store_cxt = NULL;
+               estate->tuple_store_owner = NULL;
+       }
        estate->rsi = rsi;
 
-       estate->trig_nargs = 0;
-       estate->trig_argv = NULL;
-
        estate->found_varno = func->found_varno;
        estate->ndatums = func->ndatums;
        estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
@@ -2341,11 +2659,14 @@ plpgsql_estate_setup(PLpgSQL_execstate *estate,
        estate->eval_tuptable = NULL;
        estate->eval_processed = 0;
        estate->eval_lastoid = InvalidOid;
+       estate->eval_econtext = NULL;
+       estate->cur_expr = NULL;
 
-       estate->err_func = func;
        estate->err_stmt = NULL;
        estate->err_text = NULL;
 
+       estate->plugin_info = NULL;
+
        /*
         * Create an EState and ExprContext for evaluation of simple expressions.
         */
@@ -2396,30 +2717,20 @@ static void
 exec_prepare_plan(PLpgSQL_execstate *estate,
                                  PLpgSQL_expr *expr, int cursorOptions)
 {
-       int                     i;
        SPIPlanPtr      plan;
-       Oid                *argtypes;
 
        /*
-        * We need a temporary argtypes array to load with data. (The finished
-        * plan structure will contain a copy of it.)
+        * The grammar can't conveniently set expr->func while building the parse
+        * tree, so make sure it's set before parser hooks need it.
         */
-       argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
-
-       for (i = 0; i < expr->nparams; i++)
-       {
-               Datum           paramval;
-               bool            paramisnull;
-
-               exec_eval_datum(estate, estate->datums[expr->params[i]],
-                                               InvalidOid,
-                                               &argtypes[i], &paramval, &paramisnull);
-       }
+       expr->func = estate->func;
 
        /*
         * Generate and save the plan
         */
-       plan = SPI_prepare_cursor(expr->query, expr->nparams, argtypes,
+       plan = SPI_prepare_params(expr->query,
+                                                         (ParserSetupHook) plpgsql_parser_setup,
+                                                         (void *) expr,
                                                          cursorOptions);
        if (plan == NULL)
        {
@@ -2436,17 +2747,13 @@ exec_prepare_plan(PLpgSQL_execstate *estate,
                                                 errmsg("cannot begin/end transactions in PL/pgSQL"),
                                                 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
                        default:
-                               elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
+                               elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
                                         expr->query, SPI_result_code_string(SPI_result));
                }
        }
        expr->plan = SPI_saveplan(plan);
        SPI_freeplan(plan);
-       plan = expr->plan;
-       expr->plan_argtypes = plan->argtypes;
        exec_simple_check_plan(expr);
-
-       pfree(argtypes);
 }
 
 
@@ -2458,9 +2765,7 @@ static int
 exec_stmt_execsql(PLpgSQL_execstate *estate,
                                  PLpgSQL_stmt_execsql *stmt)
 {
-       int                     i;
-       Datum      *values;
-       char       *nulls;
+       ParamListInfo paramLI;
        long            tcount;
        int                     rc;
        PLpgSQL_expr *expr = stmt->sqlstmt;
@@ -2497,24 +2802,10 @@ exec_stmt_execsql(PLpgSQL_execstate *estate,
        }
 
        /*
-        * Now build up the values and nulls arguments for SPI_execute_plan()
+        * Set up ParamListInfo (note this is only carrying a hook function, not
+        * any actual data values, at this point)
         */
-       values = (Datum *) palloc(expr->nparams * sizeof(Datum));
-       nulls = (char *) palloc(expr->nparams * sizeof(char));
-
-       for (i = 0; i < expr->nparams; i++)
-       {
-               PLpgSQL_datum *datum = estate->datums[expr->params[i]];
-               Oid                     paramtypeid;
-               bool            paramisnull;
-
-               exec_eval_datum(estate, datum, expr->plan_argtypes[i],
-                                               &paramtypeid, &values[i], &paramisnull);
-               if (paramisnull)
-                       nulls[i] = 'n';
-               else
-                       nulls[i] = ' ';
-       }
+       paramLI = setup_param_list(estate, expr);
 
        /*
         * If we have INTO, then we only need one row back ... but if we have INTO
@@ -2540,8 +2831,8 @@ exec_stmt_execsql(PLpgSQL_execstate *estate,
        /*
         * Execute the plan
         */
-       rc = SPI_execute_plan(expr->plan, values, nulls,
-                                                 estate->readonly_func, tcount);
+       rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
+                                                                                estate->readonly_func, tcount);
 
        /*
         * Check for error, and set FOUND if appropriate (for historical reasons
@@ -2570,8 +2861,19 @@ exec_stmt_execsql(PLpgSQL_execstate *estate,
                        Assert(!stmt->mod_stmt);
                        break;
 
+               case SPI_OK_REWRITTEN:
+                       Assert(!stmt->mod_stmt);
+
+                       /*
+                        * The command was rewritten into another kind of command. It's
+                        * not clear what FOUND would mean in that case (and SPI doesn't
+                        * return the row count either), so just set it to false.
+                        */
+                       exec_set_found(estate, false);
+                       break;
+
                default:
-                       elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
+                       elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
                                 expr->query, SPI_result_code_string(rc));
        }
 
@@ -2595,9 +2897,9 @@ exec_stmt_execsql(PLpgSQL_execstate *estate,
 
                /* Determine if we assign to a record or a row */
                if (stmt->rec != NULL)
-                       rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
+                       rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
                else if (stmt->row != NULL)
-                       row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
+                       row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
                else
                        elog(ERROR, "unsupported target");
 
@@ -2638,8 +2940,8 @@ exec_stmt_execsql(PLpgSQL_execstate *estate,
                                         (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
        }
 
-       pfree(values);
-       pfree(nulls);
+       if (paramLI)
+               pfree(paramLI);
 
        return PLPGSQL_RC_OK;
 }
@@ -2668,7 +2970,7 @@ exec_stmt_dynexecute(PLpgSQL_execstate *estate,
        if (isnull)
                ereport(ERROR,
                                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                errmsg("cannot EXECUTE a null querystring")));
+                                errmsg("query string argument of EXECUTE is null")));
 
        /* Get the C-String representation */
        querystr = convert_value_to_string(query, restype);
@@ -2676,9 +2978,21 @@ exec_stmt_dynexecute(PLpgSQL_execstate *estate,
        exec_eval_cleanup(estate);
 
        /*
-        * Call SPI_execute() without preparing a saved plan.
+        * Execute the query without preparing a saved plan.
         */
-       exec_res = SPI_execute(querystr, estate->readonly_func, 0);
+       if (stmt->params)
+       {
+               PreparedParamsData *ppd;
+
+               ppd = exec_eval_using_params(estate, stmt->params);
+               exec_res = SPI_execute_with_args(querystr,
+                                                                                ppd->nargs, ppd->types,
+                                                                                ppd->values, ppd->nulls,
+                                                                                estate->readonly_func, 0);
+               free_params_data(ppd);
+       }
+       else
+               exec_res = SPI_execute(querystr, estate->readonly_func, 0);
 
        switch (exec_res)
        {
@@ -2690,6 +3004,7 @@ exec_stmt_dynexecute(PLpgSQL_execstate *estate,
                case SPI_OK_UPDATE_RETURNING:
                case SPI_OK_DELETE_RETURNING:
                case SPI_OK_UTILITY:
+               case SPI_OK_REWRITTEN:
                        break;
 
                case 0:
@@ -2720,7 +3035,8 @@ exec_stmt_dynexecute(PLpgSQL_execstate *estate,
                                if (*ptr == 'S' || *ptr == 's')
                                        ereport(ERROR,
                                                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                                                        errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
+                                        errmsg("EXECUTE of SELECT ... INTO is not implemented"),
+                                                        errhint("You might want to use EXECUTE ... INTO instead.")));
                                break;
                        }
 
@@ -2761,9 +3077,9 @@ exec_stmt_dynexecute(PLpgSQL_execstate *estate,
 
                /* Determine if we assign to a record or a row */
                if (stmt->rec != NULL)
-                       rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
+                       rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
                else if (stmt->row != NULL)
-                       row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
+                       row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
                else
                        elog(ERROR, "unsupported target");
 
@@ -2818,177 +3134,23 @@ exec_stmt_dynexecute(PLpgSQL_execstate *estate,
 static int
 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
 {
-       Datum           query;
-       bool            isnull;
-       Oid                     restype;
-       char       *querystr;
-       PLpgSQL_rec *rec = NULL;
-       PLpgSQL_row *row = NULL;
-       SPITupleTable *tuptab;
-       int                     n;
-       SPIPlanPtr      plan;
        Portal          portal;
-       bool            found = false;
-
-       /*
-        * Determine if we assign to a record or a row
-        */
-       if (stmt->rec != NULL)
-               rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
-       else if (stmt->row != NULL)
-               row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
-       else
-               elog(ERROR, "unsupported target");
-
-       /*
-        * Evaluate the string expression after the EXECUTE keyword. It's result
-        * is the querystring we have to execute.
-        */
-       query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
-       if (isnull)
-               ereport(ERROR,
-                               (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                errmsg("cannot EXECUTE a null querystring")));
-
-       /* Get the C-String representation */
-       querystr = convert_value_to_string(query, restype);
-
-       exec_eval_cleanup(estate);
-
-       /*
-        * Prepare a plan and open an implicit cursor for the query
-        */
-       plan = SPI_prepare(querystr, 0, NULL);
-       if (plan == NULL)
-               elog(ERROR, "SPI_prepare failed for \"%s\": %s",
-                        querystr, SPI_result_code_string(SPI_result));
-       portal = SPI_cursor_open(NULL, plan, NULL, NULL,
-                                                        estate->readonly_func);
-       if (portal == NULL)
-               elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
-                        querystr, SPI_result_code_string(SPI_result));
-       pfree(querystr);
-       SPI_freeplan(plan);
-
-       /*
-        * Fetch the initial 10 tuples
-        */
-       SPI_cursor_fetch(portal, true, 10);
-       tuptab = SPI_tuptable;
-       n = SPI_processed;
-
-       /*
-        * If the query didn't return any rows, set the target to NULL and return
-        * with FOUND = false.
-        */
-       if (n == 0)
-               exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
-       else
-               found = true;                   /* processed at least one tuple */
-
-       /*
-        * Now do the loop
-        */
-       while (n > 0)
-       {
-               int                     i;
-
-               for (i = 0; i < n; i++)
-               {
-                       int                     rc;
-
-                       /*
-                        * Assign the tuple to the target
-                        */
-                       exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
-
-                       /*
-                        * Execute the statements
-                        */
-                       rc = exec_stmts(estate, stmt->body);
-
-                       if (rc != PLPGSQL_RC_OK)
-                       {
-                               if (rc == PLPGSQL_RC_EXIT)
-                               {
-                                       if (estate->exitlabel == NULL)
-                                               /* unlabelled exit, finish the current loop */
-                                               rc = PLPGSQL_RC_OK;
-                                       else if (stmt->label != NULL &&
-                                                        strcmp(stmt->label, estate->exitlabel) == 0)
-                                       {
-                                               /* labelled exit, matches the current stmt's label */
-                                               estate->exitlabel = NULL;
-                                               rc = PLPGSQL_RC_OK;
-                                       }
-
-                                       /*
-                                        * otherwise, we processed a labelled exit that does not
-                                        * match the current statement's label, if any: return
-                                        * RC_EXIT so that the EXIT continues to recurse upward.
-                                        */
-                               }
-                               else if (rc == PLPGSQL_RC_CONTINUE)
-                               {
-                                       if (estate->exitlabel == NULL)
-                                               /* unlabelled continue, continue the current loop */
-                                               continue;
-                                       else if (stmt->label != NULL &&
-                                                        strcmp(stmt->label, estate->exitlabel) == 0)
-                                       {
-                                               /* labelled continue, matches the current stmt's label */
-                                               estate->exitlabel = NULL;
-                                               continue;
-                                       }
-
-                                       /*
-                                        * otherwise, we process a labelled continue that does not
-                                        * match the current statement's label, so propagate
-                                        * RC_CONTINUE upward in the stack.
-                                        */
-                               }
-
-                               /*
-                                * We're aborting the loop, so cleanup and set FOUND. (This
-                                * code should match the code after the loop.)
-                                */
-                               SPI_freetuptable(tuptab);
-                               SPI_cursor_close(portal);
-                               exec_set_found(estate, found);
-
-                               return rc;
-                       }
-               }
+       int                     rc;
 
-               SPI_freetuptable(tuptab);
-
-               /*
-                * Fetch the next 50 tuples
-                */
-               SPI_cursor_fetch(portal, true, 50);
-               n = SPI_processed;
-               tuptab = SPI_tuptable;
-       }
+       portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
+                                                                          NULL, 0);
 
        /*
-        * Release last group of tuples
+        * Execute the loop
         */
-       SPI_freetuptable(tuptab);
+       rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
 
        /*
         * Close the implicit cursor
         */
        SPI_cursor_close(portal);
 
-       /*
-        * Set the FOUND variable to indicate the result of executing the loop
-        * (namely, whether we looped one or more times). This must be set here so
-        * that it does not interfere with the value of the FOUND variable inside
-        * the loop processing itself.
-        */
-       exec_set_found(estate, found);
-
-       return PLPGSQL_RC_OK;
+       return rc;
 }
 
 
@@ -2999,15 +3161,11 @@ exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
 static int
 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
 {
-       PLpgSQL_var *curvar = NULL;
+       PLpgSQL_var *curvar;
        char       *curname = NULL;
-       PLpgSQL_expr *query = NULL;
+       PLpgSQL_expr *query;
        Portal          portal;
-       int                     i;
-       Datum      *values;
-       char       *nulls;
-       bool            isnull;
-
+       ParamListInfo paramLI;
 
        /* ----------
         * Get the cursor variable and if it has an assigned name, check
@@ -3017,7 +3175,7 @@ exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
        curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
        if (!curvar->isnull)
        {
-               curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
+               curname = TextDatumGetCString(curvar->value);
                if (SPI_cursor_find(curname) != NULL)
                        ereport(ERROR,
                                        (errcode(ERRCODE_DUPLICATE_CURSOR),
@@ -3047,52 +3205,17 @@ exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
                 * This is an OPEN refcursor FOR EXECUTE ...
                 * ----------
                 */
-               Datum           queryD;
-               Oid                     restype;
-               char       *querystr;
-               SPIPlanPtr      curplan;
-
-               /* ----------
-                * We evaluate the string expression after the
-                * EXECUTE keyword. It's result is the querystring we have
-                * to execute.
-                * ----------
-                */
-               queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
-               if (isnull)
-                       ereport(ERROR,
-                                       (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                        errmsg("cannot EXECUTE a null querystring")));
-
-               /* Get the C-String representation */
-               querystr = convert_value_to_string(queryD, restype);
+               portal = exec_dynquery_with_params(estate,
+                                                                                  stmt->dynquery,
+                                                                                  stmt->params,
+                                                                                  curname,
+                                                                                  stmt->cursor_options);
 
-               exec_eval_cleanup(estate);
-
-               /* ----------
-                * Now we prepare a query plan for it and open a cursor
-                * ----------
-                */
-               curplan = SPI_prepare_cursor(querystr, 0, NULL, stmt->cursor_options);
-               if (curplan == NULL)
-                       elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
-                                querystr, SPI_result_code_string(SPI_result));
-               portal = SPI_cursor_open(curname, curplan, NULL, NULL,
-                                                                estate->readonly_func);
-               if (portal == NULL)
-                       elog(ERROR, "could not open cursor for query \"%s\": %s",
-                                querystr, SPI_result_code_string(SPI_result));
-               pfree(querystr);
-               SPI_freeplan(curplan);
-
-               /* ----------
-                * Store the eventually assigned cursor name in the cursor variable
-                * ----------
+               /*
+                * If cursor variable was NULL, store the generated portal name in it
                 */
-               free_var(curvar);
-               curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
-               curvar->isnull = false;
-               curvar->freeval = true;
+               if (curname == NULL)
+                       assign_text_var(curvar, portal->name);
 
                return PLPGSQL_RC_OK;
        }
@@ -3145,52 +3268,32 @@ exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
                        exec_prepare_plan(estate, query, curvar->cursor_options);
        }
 
-       /* ----------
-        * Here we go if we have a saved plan where we have to put
-        * values into, either from an explicit cursor or from a
-        * refcursor opened with OPEN ... FOR SELECT ...;
-        * ----------
+       /*
+        * Set up ParamListInfo (note this is only carrying a hook function, not
+        * any actual data values, at this point)
         */
-       values = (Datum *) palloc(query->nparams * sizeof(Datum));
-       nulls = (char *) palloc(query->nparams * sizeof(char));
-
-       for (i = 0; i < query->nparams; i++)
-       {
-               PLpgSQL_datum *datum = estate->datums[query->params[i]];
-               Oid                     paramtypeid;
-               bool            paramisnull;
-
-               exec_eval_datum(estate, datum, query->plan_argtypes[i],
-                                               &paramtypeid, &values[i], &paramisnull);
-               if (paramisnull)
-                       nulls[i] = 'n';
-               else
-                       nulls[i] = ' ';
-       }
+       paramLI = setup_param_list(estate, query);
 
-       /* ----------
+       /*
         * Open the cursor
-        * ----------
         */
-       portal = SPI_cursor_open(curname, query->plan, values, nulls,
-                                                        estate->readonly_func);
+       portal = SPI_cursor_open_with_paramlist(curname, query->plan,
+                                                                                       paramLI,
+                                                                                       estate->readonly_func);
        if (portal == NULL)
                elog(ERROR, "could not open cursor: %s",
                         SPI_result_code_string(SPI_result));
 
-       pfree(values);
-       pfree(nulls);
-       if (curname)
-               pfree(curname);
-
-       /* ----------
-        * Store the eventually assigned portal name in the cursor variable
-        * ----------
+       /*
+        * If cursor variable was NULL, store the generated portal name in it
         */
-       free_var(curvar);
-       curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
-       curvar->isnull = false;
-       curvar->freeval = true;
+       if (curname == NULL)
+               assign_text_var(curvar, portal->name);
+
+       if (curname)
+               pfree(curname);
+       if (paramLI)
+               pfree(paramLI);
 
        return PLPGSQL_RC_OK;
 }
@@ -3211,7 +3314,7 @@ exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
        SPITupleTable *tuptab;
        Portal          portal;
        char       *curname;
-       int                     n;
+       uint32          n;
 
        /* ----------
         * Get the portal of the cursor by name
@@ -3221,8 +3324,8 @@ exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
        if (curvar->isnull)
                ereport(ERROR,
                                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
-       curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
+                                errmsg("cursor variable \"%s\" is null", curvar->refname)));
+       curname = TextDatumGetCString(curvar->value);
 
        portal = SPI_cursor_find(curname);
        if (portal == NULL)
@@ -3242,7 +3345,7 @@ exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
                if (isnull)
                        ereport(ERROR,
                                        (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                        errmsg("relative or absolute cursor position is NULL")));
+                                        errmsg("relative or absolute cursor position is null")));
 
                exec_eval_cleanup(estate);
        }
@@ -3254,9 +3357,9 @@ exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
                 * ----------
                 */
                if (stmt->rec != NULL)
-                       rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
+                       rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
                else if (stmt->row != NULL)
-                       row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
+                       row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
                else
                        elog(ERROR, "unsupported target");
 
@@ -3269,19 +3372,13 @@ exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
                n = SPI_processed;
 
                /* ----------
-                * Set the target and the global FOUND variable appropriately.
+                * Set the target appropriately.
                 * ----------
                 */
                if (n == 0)
-               {
                        exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
-                       exec_set_found(estate, false);
-               }
                else
-               {
                        exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
-                       exec_set_found(estate, true);
-               }
 
                SPI_freetuptable(tuptab);
        }
@@ -3290,11 +3387,12 @@ exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
                /* Move the cursor */
                SPI_scroll_cursor_move(portal, stmt->direction, how_many);
                n = SPI_processed;
-
-               /* Set the global FOUND variable appropriately. */
-               exec_set_found(estate, n != 0);
        }
 
+       /* Set the ROW_COUNT and the global FOUND variable appropriately. */
+       estate->eval_processed = n;
+       exec_set_found(estate, n != 0);
+
        return PLPGSQL_RC_OK;
 }
 
@@ -3317,8 +3415,8 @@ exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
        if (curvar->isnull)
                ereport(ERROR,
                                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
-       curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
+                                errmsg("cursor variable \"%s\" is null", curvar->refname)));
+       curname = TextDatumGetCString(curvar->value);
 
        portal = SPI_cursor_find(curname);
        if (portal == NULL)
@@ -3384,7 +3482,7 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                if (*isNull && var->notnull)
                                        ereport(ERROR,
                                                        (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                                        errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
+                                                        errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
                                                                        var->refname)));
 
                                /*
@@ -3425,11 +3523,6 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                 */
                                PLpgSQL_row *row = (PLpgSQL_row *) target;
 
-                               /* Source must be of RECORD or composite type */
-                               if (!type_is_rowtype(valtype))
-                                       ereport(ERROR,
-                                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
-                                                        errmsg("cannot assign non-composite value to a row variable")));
                                if (*isNull)
                                {
                                        /* If source is null, just assign nulls to the row */
@@ -3443,7 +3536,12 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                        TupleDesc       tupdesc;
                                        HeapTupleData tmptup;
 
-                                       /* Else source is a tuple Datum, safe to do this: */
+                                       /* Source must be of RECORD or composite type */
+                                       if (!type_is_rowtype(valtype))
+                                               ereport(ERROR,
+                                                               (errcode(ERRCODE_DATATYPE_MISMATCH),
+                                                                errmsg("cannot assign non-composite value to a row variable")));
+                                       /* Source is a tuple Datum, so safe to do this: */
                                        td = DatumGetHeapTupleHeader(value);
                                        /* Extract rowtype info and find a tupdesc */
                                        tupType = HeapTupleHeaderGetTypeId(td);
@@ -3467,11 +3565,6 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                 */
                                PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
 
-                               /* Source must be of RECORD or composite type */
-                               if (!type_is_rowtype(valtype))
-                                       ereport(ERROR,
-                                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
-                                                        errmsg("cannot assign non-composite value to a record variable")));
                                if (*isNull)
                                {
                                        /* If source is null, just assign nulls to the record */
@@ -3485,7 +3578,13 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                        TupleDesc       tupdesc;
                                        HeapTupleData tmptup;
 
-                                       /* Else source is a tuple Datum, safe to do this: */
+                                       /* Source must be of RECORD or composite type */
+                                       if (!type_is_rowtype(valtype))
+                                               ereport(ERROR,
+                                                               (errcode(ERRCODE_DATATYPE_MISMATCH),
+                                                                errmsg("cannot assign non-composite value to a record variable")));
+
+                                       /* Source is a tuple Datum, so safe to do this: */
                                        td = DatumGetHeapTupleHeader(value);
                                        /* Extract rowtype info and find a tupdesc */
                                        tupType = HeapTupleHeaderGetTypeId(td);
@@ -3512,9 +3611,9 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                int                     fno;
                                HeapTuple       newtup;
                                int                     natts;
-                               int                     i;
                                Datum      *values;
-                               char       *nulls;
+                               bool       *nulls;
+                               bool       *replaces;
                                void       *mustfree;
                                bool            attisnull;
                                Oid                     atttype;
@@ -3536,10 +3635,11 @@ exec_assign_value(PLpgSQL_execstate *estate,
 
                                /*
                                 * Get the number of the records field to change and the
-                                * number of attributes in the tuple.
+                                * number of attributes in the tuple.  Note: disallow system
+                                * column names because the code below won't cope.
                                 */
                                fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
-                               if (fno == SPI_ERROR_NOATTRIBUTE)
+                               if (fno <= 0)
                                        ereport(ERROR,
                                                        (errcode(ERRCODE_UNDEFINED_COLUMN),
                                                         errmsg("record \"%s\" has no field \"%s\"",
@@ -3548,24 +3648,16 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                natts = rec->tupdesc->natts;
 
                                /*
-                                * Set up values/datums arrays for heap_formtuple.      For all
+                                * Set up values/control arrays for heap_modify_tuple. For all
                                 * the attributes except the one we want to replace, use the
                                 * value that's in the old tuple.
                                 */
                                values = palloc(sizeof(Datum) * natts);
-                               nulls = palloc(natts);
+                               nulls = palloc(sizeof(bool) * natts);
+                               replaces = palloc(sizeof(bool) * natts);
 
-                               for (i = 0; i < natts; i++)
-                               {
-                                       if (i == fno)
-                                               continue;
-                                       values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
-                                                                                         i + 1, &attisnull);
-                                       if (attisnull)
-                                               nulls[i] = 'n';
-                                       else
-                                               nulls[i] = ' ';
-                               }
+                               memset(replaces, false, sizeof(bool) * natts);
+                               replaces[fno] = true;
 
                                /*
                                 * Now insert the new value, being careful to cast it to the
@@ -3579,10 +3671,7 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                                                                                         atttype,
                                                                                                         atttypmod,
                                                                                                         attisnull);
-                               if (attisnull)
-                                       nulls[fno] = 'n';
-                               else
-                                       nulls[fno] = ' ';
+                               nulls[fno] = attisnull;
 
                                /*
                                 * Avoid leaking the result of exec_simple_cast_value, if it
@@ -3594,10 +3683,11 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                        mustfree = NULL;
 
                                /*
-                                * Now call heap_formtuple() to create a new tuple that
+                                * Now call heap_modify_tuple() to create a new tuple that
                                 * replaces the old one in the record.
                                 */
-                               newtup = heap_formtuple(rec->tupdesc, values, nulls);
+                               newtup = heap_modify_tuple(rec->tup, rec->tupdesc,
+                                                                                  values, nulls, replaces);
 
                                if (rec->freetup)
                                        heap_freetuple(rec->tup);
@@ -3607,6 +3697,7 @@ exec_assign_value(PLpgSQL_execstate *estate,
 
                                pfree(values);
                                pfree(nulls);
+                               pfree(replaces);
                                if (mustfree)
                                        pfree(mustfree);
 
@@ -3649,14 +3740,14 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                        if (nsubscripts >= MAXDIM)
                                                ereport(ERROR,
                                                                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
-                                                                errmsg("number of array dimensions exceeds the maximum allowed, %d",
-                                                                               MAXDIM)));
+                                                                errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
+                                                                               nsubscripts, MAXDIM)));
                                        subscripts[nsubscripts++] = arrayelem->subscript;
                                        target = estate->datums[arrayelem->arrayparentno];
                                } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
 
                                /* Fetch current value of array datum */
-                               exec_eval_datum(estate, target, InvalidOid,
+                               exec_eval_datum(estate, target,
                                                          &arraytypeid, &oldarraydatum, &oldarrayisnull);
 
                                arrayelemtypeid = get_element_type(arraytypeid);
@@ -3686,7 +3777,7 @@ exec_assign_value(PLpgSQL_execstate *estate,
                                        if (subisnull)
                                                ereport(ERROR,
                                                                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
-                                                                errmsg("array subscript in assignment must not be NULL")));
+                                                                errmsg("array subscript in assignment must not be null")));
                                }
 
                                /* Coerce source value to match array element type. */
@@ -3761,8 +3852,6 @@ exec_assign_value(PLpgSQL_execstate *estate,
  *
  * The type oid, value in Datum format, and null flag are returned.
  *
- * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
- *
  * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
  *
  * NOTE: caller must not modify the returned value, since it points right
@@ -3773,7 +3862,6 @@ exec_assign_value(PLpgSQL_execstate *estate,
 static void
 exec_eval_datum(PLpgSQL_execstate *estate,
                                PLpgSQL_datum *datum,
-                               Oid expectedtypeid,
                                Oid *typeid,
                                Datum *value,
                                bool *isnull)
@@ -3789,11 +3877,6 @@ exec_eval_datum(PLpgSQL_execstate *estate,
                                *typeid = var->datatype->typoid;
                                *value = var->value;
                                *isnull = var->isnull;
-                               if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
-                                       ereport(ERROR,
-                                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
-                                                        errmsg("type of \"%s\" does not match that when preparing the plan",
-                                                                       var->refname)));
                                break;
                        }
 
@@ -3814,11 +3897,6 @@ exec_eval_datum(PLpgSQL_execstate *estate,
                                *typeid = row->rowtupdesc->tdtypeid;
                                *value = HeapTupleGetDatum(tup);
                                *isnull = false;
-                               if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
-                                       ereport(ERROR,
-                                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
-                                                        errmsg("type of \"%s\" does not match that when preparing the plan",
-                                                                       row->refname)));
                                break;
                        }
 
@@ -3851,11 +3929,6 @@ exec_eval_datum(PLpgSQL_execstate *estate,
                                *typeid = rec->tupdesc->tdtypeid;
                                *value = HeapTupleGetDatum(&worktup);
                                *isnull = false;
-                               if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
-                                       ereport(ERROR,
-                                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
-                                                        errmsg("type of \"%s\" does not match that when preparing the plan",
-                                                                       rec->refname)));
                                break;
                        }
 
@@ -3880,42 +3953,126 @@ exec_eval_datum(PLpgSQL_execstate *estate,
                                                                        rec->refname, recfield->fieldname)));
                                *typeid = SPI_gettypeid(rec->tupdesc, fno);
                                *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
-                               if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
+                               break;
+                       }
+
+               default:
+                       elog(ERROR, "unrecognized dtype: %d", datum->dtype);
+       }
+}
+
+/*
+ * exec_get_datum_type                         Get datatype of a PLpgSQL_datum
+ *
+ * This is the same logic as in exec_eval_datum, except that it can handle
+ * some cases where exec_eval_datum has to fail; specifically, we may have
+ * a tupdesc but no row value for a record variable.  (This currently can
+ * happen only for a trigger's NEW/OLD records.)
+ */
+Oid
+exec_get_datum_type(PLpgSQL_execstate *estate,
+                                       PLpgSQL_datum *datum)
+{
+       Oid                     typeid;
+
+       switch (datum->dtype)
+       {
+               case PLPGSQL_DTYPE_VAR:
+                       {
+                               PLpgSQL_var *var = (PLpgSQL_var *) datum;
+
+                               typeid = var->datatype->typoid;
+                               break;
+                       }
+
+               case PLPGSQL_DTYPE_ROW:
+                       {
+                               PLpgSQL_row *row = (PLpgSQL_row *) datum;
+
+                               if (!row->rowtupdesc)   /* should not happen */
+                                       elog(ERROR, "row variable has no tupdesc");
+                               /* Make sure we have a valid type/typmod setting */
+                               BlessTupleDesc(row->rowtupdesc);
+                               typeid = row->rowtupdesc->tdtypeid;
+                               break;
+                       }
+
+               case PLPGSQL_DTYPE_REC:
+                       {
+                               PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
+
+                               if (rec->tupdesc == NULL)
                                        ereport(ERROR,
-                                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
-                                                        errmsg("type of \"%s.%s\" does not match that when preparing the plan",
-                                                                       rec->refname, recfield->fieldname)));
+                                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                                                  errmsg("record \"%s\" is not assigned yet",
+                                                                 rec->refname),
+                                                  errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
+                               /* Make sure we have a valid type/typmod setting */
+                               BlessTupleDesc(rec->tupdesc);
+                               typeid = rec->tupdesc->tdtypeid;
                                break;
                        }
 
-               case PLPGSQL_DTYPE_TRIGARG:
+               case PLPGSQL_DTYPE_RECFIELD:
                        {
-                               PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
-                               int                     tgargno;
+                               PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
+                               PLpgSQL_rec *rec;
+                               int                     fno;
 
-                               *typeid = TEXTOID;
-                               tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
-                               if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
-                               {
-                                       *value = (Datum) 0;
-                                       *isnull = true;
-                               }
-                               else
-                               {
-                                       *value = estate->trig_argv[tgargno];
-                                       *isnull = false;
-                               }
-                               if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
+                               rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
+                               if (rec->tupdesc == NULL)
                                        ereport(ERROR,
-                                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
-                                                        errmsg("type of tgargv[%d] does not match that when preparing the plan",
-                                                                       tgargno)));
+                                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                                                  errmsg("record \"%s\" is not assigned yet",
+                                                                 rec->refname),
+                                                  errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
+                               fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
+                               if (fno == SPI_ERROR_NOATTRIBUTE)
+                                       ereport(ERROR,
+                                                       (errcode(ERRCODE_UNDEFINED_COLUMN),
+                                                        errmsg("record \"%s\" has no field \"%s\"",
+                                                                       rec->refname, recfield->fieldname)));
+                               typeid = SPI_gettypeid(rec->tupdesc, fno);
                                break;
                        }
 
                default:
                        elog(ERROR, "unrecognized dtype: %d", datum->dtype);
+                       typeid = InvalidOid;    /* keep compiler quiet */
+                       break;
        }
+
+       return typeid;
+}
+
+/*
+ * exec_get_rec_fieldtype                              Get datatype of a PLpgSQL record field
+ *
+ * Also returns the field number to *fieldno.
+ */
+Oid
+exec_get_rec_fieldtype(PLpgSQL_rec *rec, const char *fieldname,
+                                          int *fieldno)
+{
+       Oid                     typeid;
+       int                     fno;
+
+       if (rec->tupdesc == NULL)
+               ereport(ERROR,
+                               (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                                errmsg("record \"%s\" is not assigned yet",
+                                               rec->refname),
+                                errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
+       fno = SPI_fnumber(rec->tupdesc, fieldname);
+       if (fno == SPI_ERROR_NOATTRIBUTE)
+               ereport(ERROR,
+                               (errcode(ERRCODE_UNDEFINED_COLUMN),
+                                errmsg("record \"%s\" has no field \"%s\"",
+                                               rec->refname, fieldname)));
+       typeid = SPI_gettypeid(rec->tupdesc, fno);
+
+       *fieldno = fno;
+       return typeid;
 }
 
 /* ----------
@@ -3978,7 +4135,7 @@ exec_eval_expr(PLpgSQL_execstate *estate,
                           bool *isNull,
                           Oid *rettype)
 {
-       Datum           result;
+       Datum           result = 0;
        int                     rc;
 
        /*
@@ -4004,7 +4161,24 @@ exec_eval_expr(PLpgSQL_execstate *estate,
                                 errmsg("query \"%s\" did not return data", expr->query)));
 
        /*
-        * If there are no rows selected, the result is NULL.
+        * Check that the expression returns exactly one column...
+        */
+       if (estate->eval_tuptable->tupdesc->natts != 1)
+               ereport(ERROR,
+                               (errcode(ERRCODE_SYNTAX_ERROR),
+                                errmsg_plural("query \"%s\" returned %d column",
+                                                          "query \"%s\" returned %d columns",
+                                                          estate->eval_tuptable->tupdesc->natts,
+                                                          expr->query,
+                                                          estate->eval_tuptable->tupdesc->natts)));
+
+       /*
+        * ... and get the column's datatype.
+        */
+       *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
+
+       /*
+        * If there are no rows selected, the result is a NULL of that type.
         */
        if (estate->eval_processed == 0)
        {
@@ -4013,23 +4187,17 @@ exec_eval_expr(PLpgSQL_execstate *estate,
        }
 
        /*
-        * Check that the expression returned one single Datum
+        * Check that the expression returned no more than one row.
         */
-       if (estate->eval_processed > 1)
+       if (estate->eval_processed != 1)
                ereport(ERROR,
                                (errcode(ERRCODE_CARDINALITY_VIOLATION),
                                 errmsg("query \"%s\" returned more than one row",
                                                expr->query)));
-       if (estate->eval_tuptable->tupdesc->natts != 1)
-               ereport(ERROR,
-                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                errmsg("query \"%s\" returned %d columns", expr->query,
-                                               estate->eval_tuptable->tupdesc->natts)));
 
        /*
-        * Return the result and its type
+        * Return the single result Datum.
         */
-       *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
        return SPI_getbinval(estate->eval_tuptable->vals[0],
                                                 estate->eval_tuptable->tupdesc, 1, isNull);
 }
@@ -4043,9 +4211,7 @@ static int
 exec_run_select(PLpgSQL_execstate *estate,
                                PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
 {
-       int                     i;
-       Datum      *values;
-       char       *nulls;
+       ParamListInfo paramLI;
        int                     rc;
 
        /*
@@ -4055,58 +4221,201 @@ exec_run_select(PLpgSQL_execstate *estate,
                exec_prepare_plan(estate, expr, 0);
 
        /*
-        * Now build up the values and nulls arguments for SPI_execute_plan()
+        * Set up ParamListInfo (note this is only carrying a hook function, not
+        * any actual data values, at this point)
         */
-       values = (Datum *) palloc(expr->nparams * sizeof(Datum));
-       nulls = (char *) palloc(expr->nparams * sizeof(char));
-
-       for (i = 0; i < expr->nparams; i++)
-       {
-               PLpgSQL_datum *datum = estate->datums[expr->params[i]];
-               Oid                     paramtypeid;
-               bool            paramisnull;
-
-               exec_eval_datum(estate, datum, expr->plan_argtypes[i],
-                                               &paramtypeid, &values[i], &paramisnull);
-               if (paramisnull)
-                       nulls[i] = 'n';
-               else
-                       nulls[i] = ' ';
-       }
+       paramLI = setup_param_list(estate, expr);
 
        /*
         * If a portal was requested, put the query into the portal
         */
        if (portalP != NULL)
        {
-               *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
-                                                                  estate->readonly_func);
+               *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
+                                                                                                 paramLI,
+                                                                                                 estate->readonly_func);
                if (*portalP == NULL)
                        elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
                                 expr->query, SPI_result_code_string(SPI_result));
-               pfree(values);
-               pfree(nulls);
+               if (paramLI)
+                       pfree(paramLI);
                return SPI_OK_CURSOR;
        }
 
        /*
-        * Execute the query
+        * Execute the query
+        */
+       rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
+                                                                                estate->readonly_func, maxtuples);
+       if (rc != SPI_OK_SELECT)
+               ereport(ERROR,
+                               (errcode(ERRCODE_SYNTAX_ERROR),
+                                errmsg("query \"%s\" is not a SELECT", expr->query)));
+
+       /* Save query results for eventual cleanup */
+       Assert(estate->eval_tuptable == NULL);
+       estate->eval_tuptable = SPI_tuptable;
+       estate->eval_processed = SPI_processed;
+       estate->eval_lastoid = SPI_lastoid;
+
+       if (paramLI)
+               pfree(paramLI);
+
+       return rc;
+}
+
+
+/*
+ * exec_for_query --- execute body of FOR loop for each row from a portal
+ *
+ * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
+ */
+static int
+exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
+                          Portal portal, bool prefetch_ok)
+{
+       PLpgSQL_rec *rec = NULL;
+       PLpgSQL_row *row = NULL;
+       SPITupleTable *tuptab;
+       bool            found = false;
+       int                     rc = PLPGSQL_RC_OK;
+       int                     n;
+
+       /*
+        * Determine if we assign to a record or a row
+        */
+       if (stmt->rec != NULL)
+               rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
+       else if (stmt->row != NULL)
+               row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
+       else
+               elog(ERROR, "unsupported target");
+
+       /*
+        * Make sure the portal doesn't get closed by the user statements we
+        * execute.
+        */
+       PinPortal(portal);
+
+       /*
+        * Fetch the initial tuple(s).  If prefetching is allowed then we grab a
+        * few more rows to avoid multiple trips through executor startup
+        * overhead.
+        */
+       SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
+       tuptab = SPI_tuptable;
+       n = SPI_processed;
+
+       /*
+        * If the query didn't return any rows, set the target to NULL and fall
+        * through with found = false.
+        */
+       if (n <= 0)
+               exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
+       else
+               found = true;                   /* processed at least one tuple */
+
+       /*
+        * Now do the loop
+        */
+       while (n > 0)
+       {
+               int                     i;
+
+               for (i = 0; i < n; i++)
+               {
+                       /*
+                        * Assign the tuple to the target
+                        */
+                       exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
+
+                       /*
+                        * Execute the statements
+                        */
+                       rc = exec_stmts(estate, stmt->body);
+
+                       if (rc != PLPGSQL_RC_OK)
+                       {
+                               if (rc == PLPGSQL_RC_EXIT)
+                               {
+                                       if (estate->exitlabel == NULL)
+                                       {
+                                               /* unlabelled exit, so exit the current loop */
+                                               rc = PLPGSQL_RC_OK;
+                                       }
+                                       else if (stmt->label != NULL &&
+                                                        strcmp(stmt->label, estate->exitlabel) == 0)
+                                       {
+                                               /* label matches this loop, so exit loop */
+                                               estate->exitlabel = NULL;
+                                               rc = PLPGSQL_RC_OK;
+                                       }
+
+                                       /*
+                                        * otherwise, we processed a labelled exit that does not
+                                        * match the current statement's label, if any; return
+                                        * RC_EXIT so that the EXIT continues to recurse upward.
+                                        */
+                               }
+                               else if (rc == PLPGSQL_RC_CONTINUE)
+                               {
+                                       if (estate->exitlabel == NULL)
+                                       {
+                                               /* unlabelled continue, so re-run the current loop */
+                                               rc = PLPGSQL_RC_OK;
+                                               continue;
+                                       }
+                                       else if (stmt->label != NULL &&
+                                                        strcmp(stmt->label, estate->exitlabel) == 0)
+                                       {
+                                               /* label matches this loop, so re-run loop */
+                                               estate->exitlabel = NULL;
+                                               rc = PLPGSQL_RC_OK;
+                                               continue;
+                                       }
+
+                                       /*
+                                        * otherwise, we process a labelled continue that does not
+                                        * match the current statement's label, if any; return
+                                        * RC_CONTINUE so that the CONTINUE will propagate up the
+                                        * stack.
+                                        */
+                               }
+
+                               /*
+                                * We're aborting the loop.  Need a goto to get out of two
+                                * levels of loop...
+                                */
+                               goto loop_exit;
+                       }
+               }
+
+               SPI_freetuptable(tuptab);
+
+               /*
+                * Fetch more tuples.  If prefetching is allowed, grab 50 at a time.
+                */
+               SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
+               tuptab = SPI_tuptable;
+               n = SPI_processed;
+       }
+
+loop_exit:
+
+       /*
+        * Release last group of tuples (if any)
         */
-       rc = SPI_execute_plan(expr->plan, values, nulls,
-                                                 estate->readonly_func, maxtuples);
-       if (rc != SPI_OK_SELECT)
-               ereport(ERROR,
-                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                errmsg("query \"%s\" is not a SELECT", expr->query)));
+       SPI_freetuptable(tuptab);
 
-       /* Save query results for eventual cleanup */
-       Assert(estate->eval_tuptable == NULL);
-       estate->eval_tuptable = SPI_tuptable;
-       estate->eval_processed = SPI_processed;
-       estate->eval_lastoid = SPI_lastoid;
+       UnpinPortal(portal);
 
-       pfree(values);
-       pfree(nulls);
+       /*
+        * Set the FOUND variable to indicate the result of executing the loop
+        * (namely, whether we looped one or more times). This must be set last so
+        * that it does not interfere with the value of the FOUND variable inside
+        * the loop processing itself.
+        */
+       exec_set_found(estate, found);
 
        return rc;
 }
@@ -4140,11 +4449,12 @@ exec_eval_simple_expr(PLpgSQL_execstate *estate,
                                          Oid *rettype)
 {
        ExprContext *econtext = estate->eval_econtext;
+       LocalTransactionId curlxid = MyProc->lxid;
        CachedPlanSource *plansource;
        CachedPlan *cplan;
        ParamListInfo paramLI;
-       int                     i;
-       Snapshot        saveActiveSnapshot;
+       PLpgSQL_expr *save_cur_expr;
+       MemoryContext oldcontext;
 
        /*
         * Forget it if expression wasn't simple before.
@@ -4180,90 +4490,63 @@ exec_eval_simple_expr(PLpgSQL_execstate *estate,
 
        /*
         * Prepare the expression for execution, if it's not been done already in
-        * the current eval_estate.  (This will be forced to happen if we called
+        * the current transaction.  (This will be forced to happen if we called
         * exec_simple_check_plan above.)
         */
-       if (expr->expr_simple_id != estate->eval_estate_simple_id)
+       if (expr->expr_simple_lxid != curlxid)
        {
                expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
-                                                                                                 estate->eval_estate);
-               expr->expr_simple_id = estate->eval_estate_simple_id;
+                                                                                                 simple_eval_estate);
+               expr->expr_simple_lxid = curlxid;
        }
 
        /*
-        * Param list can live in econtext's temporary memory context.
-        *
-        * XXX think about avoiding repeated palloc's for param lists? Beware
-        * however that this routine is re-entrant: exec_eval_datum() can call it
-        * back for subscript evaluation, and so there can be a need to have more
-        * than one active param list.
+        * We have to do some of the things SPI_execute_plan would do, in
+        * particular advance the snapshot if we are in a non-read-only function.
+        * Without this, stable functions within the expression would fail to see
+        * updates made so far by our own function.
         */
-       if (expr->nparams > 0)
-       {
-               /* sizeof(ParamListInfoData) includes the first array element */
-               paramLI = (ParamListInfo)
-                       MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
-                                                          sizeof(ParamListInfoData) +
-                                                          (expr->nparams - 1) *sizeof(ParamExternData));
-               paramLI->numParams = expr->nparams;
-
-               for (i = 0; i < expr->nparams; i++)
-               {
-                       ParamExternData *prm = &paramLI->params[i];
-                       PLpgSQL_datum *datum = estate->datums[expr->params[i]];
+       SPI_push();
 
-                       prm->pflags = 0;
-                       exec_eval_datum(estate, datum, expr->plan_argtypes[i],
-                                                       &prm->ptype,
-                                                       &prm->value, &prm->isnull);
-               }
+       oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
+       if (!estate->readonly_func)
+       {
+               CommandCounterIncrement();
+               PushActiveSnapshot(GetTransactionSnapshot());
        }
-       else
-               paramLI = NULL;
 
        /*
-        * Now we can safely make the econtext point to the param list.
+        * Create the param list in econtext's temporary memory context. We won't
+        * need to free it explicitly, since it will go away at the next reset of
+        * that context.
+        *
+        * XXX think about avoiding repeated palloc's for param lists?  It should
+        * be possible --- this routine isn't re-entrant anymore.
+        *
+        * Just for paranoia's sake, save and restore the prior value of
+        * estate->cur_expr, which setup_param_list() sets.
         */
+       save_cur_expr = estate->cur_expr;
+
+       paramLI = setup_param_list(estate, expr);
        econtext->ecxt_param_list_info = paramLI;
 
        /*
-        * We have to do some of the things SPI_execute_plan would do, in
-        * particular advance the snapshot if we are in a non-read-only function.
-        * Without this, stable functions within the expression would fail to see
-        * updates made so far by our own function.
+        * Finally we can call the executor to evaluate the expression
         */
-       SPI_push();
-       saveActiveSnapshot = ActiveSnapshot;
+       *result = ExecEvalExpr(expr->expr_simple_state,
+                                                  econtext,
+                                                  isNull,
+                                                  NULL);
 
-       PG_TRY();
-       {
-               MemoryContext oldcontext;
+       /* Assorted cleanup */
+       estate->cur_expr = save_cur_expr;
 
-               oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
-               if (!estate->readonly_func)
-               {
-                       CommandCounterIncrement();
-                       ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
-               }
+       if (!estate->readonly_func)
+               PopActiveSnapshot();
 
-               /*
-                * Finally we can call the executor to evaluate the expression
-                */
-               *result = ExecEvalExpr(expr->expr_simple_state,
-                                                          econtext,
-                                                          isNull,
-                                                          NULL);
-               MemoryContextSwitchTo(oldcontext);
-       }
-       PG_CATCH();
-       {
-               /* Restore global vars and propagate error */
-               ActiveSnapshot = saveActiveSnapshot;
-               PG_RE_THROW();
-       }
-       PG_END_TRY();
+       MemoryContextSwitchTo(oldcontext);
 
-       ActiveSnapshot = saveActiveSnapshot;
        SPI_pop();
 
        /*
@@ -4278,6 +4561,95 @@ exec_eval_simple_expr(PLpgSQL_execstate *estate,
 }
 
 
+/*
+ * Create a ParamListInfo to pass to SPI
+ *
+ * The ParamListInfo array is initially all zeroes, in particular the
+ * ptype values are all InvalidOid.  This causes the executor to call the
+ * paramFetch hook each time it wants a value. We thus evaluate only the
+ * parameters actually demanded.
+ *
+ * The result is a locally palloc'd array that should be pfree'd after use;
+ * but note it can be NULL.
+ */
+static ParamListInfo
+setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
+{
+       ParamListInfo paramLI;
+
+       /*
+        * Could we re-use these arrays instead of palloc'ing a new one each time?
+        * However, we'd have to zero the array each time anyway, since new values
+        * might have been assigned to the variables.
+        */
+       if (estate->ndatums > 0)
+       {
+               /* sizeof(ParamListInfoData) includes the first array element */
+               paramLI = (ParamListInfo)
+                       palloc0(sizeof(ParamListInfoData) +
+                                       (estate->ndatums - 1) *sizeof(ParamExternData));
+               paramLI->paramFetch = plpgsql_param_fetch;
+               paramLI->paramFetchArg = (void *) estate;
+               paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
+               paramLI->parserSetupArg = (void *) expr;
+               paramLI->numParams = estate->ndatums;
+
+               /*
+                * Set up link to active expr where the hook functions can find it.
+                * Callers must save and restore cur_expr if there is any chance that
+                * they are interrupting an active use of parameters.
+                */
+               estate->cur_expr = expr;
+
+               /*
+                * Also make sure this is set before parser hooks need it.      There is
+                * no need to save and restore, since the value is always correct once
+                * set.
+                */
+               expr->func = estate->func;
+       }
+       else
+               paramLI = NULL;
+       return paramLI;
+}
+
+/*
+ * plpgsql_param_fetch         paramFetch callback for dynamic parameter fetch
+ */
+static void
+plpgsql_param_fetch(ParamListInfo params, int paramid)
+{
+       int                     dno;
+       PLpgSQL_execstate *estate;
+       PLpgSQL_expr *expr;
+       PLpgSQL_datum *datum;
+       ParamExternData *prm;
+
+       /* paramid's are 1-based, but dnos are 0-based */
+       dno = paramid - 1;
+       Assert(dno >= 0 && dno < params->numParams);
+
+       /* fetch back the hook data */
+       estate = (PLpgSQL_execstate *) params->paramFetchArg;
+       expr = estate->cur_expr;
+       Assert(params->numParams == estate->ndatums);
+
+       /*
+        * Do nothing if asked for a value that's not supposed to be used by this
+        * SQL expression.      This avoids unwanted evaluations when functions such
+        * as copyParamList try to materialize all the values.
+        */
+       if (!bms_is_member(dno, expr->paramnos))
+               return;
+
+       /* OK, evaluate the value and store into the appropriate paramlist slot */
+       datum = estate->datums[dno];
+       prm = &params->params[dno];
+       exec_eval_datum(estate, datum,
+                                       &prm->ptype, &prm->value, &prm->isnull);
+}
+
+
 /* ----------
  * exec_move_row                       Move one tuple's values into a record or row
  * ----------
@@ -4295,13 +4667,27 @@ exec_move_row(PLpgSQL_execstate *estate,
        if (rec != NULL)
        {
                /*
-                * copy input first, just in case it is pointing at variable's value
+                * Copy input first, just in case it is pointing at variable's value
                 */
                if (HeapTupleIsValid(tup))
                        tup = heap_copytuple(tup);
+               else if (tupdesc)
+               {
+                       /* If we have a tupdesc but no data, form an all-nulls tuple */
+                       bool       *nulls;
+
+                       nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
+                       memset(nulls, true, tupdesc->natts * sizeof(bool));
+
+                       tup = heap_form_tuple(tupdesc, NULL, nulls);
+
+                       pfree(nulls);
+               }
+
                if (tupdesc)
                        tupdesc = CreateTupleDescCopy(tupdesc);
 
+               /* Free the old value ... */
                if (rec->freetup)
                {
                        heap_freetuple(rec->tup);
@@ -4313,24 +4699,12 @@ exec_move_row(PLpgSQL_execstate *estate,
                        rec->freetupdesc = false;
                }
 
+               /* ... and install the new */
                if (HeapTupleIsValid(tup))
                {
                        rec->tup = tup;
                        rec->freetup = true;
                }
-               else if (tupdesc)
-               {
-                       /* If we have a tupdesc but no data, form an all-nulls tuple */
-                       char       *nulls;
-
-                       nulls = (char *) palloc(tupdesc->natts * sizeof(char));
-                       memset(nulls, 'n', tupdesc->natts * sizeof(char));
-
-                       rec->tup = heap_formtuple(tupdesc, NULL, nulls);
-                       rec->freetup = true;
-
-                       pfree(nulls);
-               }
                else
                        rec->tup = NULL;
 
@@ -4350,18 +4724,20 @@ exec_move_row(PLpgSQL_execstate *estate,
         * attributes of the tuple to the variables the row points to.
         *
         * NOTE: this code used to demand row->nfields ==
-        * HeapTupleHeaderGetNatts(tup->t_data, but that's wrong.  The tuple might
-        * have more fields than we expected if it's from an inheritance-child
-        * table of the current table, or it might have fewer if the table has had
-        * columns added by ALTER TABLE. Ignore extra columns and assume NULL for
-        * missing columns, the same as heap_getattr would do.  We also have to
-        * skip over dropped columns in either the source or destination.
+        * HeapTupleHeaderGetNatts(tup->t_data), but that's wrong.  The tuple
+        * might have more fields than we expected if it's from an
+        * inheritance-child table of the current table, or it might have fewer if
+        * the table has had columns added by ALTER TABLE. Ignore extra columns
+        * and assume NULL for missing columns, the same as heap_getattr would do.
+        * We also have to skip over dropped columns in either the source or
+        * destination.
         *
         * If we have no tuple data at all, we'll assign NULL to all columns of
         * the row variable.
         */
        if (row != NULL)
        {
+               int                     td_natts = tupdesc ? tupdesc->natts : 0;
                int                     t_natts;
                int                     fnum;
                int                     anum;
@@ -4384,12 +4760,18 @@ exec_move_row(PLpgSQL_execstate *estate,
 
                        var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
 
-                       while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
+                       while (anum < td_natts && tupdesc->attrs[anum]->attisdropped)
                                anum++;                 /* skip dropped column in tuple */
 
-                       if (anum < t_natts)
+                       if (anum < td_natts)
                        {
-                               value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
+                               if (anum < t_natts)
+                                       value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
+                               else
+                               {
+                                       value = (Datum) 0;
+                                       isnull = true;
+                               }
                                valtype = SPI_gettypeid(tupdesc, anum + 1);
                                anum++;
                        }
@@ -4397,6 +4779,11 @@ exec_move_row(PLpgSQL_execstate *estate,
                        {
                                value = (Datum) 0;
                                isnull = true;
+
+                               /*
+                                * InvalidOid is OK because exec_assign_value doesn't care
+                                * about the type of a source NULL
+                                */
                                valtype = InvalidOid;
                        }
 
@@ -4446,7 +4833,7 @@ make_tuple_from_row(PLpgSQL_execstate *estate,
                        elog(ERROR, "dropped rowtype entry for non-dropped column");
 
                exec_eval_datum(estate, estate->datums[row->varnos[i]],
-                                               InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
+                                               &fieldtypeid, &dvalues[i], &nulls[i]);
                if (fieldtypeid != tupdesc->attrs[i]->atttypid)
                        return NULL;
        }
@@ -4471,27 +4858,11 @@ make_tuple_from_row(PLpgSQL_execstate *estate,
 static char *
 convert_value_to_string(Datum value, Oid valtype)
 {
-       char       *str;
        Oid                     typoutput;
        bool            typIsVarlena;
 
        getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
-
-       /*
-        * We do SPI_push to allow the datatype output function to use SPI.
-        * However we do not mess around with CommandCounterIncrement or advancing
-        * the snapshot, which means that a stable output function would not see
-        * updates made so far by our own function.  The use-case for such
-        * scenarios seems too narrow to justify the cycles that would be
-        * expended.
-        */
-       SPI_push();
-
-       str = OidOutputFunctionCall(typoutput, value);
-
-       SPI_pop();
-
-       return str;
+       return OidOutputFunctionCall(typoutput, value);
 }
 
 /* ----------
@@ -4517,25 +4888,14 @@ exec_cast_value(Datum value, Oid valtype,
                        char       *extval;
 
                        extval = convert_value_to_string(value, valtype);
-
-                       /* Allow input function to use SPI ... see notes above */
-                       SPI_push();
-
                        value = InputFunctionCall(reqinput, extval,
                                                                          reqtypioparam, reqtypmod);
-
-                       SPI_pop();
-
                        pfree(extval);
                }
                else
                {
-                       SPI_push();
-
                        value = InputFunctionCall(reqinput, NULL,
                                                                          reqtypioparam, reqtypmod);
-
-                       SPI_pop();
                }
        }
 
@@ -4555,26 +4915,23 @@ exec_simple_cast_value(Datum value, Oid valtype,
                                           Oid reqtype, int32 reqtypmod,
                                           bool isnull)
 {
-       if (!isnull)
+       if (valtype != reqtype || reqtypmod != -1)
        {
-               if (valtype != reqtype || reqtypmod != -1)
-               {
-                       Oid                     typinput;
-                       Oid                     typioparam;
-                       FmgrInfo        finfo_input;
+               Oid                     typinput;
+               Oid                     typioparam;
+               FmgrInfo        finfo_input;
 
-                       getTypeInputInfo(reqtype, &typinput, &typioparam);
+               getTypeInputInfo(reqtype, &typinput, &typioparam);
 
-                       fmgr_info(typinput, &finfo_input);
+               fmgr_info(typinput, &finfo_input);
 
-                       value = exec_cast_value(value,
-                                                                       valtype,
-                                                                       reqtype,
-                                                                       &finfo_input,
-                                                                       typioparam,
-                                                                       reqtypmod,
-                                                                       isnull);
-               }
+               value = exec_cast_value(value,
+                                                               valtype,
+                                                               reqtype,
+                                                               &finfo_input,
+                                                               typioparam,
+                                                               reqtypmod,
+                                                               isnull);
        }
 
        return value;
@@ -4912,31 +5269,11 @@ exec_simple_check_plan(PLpgSQL_expr *expr)
         */
        expr->expr_simple_expr = tle->expr;
        expr->expr_simple_state = NULL;
-       expr->expr_simple_id = -1;
+       expr->expr_simple_lxid = InvalidLocalTransactionId;
        /* Also stash away the expression result type */
        expr->expr_simple_type = exprType((Node *) tle->expr);
 }
 
-/*
- * Check two tupledescs have matching number and types of attributes
- */
-static bool
-compatible_tupdesc(TupleDesc td1, TupleDesc td2)
-{
-       int                     i;
-
-       if (td1->natts != td2->natts)
-               return false;
-
-       for (i = 0; i < td1->natts; i++)
-       {
-               if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
-                       return false;
-       }
-
-       return true;
-}
-
 /* ----------
  * exec_set_found                      Set the global found variable
  *                                     to true/false
@@ -4948,53 +5285,76 @@ exec_set_found(PLpgSQL_execstate *estate, bool state)
        PLpgSQL_var *var;
 
        var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
-       var->value = (Datum) state;
+       var->value = PointerGetDatum(state);
        var->isnull = false;
 }
 
 /*
  * plpgsql_create_econtext --- create an eval_econtext for the current function
  *
- * We may need to create a new eval_estate too, if there's not one already
- * for the current (sub) transaction.  The EState will be cleaned up at
- * (sub) transaction end.
+ * We may need to create a new simple_eval_estate too, if there's not one
+ * already for the current transaction.  The EState will be cleaned up at
+ * transaction end.
  */
 static void
 plpgsql_create_econtext(PLpgSQL_execstate *estate)
 {
-       SubTransactionId my_subxid = GetCurrentSubTransactionId();
-       SimpleEstateStackEntry *entry = simple_estate_stack;
+       SimpleEcontextStackEntry *entry;
 
-       /* Create new EState if not one for current subxact */
-       if (entry == NULL ||
-               entry->xact_subxid != my_subxid)
+       /*
+        * Create an EState for evaluation of simple expressions, if there's not
+        * one already in the current transaction.      The EState is made a child of
+        * TopTransactionContext so it will have the right lifespan.
+        */
+       if (simple_eval_estate == NULL)
        {
                MemoryContext oldcontext;
 
-               /* Stack entries are kept in TopTransactionContext for simplicity */
-               entry = (SimpleEstateStackEntry *)
-                       MemoryContextAlloc(TopTransactionContext,
-                                                          sizeof(SimpleEstateStackEntry));
-
-               /* But each EState should be a child of its CurTransactionContext */
-               oldcontext = MemoryContextSwitchTo(CurTransactionContext);
-               entry->xact_eval_estate = CreateExecutorState();
+               oldcontext = MemoryContextSwitchTo(TopTransactionContext);
+               simple_eval_estate = CreateExecutorState();
                MemoryContextSwitchTo(oldcontext);
+       }
+
+       /*
+        * Create a child econtext for the current function.
+        */
+       estate->eval_econtext = CreateExprContext(simple_eval_estate);
 
-               /* Assign a reasonably-unique ID to this EState */
-               entry->xact_estate_simple_id = simple_estate_id_counter++;
-               entry->xact_subxid = my_subxid;
+       /*
+        * Make a stack entry so we can clean up the econtext at subxact end.
+        * Stack entries are kept in TopTransactionContext for simplicity.
+        */
+       entry = (SimpleEcontextStackEntry *)
+               MemoryContextAlloc(TopTransactionContext,
+                                                  sizeof(SimpleEcontextStackEntry));
 
-               entry->next = simple_estate_stack;
-               simple_estate_stack = entry;
-       }
+       entry->stack_econtext = estate->eval_econtext;
+       entry->xact_subxid = GetCurrentSubTransactionId();
 
-       /* Link plpgsql estate to it */
-       estate->eval_estate = entry->xact_eval_estate;
-       estate->eval_estate_simple_id = entry->xact_estate_simple_id;
+       entry->next = simple_econtext_stack;
+       simple_econtext_stack = entry;
+}
+
+/*
+ * plpgsql_destroy_econtext --- destroy function's econtext
+ *
+ * We check that it matches the top stack entry, and destroy the stack
+ * entry along with the context.
+ */
+static void
+plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
+{
+       SimpleEcontextStackEntry *next;
+
+       Assert(simple_econtext_stack != NULL);
+       Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
 
-       /* And create a child econtext for the current function */
-       estate->eval_econtext = CreateExprContext(estate->eval_estate);
+       next = simple_econtext_stack->next;
+       pfree(simple_econtext_stack);
+       simple_econtext_stack = next;
+
+       FreeExprContext(estate->eval_econtext, true);
+       estate->eval_econtext = NULL;
 }
 
 /*
@@ -5010,29 +5370,31 @@ plpgsql_xact_cb(XactEvent event, void *arg)
         * If we are doing a clean transaction shutdown, free the EState (so that
         * any remaining resources will be released correctly). In an abort, we
         * expect the regular abort recovery procedures to release everything of
-        * interest.  We don't need to free the individual stack entries since
-        * TopTransactionContext is about to go away anyway.
-        *
-        * Note: if plpgsql_subxact_cb is doing its job, there should be at most
-        * one stack entry, but we may as well code this as a loop.
+        * interest.
         */
        if (event != XACT_EVENT_ABORT)
        {
-               while (simple_estate_stack != NULL)
-               {
-                       FreeExecutorState(simple_estate_stack->xact_eval_estate);
-                       simple_estate_stack = simple_estate_stack->next;
-               }
+               /* Shouldn't be any econtext stack entries left at commit */
+               Assert(simple_econtext_stack == NULL);
+
+               if (simple_eval_estate)
+                       FreeExecutorState(simple_eval_estate);
+               simple_eval_estate = NULL;
        }
        else
-               simple_estate_stack = NULL;
+       {
+               simple_econtext_stack = NULL;
+               simple_eval_estate = NULL;
+       }
 }
 
 /*
  * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
  *
- * If a simple-expression EState was created in the current subtransaction,
- * it has to be cleaned up.
+ * Make sure any simple-expression econtexts created in the current
+ * subtransaction get cleaned up.  We have to do this explicitly because
+ * no other code knows which child econtexts of simple_eval_estate belong
+ * to which level of subxact.
  */
 void
 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
@@ -5041,16 +5403,16 @@ plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
        if (event == SUBXACT_EVENT_START_SUB)
                return;
 
-       if (simple_estate_stack != NULL &&
-               simple_estate_stack->xact_subxid == mySubid)
+       while (simple_econtext_stack != NULL &&
+                  simple_econtext_stack->xact_subxid == mySubid)
        {
-               SimpleEstateStackEntry *next;
+               SimpleEcontextStackEntry *next;
 
-               if (event == SUBXACT_EVENT_COMMIT_SUB)
-                       FreeExecutorState(simple_estate_stack->xact_eval_estate);
-               next = simple_estate_stack->next;
-               pfree(simple_estate_stack);
-               simple_estate_stack = next;
+               FreeExprContext(simple_econtext_stack->stack_econtext,
+                                               (event == SUBXACT_EVENT_COMMIT_SUB));
+               next = simple_econtext_stack->next;
+               pfree(simple_econtext_stack);
+               simple_econtext_stack = next;
        }
 }
 
@@ -5069,3 +5431,158 @@ free_var(PLpgSQL_var *var)
                var->freeval = false;
        }
 }
+
+/*
+ * free old value of a text variable and assign new value from C string
+ */
+static void
+assign_text_var(PLpgSQL_var *var, const char *str)
+{
+       free_var(var);
+       var->value = CStringGetTextDatum(str);
+       var->isnull = false;
+       var->freeval = true;
+}
+
+/*
+ * exec_eval_using_params --- evaluate params of USING clause
+ */
+static PreparedParamsData *
+exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
+{
+       PreparedParamsData *ppd;
+       int                     nargs;
+       int                     i;
+       ListCell   *lc;
+
+       ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
+       nargs = list_length(params);
+
+       ppd->nargs = nargs;
+       ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
+       ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
+       ppd->nulls = (char *) palloc(nargs * sizeof(char));
+       ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
+
+       i = 0;
+       foreach(lc, params)
+       {
+               PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
+               bool            isnull;
+
+               ppd->values[i] = exec_eval_expr(estate, param,
+                                                                               &isnull,
+                                                                               &ppd->types[i]);
+               ppd->nulls[i] = isnull ? 'n' : ' ';
+               ppd->freevals[i] = false;
+
+               /* pass-by-ref non null values must be copied into plpgsql context */
+               if (!isnull)
+               {
+                       int16           typLen;
+                       bool            typByVal;
+
+                       get_typlenbyval(ppd->types[i], &typLen, &typByVal);
+                       if (!typByVal)
+                       {
+                               ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
+                               ppd->freevals[i] = true;
+                       }
+               }
+
+               exec_eval_cleanup(estate);
+
+               i++;
+       }
+
+       return ppd;
+}
+
+/*
+ * free_params_data --- pfree all pass-by-reference values used in USING clause
+ */
+static void
+free_params_data(PreparedParamsData *ppd)
+{
+       int                     i;
+
+       for (i = 0; i < ppd->nargs; i++)
+       {
+               if (ppd->freevals[i])
+                       pfree(DatumGetPointer(ppd->values[i]));
+       }
+
+       pfree(ppd->types);
+       pfree(ppd->values);
+       pfree(ppd->nulls);
+       pfree(ppd->freevals);
+
+       pfree(ppd);
+}
+
+/*
+ * Open portal for dynamic query
+ */
+static Portal
+exec_dynquery_with_params(PLpgSQL_execstate *estate,
+                                                 PLpgSQL_expr *dynquery,
+                                                 List *params,
+                                                 const char *portalname,
+                                                 int cursorOptions)
+{
+       Portal          portal;
+       Datum           query;
+       bool            isnull;
+       Oid                     restype;
+       char       *querystr;
+
+       /*
+        * Evaluate the string expression after the EXECUTE keyword. Its result is
+        * the querystring we have to execute.
+        */
+       query = exec_eval_expr(estate, dynquery, &isnull, &restype);
+       if (isnull)
+               ereport(ERROR,
+                               (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+                                errmsg("query string argument of EXECUTE is null")));
+
+       /* Get the C-String representation */
+       querystr = convert_value_to_string(query, restype);
+
+       exec_eval_cleanup(estate);
+
+       /*
+        * Open an implicit cursor for the query.  We use
+        * SPI_cursor_open_with_args even when there are no params, because this
+        * avoids making and freeing one copy of the plan.
+        */
+       if (params)
+       {
+               PreparedParamsData *ppd;
+
+               ppd = exec_eval_using_params(estate, params);
+               portal = SPI_cursor_open_with_args(portalname,
+                                                                                  querystr,
+                                                                                  ppd->nargs, ppd->types,
+                                                                                  ppd->values, ppd->nulls,
+                                                                                  estate->readonly_func,
+                                                                                  cursorOptions);
+               free_params_data(ppd);
+       }
+       else
+       {
+               portal = SPI_cursor_open_with_args(portalname,
+                                                                                  querystr,
+                                                                                  0, NULL,
+                                                                                  NULL, NULL,
+                                                                                  estate->readonly_func,
+                                                                                  cursorOptions);
+       }
+
+       if (portal == NULL)
+               elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
+                        querystr, SPI_result_code_string(SPI_result));
+       pfree(querystr);
+
+       return portal;
+}