]> granicus.if.org Git - postgresql/blobdiff - src/pl/plperl/plperl.c
Fix typo in comment.
[postgresql] / src / pl / plperl / plperl.c
index 3d81d6095b820cd12b157205b14a8b0d44486723..da1b8780d3f8d749264a6c4dfce63c6ecc9ef3bb 100644 (file)
@@ -4,7 +4,7 @@
  * IDENTIFICATION
  *
  *       This software is copyrighted by Mark Hollomon
- *      but is shameless cribbed from pltcl.c by Jan Weick.
+ *       but is shamelessly cribbed from pltcl.c by Jan Wieck.
  *
  *       The author hereby grants permission  to  use,  copy,  modify,
  *       distribute,  and      license this software and its documentation
  *       ENHANCEMENTS, OR MODIFICATIONS.
  *
  * IDENTIFICATION
- *       $PostgreSQL: pgsql/src/pl/plperl/plperl.c,v 1.52 2004/10/06 16:36:02 momjian Exp $
+ *       $PostgreSQL: pgsql/src/pl/plperl/plperl.c,v 1.103 2006/02/28 23:38:13 neilc Exp $
  *
  **********************************************************************/
 
-#define PLPERL_HAVE_UID_GID
 #include "postgres.h"
+/* Defined by Perl */
+#undef _
 
 /* system stuff */
+#include <ctype.h>
 #include <fcntl.h>
 #include <unistd.h>
+#include <locale.h>
 
 /* postgreSQL stuff */
-#include "access/heapam.h"
-#include "catalog/pg_language.h"
-#include "catalog/pg_proc.h"
-#include "catalog/pg_type.h"
-#include "funcapi.h"                   /* need for SRF support */
 #include "commands/trigger.h"
 #include "executor/spi.h"
-#include "fmgr.h"
-#include "tcop/tcopprot.h"
+#include "funcapi.h"
 #include "utils/lsyscache.h"
-#include "utils/syscache.h"
+#include "utils/memutils.h"
 #include "utils/typcache.h"
+#include "miscadmin.h"
+#include "mb/pg_wchar.h"
 
-/* perl stuff */
-#include "EXTERN.h"
-#include "perl.h"
-#include "XSUB.h"
-#include "ppport.h"
-
-/* just in case these symbols aren't provided */
-#ifndef pTHX_
-#define pTHX_
-#define pTHX void
-#endif
+/* define this before the perl headers get a chance to mangle DLLIMPORT */
+extern DLLIMPORT bool check_function_bodies;
 
+/* perl stuff */
+#include "plperl.h"
 
 /**********************************************************************
  * The information we cache about loaded procedures
@@ -83,30 +75,43 @@ typedef struct plperl_proc_desc
        bool            lanpltrusted;
        bool            fn_retistuple;  /* true, if function returns tuple */
        bool            fn_retisset;    /* true, if function returns set */
-       Oid                     ret_oid;                /* Oid of returning type */
-       FmgrInfo        result_in_func;
+       bool            fn_retisarray;  /* true if function returns array */
+       Oid                     result_oid;             /* Oid of result type */
+       FmgrInfo        result_in_func; /* I/O function and arg for result type */
        Oid                     result_typioparam;
        int                     nargs;
        FmgrInfo        arg_out_func[FUNC_MAX_ARGS];
-       Oid                     arg_typioparam[FUNC_MAX_ARGS];
        bool            arg_is_rowtype[FUNC_MAX_ARGS];
        SV                 *reference;
 } plperl_proc_desc;
 
+/*
+ * The information we cache for the duration of a single call to a
+ * function.
+ */
+typedef struct plperl_call_data
+{
+       plperl_proc_desc *prodesc;
+       FunctionCallInfo  fcinfo;
+       Tuplestorestate  *tuple_store;
+       TupleDesc                 ret_tdesc;
+       AttInMetadata    *attinmeta;
+       MemoryContext     tmp_cxt;
+} plperl_call_data;
+
 
 /**********************************************************************
  * Global data
  **********************************************************************/
-static int     plperl_firstcall = 1;
+static bool plperl_firstcall = true;
 static bool plperl_safe_init_done = false;
 static PerlInterpreter *plperl_interp = NULL;
 static HV  *plperl_proc_hash = NULL;
-static AV  *g_column_keys = NULL;
-static SV  *srf_perlret = NULL; /* keep returned value */
-static int     g_attr_num = 0;
+
+static bool plperl_use_strict = false;
 
 /* this is saved and restored by plperl_call_handler */
-static plperl_proc_desc *plperl_current_prodesc = NULL;
+static plperl_call_data *current_call_data = NULL;
 
 /**********************************************************************
  * Forward declarations
@@ -115,6 +120,7 @@ static void plperl_init_all(void);
 static void plperl_init_interp(void);
 
 Datum          plperl_call_handler(PG_FUNCTION_ARGS);
+Datum          plperl_validator(PG_FUNCTION_ARGS);
 void           plperl_init(void);
 
 static Datum plperl_func_handler(PG_FUNCTION_ARGS);
@@ -122,11 +128,10 @@ static Datum plperl_func_handler(PG_FUNCTION_ARGS);
 static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
 static plperl_proc_desc *compile_plperl_function(Oid fn_oid, bool is_trigger);
 
-static SV  *plperl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc);
+static SV  *plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc);
 static void plperl_init_shared_libs(pTHX);
 static HV  *plperl_spi_execute_fetch_result(SPITupleTable *, int, int);
 
-
 /*
  * This routine is a crock, and so is everyplace that calls it.  The problem
  * is that the cached form of plperl functions/queries is allocated permanently
@@ -144,483 +149,522 @@ perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
        fmgr_info_cxt(functionId, finfo, TopMemoryContext);
 }
 
-/**********************************************************************
- * plperl_init()                       - Initialize everything that can be
- *                                                       safely initialized during postmaster
- *                                                       startup.
- *
- * DO NOT make this static --- it has to be callable by preload
- **********************************************************************/
+
+/* Perform initialization during postmaster startup. */
+
 void
 plperl_init(void)
 {
-       /************************************************************
-        * Do initialization only once
-        ************************************************************/
        if (!plperl_firstcall)
                return;
 
-       /************************************************************
-        * Free the proc hash table
-        ************************************************************/
-       if (plperl_proc_hash != NULL)
-       {
-               hv_undef(plperl_proc_hash);
-               SvREFCNT_dec((SV *) plperl_proc_hash);
-               plperl_proc_hash = NULL;
-       }
+       DefineCustomBoolVariable(
+                                                        "plperl.use_strict",
+         "If true, will compile trusted and untrusted perl code in strict mode",
+                                                        NULL,
+                                                        &plperl_use_strict,
+                                                        PGC_USERSET,
+                                                        NULL, NULL);
 
-       /************************************************************
-        * Destroy the existing Perl interpreter
-        ************************************************************/
-       if (plperl_interp != NULL)
-       {
-               perl_destruct(plperl_interp);
-               perl_free(plperl_interp);
-               plperl_interp = NULL;
-       }
+       EmitWarningsOnPlaceholders("plperl");
 
-       /************************************************************
-        * Now recreate a new Perl interpreter
-        ************************************************************/
        plperl_init_interp();
-
-       plperl_firstcall = 0;
+       plperl_firstcall = false;
 }
 
-/**********************************************************************
- * plperl_init_all()           - Initialize all
- **********************************************************************/
+
+/* Perform initialization during backend startup. */
+
 static void
 plperl_init_all(void)
 {
-
-       /************************************************************
-        * Execute postmaster-startup safe initialization
-        ************************************************************/
        if (plperl_firstcall)
                plperl_init();
 
-       /************************************************************
-        * Any other initialization that must be done each time a new
-        * backend starts -- currently none
-        ************************************************************/
-
+       /* We don't need to do anything yet when a new backend starts. */
 }
 
+/* Each of these macros must represent a single string literal */
+
+#define PERLBOOT \
+       "SPI::bootstrap(); use vars qw(%_SHARED);" \
+       "sub ::plperl_warn { my $msg = shift; " \
+       "       $msg =~ s/\\(eval \\d+\\) //g; &elog(&NOTICE, $msg); } " \
+       "$SIG{__WARN__} = \\&::plperl_warn; " \
+       "sub ::plperl_die { my $msg = shift; " \
+       "       $msg =~ s/\\(eval \\d+\\) //g; die $msg; } " \
+       "$SIG{__DIE__} = \\&::plperl_die; " \
+       "sub ::mkunsafefunc {" \
+       "      my $ret = eval(qq[ sub { $_[0] $_[1] } ]); " \
+       "      $@ =~ s/\\(eval \\d+\\) //g if $@; return $ret; }" \
+       "use strict; " \
+       "sub ::mk_strict_unsafefunc {" \
+       "      my $ret = eval(qq[ sub { use strict; $_[0] $_[1] } ]); " \
+       "      $@ =~ s/\\(eval \\d+\\) //g if $@; return $ret; } " \
+       "sub ::_plperl_to_pg_array {" \
+       "  my $arg = shift; ref $arg eq 'ARRAY' || return $arg; " \
+       "  my $res = ''; my $first = 1; " \
+       "  foreach my $elem (@$arg) " \
+       "  { " \
+       "    $res .= ', ' unless $first; $first = undef; " \
+       "    if (ref $elem) " \
+       "    { " \
+       "      $res .= _plperl_to_pg_array($elem); " \
+       "    } " \
+       "    elsif (defined($elem)) " \
+       "    { " \
+       "      my $str = qq($elem); " \
+       "      $str =~ s/([\"\\\\])/\\\\$1/g; " \
+       "      $res .= qq(\"$str\"); " \
+       "    } " \
+       "    else " \
+       "    { "\
+       "      $res .= 'NULL' ; " \
+       "    } "\
+       "  } " \
+       "  return qq({$res}); " \
+       "} "
+
+#define SAFE_MODULE \
+       "require Safe; $Safe::VERSION"
+
+#define SAFE_OK \
+       "use vars qw($PLContainer); $PLContainer = new Safe('PLPerl');" \
+       "$PLContainer->permit_only(':default');" \
+       "$PLContainer->permit(qw[:base_math !:base_io sort time]);" \
+       "$PLContainer->share(qw[&elog &spi_exec_query &return_next " \
+       "&spi_query &spi_fetchrow " \
+       "&_plperl_to_pg_array " \
+       "&DEBUG &LOG &INFO &NOTICE &WARNING &ERROR %_SHARED ]);" \
+       "sub ::mksafefunc {" \
+       "      my $ret = $PLContainer->reval(qq[sub { $_[0] $_[1] }]); " \
+       "      $@ =~ s/\\(eval \\d+\\) //g if $@; return $ret; }" \
+       "$PLContainer->permit('require'); $PLContainer->reval('use strict;');" \
+       "$PLContainer->deny('require');" \
+       "sub ::mk_strict_safefunc {" \
+       "      my $ret = $PLContainer->reval(qq[sub { BEGIN { strict->import(); } $_[0] $_[1] }]); " \
+       "      $@ =~ s/\\(eval \\d+\\) //g if $@; return $ret; }"
+
+#define SAFE_BAD \
+       "use vars qw($PLContainer); $PLContainer = new Safe('PLPerl');" \
+       "$PLContainer->permit_only(':default');" \
+       "$PLContainer->share(qw[&elog &ERROR ]);" \
+       "sub ::mksafefunc { return $PLContainer->reval(qq[sub { " \
+       "      elog(ERROR,'trusted Perl functions disabled - " \
+       "      please upgrade Perl Safe module to version 2.09 or later');}]); }" \
+       "sub ::mk_strict_safefunc { return $PLContainer->reval(qq[sub { " \
+       "      elog(ERROR,'trusted Perl functions disabled - " \
+       "      please upgrade Perl Safe module to version 2.09 or later');}]); }"
+
 
-/**********************************************************************
- * plperl_init_interp() - Create the Perl interpreter
- **********************************************************************/
 static void
 plperl_init_interp(void)
 {
+       static char *embedding[3] = {
+               "", "-e", PERLBOOT
+       };
 
-       char       *embedding[3] = {
-               "", "-e",
+#ifdef WIN32
 
-               /*
-                * no commas between the next lines please. They are supposed to
-                * be one string
-                */
-               "SPI::bootstrap(); use vars qw(%_SHARED);"
-               "sub ::mkunsafefunc {return eval(qq[ sub { $_[0] $_[1] } ]); }"
-       };
+       /* 
+        * The perl library on startup does horrible things like call
+        * setlocale(LC_ALL,""). We have protected against that on most
+        * platforms by setting the environment appropriately. However, on
+        * Windows, setlocale() does not consult the environment, so we need
+        * to save the existing locale settings before perl has a chance to 
+        * mangle them and restore them after its dirty deeds are done.
+        *
+        * MSDN ref:
+        * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_locale.asp
+        *
+        * It appears that we only need to do this on interpreter startup, and
+        * subsequent calls to the interpreter don't mess with the locale
+        * settings.
+        *
+        * We restore them using Perl's POSIX::setlocale() function so that
+        * Perl doesn't have a different idea of the locale from Postgres.
+        *
+        */
+
+       char *loc;
+       char *save_collate, *save_ctype, *save_monetary, *save_numeric, *save_time;
+       char buf[1024];
+
+       loc = setlocale(LC_COLLATE,NULL);
+       save_collate = loc ? pstrdup(loc) : NULL;
+       loc = setlocale(LC_CTYPE,NULL);
+       save_ctype = loc ? pstrdup(loc) : NULL;
+       loc = setlocale(LC_MONETARY,NULL);
+       save_monetary = loc ? pstrdup(loc) : NULL;
+       loc = setlocale(LC_NUMERIC,NULL);
+       save_numeric = loc ? pstrdup(loc) : NULL;
+       loc = setlocale(LC_TIME,NULL);
+       save_time = loc ? pstrdup(loc) : NULL;
+
+#endif
 
        plperl_interp = perl_alloc();
        if (!plperl_interp)
-               elog(ERROR, "could not allocate perl interpreter");
+               elog(ERROR, "could not allocate Perl interpreter");
 
        perl_construct(plperl_interp);
        perl_parse(plperl_interp, plperl_init_shared_libs, 3, embedding, NULL);
        perl_run(plperl_interp);
 
-       /************************************************************
-        * Initialize the proc and query hash tables
-        ************************************************************/
        plperl_proc_hash = newHV();
 
+#ifdef WIN32
+
+       eval_pv("use POSIX qw(locale_h);", TRUE); /* croak on failure */
+
+       if (save_collate != NULL)
+       {
+               snprintf(buf, sizeof(buf),"setlocale(%s,'%s');",
+                                "LC_COLLATE",save_collate);
+               eval_pv(buf,TRUE);
+               pfree(save_collate);
+       }
+       if (save_ctype != NULL)
+       {
+               snprintf(buf, sizeof(buf),"setlocale(%s,'%s');",
+                                "LC_CTYPE",save_ctype);
+               eval_pv(buf,TRUE);
+               pfree(save_ctype);
+       }
+       if (save_monetary != NULL)
+       {
+               snprintf(buf, sizeof(buf),"setlocale(%s,'%s');",
+                                "LC_MONETARY",save_monetary);
+               eval_pv(buf,TRUE);
+               pfree(save_monetary);
+       }
+       if (save_numeric != NULL)
+       {
+               snprintf(buf, sizeof(buf),"setlocale(%s,'%s');",
+                                "LC_NUMERIC",save_numeric);
+               eval_pv(buf,TRUE);
+               pfree(save_numeric);
+       }
+       if (save_time != NULL)
+       {
+               snprintf(buf, sizeof(buf),"setlocale(%s,'%s');",
+                                "LC_TIME",save_time);
+               eval_pv(buf,TRUE);
+               pfree(save_time);
+       }
+
+#endif
+
 }
 
 
 static void
 plperl_safe_init(void)
 {
-       static char *safe_module =
-       "require Safe; $Safe::VERSION";
-
-       static char *safe_ok =
-       "use vars qw($PLContainer); $PLContainer = new Safe('PLPerl');"
-       "$PLContainer->permit_only(':default');$PLContainer->permit(':base_math');"
-       "$PLContainer->share(qw[&elog &spi_exec_query &DEBUG &LOG &INFO &NOTICE &WARNING &ERROR %SHARED ]);"
-       "sub ::mksafefunc { return $PLContainer->reval(qq[sub { $_[0] $_[1]}]); }"
-                          ;
-
-       static char *safe_bad =
-       "use vars qw($PLContainer); $PLContainer = new Safe('PLPerl');"
-       "$PLContainer->permit_only(':default');$PLContainer->permit(':base_math');"
-       "$PLContainer->share(qw[&elog &DEBUG &LOG &INFO &NOTICE &WARNING &ERROR %SHARED ]);"
-       "sub ::mksafefunc { return $PLContainer->reval(qq[sub { "
-       "elog(ERROR,'trusted perl functions disabled - please upgrade perl Safe module to at least 2.09');}]); }"
-                          ;
-
        SV                 *res;
+       double          safe_version;
 
-       float           safe_version;
-
-       res = eval_pv(safe_module, FALSE);      /* TRUE = croak if failure */
+       res = eval_pv(SAFE_MODULE, FALSE);      /* TRUE = croak if failure */
 
        safe_version = SvNV(res);
 
-       eval_pv((safe_version < 2.09 ? safe_bad : safe_ok), FALSE);
+       /*
+        * We actually want to reject safe_version < 2.09, but it's risky to
+        * assume that floating-point comparisons are exact, so use a slightly
+        * smaller comparison value.
+        */
+       if (safe_version < 2.0899)
+       {
+               /* not safe, so disallow all trusted funcs */
+               eval_pv(SAFE_BAD, FALSE);
+       }
+       else
+       {
+               eval_pv(SAFE_OK, FALSE);
+       }
 
        plperl_safe_init_done = true;
 }
 
-/**********************************************************************
- * turn a tuple into a hash expression and add it to a list
- **********************************************************************/
-static void
-plperl_sv_add_tuple_value(SV *rv, HeapTuple tuple, TupleDesc tupdesc)
+/*
+ * Perl likes to put a newline after its error messages; clean up such
+ */
+static char *
+strip_trailing_ws(const char *msg)
 {
-       int                     i;
-       char       *value;
+       char       *res = pstrdup(msg);
+       int                     len = strlen(res);
+
+       while (len > 0 && isspace((unsigned char) res[len - 1]))
+               res[--len] = '\0';
+       return res;
+}
+
+
+/* Build a tuple from a hash. */
+
+static HeapTuple
+plperl_build_tuple_result(HV *perlhash, AttInMetadata *attinmeta)
+{
+       TupleDesc       td = attinmeta->tupdesc;
+       char      **values;
+       SV                 *val;
        char       *key;
+       I32                     klen;
+       HeapTuple       tup;
 
-       sv_catpvf(rv, "{ ");
+       values = (char **) palloc0(td->natts * sizeof(char *));
 
-       for (i = 0; i < tupdesc->natts; i++)
+       hv_iterinit(perlhash);
+       while ((val = hv_iternextsv(perlhash, &key, &klen)))
        {
-               key = SPI_fname(tupdesc, i + 1);
-               value = SPI_getvalue(tuple, tupdesc, i + 1);
-               if (value)
-                       sv_catpvf(rv, "%s => '%s'", key, value);
-               else
-                       sv_catpvf(rv, "%s => undef", key);
-               if (i != tupdesc->natts - 1)
-                       sv_catpvf(rv, ", ");
+               int                     attn = SPI_fnumber(td, key);
+
+               if (attn <= 0 || td->attrs[attn - 1]->attisdropped)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_UNDEFINED_COLUMN),
+                                        errmsg("Perl hash contains nonexistent column \"%s\"",
+                                                       key)));
+               if (SvOK(val) && SvTYPE(val) != SVt_NULL)
+                       values[attn - 1] = SvPV(val, PL_na);
        }
+       hv_iterinit(perlhash);
 
-       sv_catpvf(rv, " }");
+       tup = BuildTupleFromCStrings(attinmeta, values);
+       pfree(values);
+       return tup;
 }
 
-/**********************************************************************
- * set up arguments for a trigger call
- **********************************************************************/
+/*
+ * convert perl array to postgres string representation
+ */
+static SV  *
+plperl_convert_to_pg_array(SV *src)
+{
+       SV                 *rv;
+       int                     count;
+
+       dSP;
+
+       PUSHMARK(SP);
+       XPUSHs(src);
+       PUTBACK;
+
+       count = call_pv("::_plperl_to_pg_array", G_SCALAR);
+
+       SPAGAIN;
+
+       if (count != 1)
+               elog(ERROR, "unexpected _plperl_to_pg_array failure");
+
+       rv = POPs;
+
+       PUTBACK;
+
+       return rv;
+}
+
+
+/* Set up the arguments for a trigger call. */
+
 static SV  *
 plperl_trigger_build_args(FunctionCallInfo fcinfo)
 {
        TriggerData *tdata;
        TupleDesc       tupdesc;
-       int                     i = 0;
-       SV                 *rv;
+       int                     i;
+       char       *level;
+       char       *event;
+       char       *relid;
+       char       *when;
+       HV                 *hv;
 
-       rv = newSVpv("{ ", 0);
+       hv = newHV();
 
        tdata = (TriggerData *) fcinfo->context;
-
        tupdesc = tdata->tg_relation->rd_att;
 
-       sv_catpvf(rv, "name => '%s'", tdata->tg_trigger->tgname);
-       sv_catpvf(rv, ", relid => '%s'", DatumGetCString(DirectFunctionCall1(oidout, ObjectIdGetDatum(tdata->tg_relation->rd_id))));
+       relid = DatumGetCString(
+                                                       DirectFunctionCall1(oidout,
+                                                                 ObjectIdGetDatum(tdata->tg_relation->rd_id)
+                                                                                               )
+               );
+
+       hv_store(hv, "name", 4, newSVpv(tdata->tg_trigger->tgname, 0), 0);
+       hv_store(hv, "relid", 5, newSVpv(relid, 0), 0);
 
        if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
        {
-               sv_catpvf(rv, ", event => 'INSERT'");
-               sv_catpvf(rv, ", new =>");
-               plperl_sv_add_tuple_value(rv, tdata->tg_trigtuple, tupdesc);
+               event = "INSERT";
+               if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
+                       hv_store(hv, "new", 3,
+                                        plperl_hash_from_tuple(tdata->tg_trigtuple, tupdesc),
+                                        0);
        }
        else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
        {
-               sv_catpvf(rv, ", event => 'DELETE'");
-               sv_catpvf(rv, ", old => ");
-               plperl_sv_add_tuple_value(rv, tdata->tg_trigtuple, tupdesc);
+               event = "DELETE";
+               if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
+                       hv_store(hv, "old", 3,
+                                        plperl_hash_from_tuple(tdata->tg_trigtuple, tupdesc),
+                                        0);
        }
        else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
        {
-               sv_catpvf(rv, ", event => 'UPDATE'");
-
-               sv_catpvf(rv, ", new =>");
-               plperl_sv_add_tuple_value(rv, tdata->tg_newtuple, tupdesc);
-
-               sv_catpvf(rv, ", old => ");
-               plperl_sv_add_tuple_value(rv, tdata->tg_trigtuple, tupdesc);
+               event = "UPDATE";
+               if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
+               {
+                       hv_store(hv, "old", 3,
+                                        plperl_hash_from_tuple(tdata->tg_trigtuple, tupdesc),
+                                        0);
+                       hv_store(hv, "new", 3,
+                                        plperl_hash_from_tuple(tdata->tg_newtuple, tupdesc),
+                                        0);
+               }
        }
        else
-               sv_catpvf(rv, ", event => 'UNKNOWN'");
+               event = "UNKNOWN";
 
-       sv_catpvf(rv, ", argc => %d", tdata->tg_trigger->tgnargs);
+       hv_store(hv, "event", 5, newSVpv(event, 0), 0);
+       hv_store(hv, "argc", 4, newSViv(tdata->tg_trigger->tgnargs), 0);
 
-       if (tdata->tg_trigger->tgnargs != 0)
+       if (tdata->tg_trigger->tgnargs > 0)
        {
-               sv_catpvf(rv, ", args => [ ");
+               AV                 *av = newAV();
+
                for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
-               {
-                       sv_catpvf(rv, "%s", tdata->tg_trigger->tgargs[i]);
-                       if (i != tdata->tg_trigger->tgnargs - 1)
-                               sv_catpvf(rv, ", ");
-               }
-               sv_catpvf(rv, " ]");
+                       av_push(av, newSVpv(tdata->tg_trigger->tgargs[i], 0));
+               hv_store(hv, "args", 4, newRV_noinc((SV *) av), 0);
        }
-       sv_catpvf(rv, ", relname => '%s'", SPI_getrelname(tdata->tg_relation));
+
+       hv_store(hv, "relname", 7,
+                        newSVpv(SPI_getrelname(tdata->tg_relation), 0), 0);
 
        if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
-               sv_catpvf(rv, ", when => 'BEFORE'");
+               when = "BEFORE";
        else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
-               sv_catpvf(rv, ", when => 'AFTER'");
+               when = "AFTER";
        else
-               sv_catpvf(rv, ", when => 'UNKNOWN'");
+               when = "UNKNOWN";
+       hv_store(hv, "when", 4, newSVpv(when, 0), 0);
 
        if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
-               sv_catpvf(rv, ", level => 'ROW'");
+               level = "ROW";
        else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
-               sv_catpvf(rv, ", level => 'STATEMENT'");
+               level = "STATEMENT";
        else
-               sv_catpvf(rv, ", level => 'UNKNOWN'");
-
-       sv_catpvf(rv, " }");
-
-       rv = perl_eval_pv(SvPV(rv, PL_na), TRUE);
-
-       return rv;
-}
-
-
-/**********************************************************************
- * check return value from plperl function
- **********************************************************************/
-static int
-plperl_is_set(SV *sv)
-{
-       int                     i = 0;
-       int                     len = 0;
-       int                     set = 0;
-       int                     other = 0;
-       AV                 *input_av;
-       SV                **val;
-
-       if (SvTYPE(sv) != SVt_RV)
-               return 0;
-
-       if (SvTYPE(SvRV(sv)) == SVt_PVHV)
-               return 0;
+               level = "UNKNOWN";
+       hv_store(hv, "level", 5, newSVpv(level, 0), 0);
 
-       if (SvTYPE(SvRV(sv)) == SVt_PVAV)
-       {
-               input_av = (AV *) SvRV(sv);
-               len = av_len(input_av) + 1;
-
-               for (i = 0; i < len; i++)
-               {
-                       val = av_fetch(input_av, i, FALSE);
-                       if (SvTYPE(*val) == SVt_RV)
-                               set = 1;
-                       else
-                               other = 1;
-               }
-       }
-
-       if (len == 0)
-               return 1;
-       if (set && !other)
-               return 1;
-       if (!set && other)
-               return 0;
-       if (set && other)
-               elog(ERROR, "plperl: check your return value structure");
-       if (!set && !other)
-               elog(ERROR, "plperl: check your return value structure");
-
-       return 0;                                       /* for compiler */
+       return newRV_noinc((SV *) hv);
 }
 
-/**********************************************************************
- * extract a list of keys from a hash
- **********************************************************************/
-static AV  *
-plperl_get_keys(HV *hv)
-{
-       AV                 *ret;
-       int                     key_count;
-       SV                 *val;
-       char       *key;
-       I32                     klen;
 
-       key_count = 0;
-       ret = newAV();
+/* Set up the new tuple returned from a trigger. */
 
-       hv_iterinit(hv);
-       while ((val = hv_iternextsv(hv, (char **) &key, &klen)))
-       {
-               av_store(ret, key_count, eval_pv(key, TRUE));
-               key_count++;
-       }
-       hv_iterinit(hv);
-       return ret;
-}
-
-/**********************************************************************
- * extract a given key (by index) from a list of keys
- **********************************************************************/
-static char *
-plperl_get_key(AV *keys, int index)
-{
-       SV                **svp;
-       int                     len;
-
-       len = av_len(keys) + 1;
-       if (index < len)
-               svp = av_fetch(keys, index, FALSE);
-       else
-               return NULL;
-       return SvPV(*svp, PL_na);
-}
-
-/**********************************************************************
- * extract a value for a given key from a hash
- *
- * return NULL on error or if we got an undef
- *
- **********************************************************************/
-static char *
-plperl_get_elem(HV *hash, char *key)
-{
-       SV                **svp;
-
-       if (hv_exists_ent(hash, eval_pv(key, TRUE), FALSE))
-               svp = hv_fetch(hash, key, strlen(key), FALSE);
-       else
-       {
-               elog(ERROR, "plperl: key '%s' not found", key);
-               return NULL;
-       }
-       return SvTYPE(*svp) == SVt_NULL ? NULL : SvPV(*svp, PL_na);
-}
-
-/**********************************************************************
- * set up the new tuple returned from a trigger
- **********************************************************************/
 static HeapTuple
-plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup, Oid fn_oid)
+plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup)
 {
        SV                **svp;
        HV                 *hvNew;
-       AV                 *plkeys;
-       char       *platt;
-       char       *plval;
        HeapTuple       rtup;
-       int                     natts,
-                               i,
-                               attn,
-                               atti;
-       int                *volatile modattrs = NULL;
-       Datum      *volatile modvalues = NULL;
-       char       *volatile modnulls = NULL;
+       SV                 *val;
+       char       *key;
+       I32                     klen;
+       int                     slotsused;
+       int                *modattrs;
+       Datum      *modvalues;
+       char       *modnulls;
+
        TupleDesc       tupdesc;
-       HeapTuple       typetup;
 
        tupdesc = tdata->tg_relation->rd_att;
 
        svp = hv_fetch(hvTD, "new", 3, FALSE);
+       if (!svp)
+               ereport(ERROR,
+                               (errcode(ERRCODE_UNDEFINED_COLUMN),
+                                errmsg("$_TD->{new} does not exist")));
+       if (!SvOK(*svp) || SvTYPE(*svp) != SVt_RV || SvTYPE(SvRV(*svp)) != SVt_PVHV)
+               ereport(ERROR,
+                               (errcode(ERRCODE_DATATYPE_MISMATCH),
+                                errmsg("$_TD->{new} is not a hash reference")));
        hvNew = (HV *) SvRV(*svp);
 
-       if (SvTYPE(hvNew) != SVt_PVHV)
-               elog(ERROR, "plperl: $_TD->{new} is not a hash");
-
-       plkeys = plperl_get_keys(hvNew);
-       natts = av_len(plkeys) + 1;
-       if (natts != tupdesc->natts)
-               elog(ERROR, "plperl: $_TD->{new} has an incorrect number of keys.");
+       modattrs = palloc(tupdesc->natts * sizeof(int));
+       modvalues = palloc(tupdesc->natts * sizeof(Datum));
+       modnulls = palloc(tupdesc->natts * sizeof(char));
+       slotsused = 0;
 
-       modattrs = palloc0(natts * sizeof(int));
-       modvalues = palloc0(natts * sizeof(Datum));
-       modnulls = palloc0(natts * sizeof(char));
-
-       for (i = 0; i < natts; i++)
+       hv_iterinit(hvNew);
+       while ((val = hv_iternextsv(hvNew, &key, &klen)))
        {
-               FmgrInfo        finfo;
-               Oid                     typinput;
-               Oid                     typelem;
-
-               platt = plperl_get_key(plkeys, i);
+               int                     attn = SPI_fnumber(tupdesc, key);
 
-               attn = modattrs[i] = SPI_fnumber(tupdesc, platt);
-
-               if (attn == SPI_ERROR_NOATTRIBUTE)
-                       elog(ERROR, "plperl: invalid attribute `%s' in tuple.", platt);
-               atti = attn - 1;
-
-               plval = plperl_get_elem(hvNew, platt);
-
-               typetup = SearchSysCache(TYPEOID, ObjectIdGetDatum(tupdesc->attrs[atti]->atttypid), 0, 0, 0);
-               typinput = ((Form_pg_type) GETSTRUCT(typetup))->typinput;
-               typelem = ((Form_pg_type) GETSTRUCT(typetup))->typelem;
-               ReleaseSysCache(typetup);
-               fmgr_info(typinput, &finfo);
-
-               if (plval)
+               if (attn <= 0 || tupdesc->attrs[attn - 1]->attisdropped)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_UNDEFINED_COLUMN),
+                                        errmsg("Perl hash contains nonexistent column \"%s\"",
+                                                       key)));
+               if (SvOK(val) && SvTYPE(val) != SVt_NULL)
                {
-                       modvalues[i] = FunctionCall3(&finfo,
-                                                                                CStringGetDatum(plval),
-                                                                                ObjectIdGetDatum(typelem),
-                                                Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
-                       modnulls[i] = ' ';
+                       Oid                     typinput;
+                       Oid                     typioparam;
+                       FmgrInfo        finfo;
+
+                       /* XXX would be better to cache these lookups */
+                       getTypeInputInfo(tupdesc->attrs[attn - 1]->atttypid,
+                                                        &typinput, &typioparam);
+                       fmgr_info(typinput, &finfo);
+                       modvalues[slotsused] = FunctionCall3(&finfo,
+                                                                                  CStringGetDatum(SvPV(val, PL_na)),
+                                                                                                ObjectIdGetDatum(typioparam),
+                                                Int32GetDatum(tupdesc->attrs[attn - 1]->atttypmod));
+                       modnulls[slotsused] = ' ';
                }
                else
                {
-                       modvalues[i] = (Datum) 0;
-                       modnulls[i] = 'n';
+                       modvalues[slotsused] = (Datum) 0;
+                       modnulls[slotsused] = 'n';
                }
+               modattrs[slotsused] = attn;
+               slotsused++;
        }
-       rtup = SPI_modifytuple(tdata->tg_relation, otup, natts, modattrs, modvalues, modnulls);
+       hv_iterinit(hvNew);
+
+       rtup = SPI_modifytuple(tdata->tg_relation, otup, slotsused,
+                                                  modattrs, modvalues, modnulls);
 
        pfree(modattrs);
        pfree(modvalues);
        pfree(modnulls);
+
        if (rtup == NULL)
-               elog(ERROR, "plperl: SPI_modifytuple failed -- error:  %d", SPI_result);
+               elog(ERROR, "SPI_modifytuple failed: %s",
+                        SPI_result_code_string(SPI_result));
 
        return rtup;
 }
 
-/**********************************************************************
- * plperl_call_handler         - This is the only visible function
- *                               of the PL interpreter. The PostgreSQL
- *                               function manager and trigger manager
- *                               call this function for execution of
- *                               perl procedures.
- **********************************************************************/
+
+/*
+ * This is the only externally-visible part of the plperl call interface.
+ * The Postgres function and trigger managers call it to execute a
+ * perl function.
+ */
 PG_FUNCTION_INFO_V1(plperl_call_handler);
 
-/* keep non-static */
 Datum
 plperl_call_handler(PG_FUNCTION_ARGS)
 {
        Datum           retval;
-       plperl_proc_desc *save_prodesc;
+       plperl_call_data *save_call_data;
 
-       /*
-        * Initialize interpreter if first time through
-        */
        plperl_init_all();
 
-       /*
-        * Ensure that static pointers are saved/restored properly
-        */
-       save_prodesc = plperl_current_prodesc;
-
+       save_call_data = current_call_data;
        PG_TRY();
        {
-               /************************************************************
-                * Connect to SPI manager
-                ************************************************************/
-               if (SPI_connect() != SPI_OK_CONNECT)
-                       elog(ERROR, "could not connect to SPI manager");
-
-               /************************************************************
-                * Determine if called as function or trigger and
-                * call appropriate subhandler
-                ************************************************************/
                if (CALLED_AS_TRIGGER(fcinfo))
                        retval = PointerGetDatum(plperl_trigger_handler(fcinfo));
                else
@@ -628,31 +672,106 @@ plperl_call_handler(PG_FUNCTION_ARGS)
        }
        PG_CATCH();
        {
-               plperl_current_prodesc = save_prodesc;
+               current_call_data = save_call_data;
                PG_RE_THROW();
        }
        PG_END_TRY();
 
-       plperl_current_prodesc = save_prodesc;
-
+       current_call_data = save_call_data;
        return retval;
 }
 
+/*
+ * This is the other externally visible function - it is called when CREATE
+ * FUNCTION is issued to validate the function being created/replaced.
+ */
+PG_FUNCTION_INFO_V1(plperl_validator);
+
+Datum
+plperl_validator(PG_FUNCTION_ARGS)
+{
+       Oid                     funcoid = PG_GETARG_OID(0);
+       HeapTuple       tuple;
+       Form_pg_proc proc;
+       char            functyptype;
+       int                     numargs;
+       Oid                *argtypes;
+       char      **argnames;
+       char       *argmodes;
+       bool            istrigger = false;
+       int                     i;
+
+       /* Get the new function's pg_proc entry */
+       tuple = SearchSysCache(PROCOID,
+                                                  ObjectIdGetDatum(funcoid),
+                                                  0, 0, 0);
+       if (!HeapTupleIsValid(tuple))
+               elog(ERROR, "cache lookup failed for function %u", funcoid);
+       proc = (Form_pg_proc) GETSTRUCT(tuple);
+
+       functyptype = get_typtype(proc->prorettype);
+
+       /* Disallow pseudotype result */
+       /* except for TRIGGER, RECORD, or VOID */
+       if (functyptype == 'p')
+       {
+               /* we assume OPAQUE with no arguments means a trigger */
+               if (proc->prorettype == TRIGGEROID ||
+                       (proc->prorettype == OPAQUEOID && proc->pronargs == 0))
+                       istrigger = true;
+               else if (proc->prorettype != RECORDOID &&
+                                proc->prorettype != VOIDOID)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                        errmsg("plperl functions cannot return type %s",
+                                                       format_type_be(proc->prorettype))));
+       }
+
+       /* Disallow pseudotypes in arguments (either IN or OUT) */
+       numargs = get_func_arg_info(tuple,
+                                                               &argtypes, &argnames, &argmodes);
+       for (i = 0; i < numargs; i++)
+       {
+               if (get_typtype(argtypes[i]) == 'p')
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                        errmsg("plperl functions cannot take type %s",
+                                                       format_type_be(argtypes[i]))));
+       }
+
+       ReleaseSysCache(tuple);
+
+       /* Postpone body checks if !check_function_bodies */
+       if (check_function_bodies)
+       {
+               plperl_proc_desc *prodesc;
+
+               plperl_init_all();
+
+               prodesc = compile_plperl_function(funcoid, istrigger);
+       }
+
+       /* the result of a validator is ignored */
+       PG_RETURN_VOID();
+}
+
+
+/* Uses mksafefunc/mkunsafefunc to create an anonymous sub whose text is
+ * supplied in s, and returns a reference to the closure. */
 
-/**********************************************************************
- * plperl_create_sub()         - calls the perl interpreter to
- *             create the anonymous subroutine whose text is in the SV.
- *             Returns the SV containing the RV to the closure.
- **********************************************************************/
 static SV  *
 plperl_create_sub(char *s, bool trusted)
 {
        dSP;
        SV                 *subref;
        int                     count;
+       char       *compile_sub;
 
        if (trusted && !plperl_safe_init_done)
+       {
                plperl_safe_init();
+               SPAGAIN;
+       }
 
        ENTER;
        SAVETMPS;
@@ -663,11 +782,20 @@ plperl_create_sub(char *s, bool trusted)
 
        /*
         * G_KEEPERR seems to be needed here, else we don't recognize compile
-        * errors properly.  Perhaps it's because there's another level of
-        * eval inside mksafefunc?
+        * errors properly.  Perhaps it's because there's another level of eval
+        * inside mksafefunc?
         */
-       count = perl_call_pv((trusted ? "mksafefunc" : "mkunsafefunc"),
-                                                G_SCALAR | G_EVAL | G_KEEPERR);
+
+       if (trusted && plperl_use_strict)
+               compile_sub = "::mk_strict_safefunc";
+       else if (plperl_use_strict)
+               compile_sub = "::mk_strict_unsafefunc";
+       else if (trusted)
+               compile_sub = "::mksafefunc";
+       else
+               compile_sub = "::mkunsafefunc";
+
+       count = perl_call_pv(compile_sub, G_SCALAR | G_EVAL | G_KEEPERR);
        SPAGAIN;
 
        if (count != 1)
@@ -680,11 +808,14 @@ plperl_create_sub(char *s, bool trusted)
 
        if (SvTRUE(ERRSV))
        {
-               POPs;
+               (void) POPs;
                PUTBACK;
                FREETMPS;
                LEAVE;
-               elog(ERROR, "creation of function failed: %s", SvPV(ERRSV, PL_na));
+               ereport(ERROR,
+                               (errcode(ERRCODE_SYNTAX_ERROR),
+                                errmsg("creation of Perl function failed: %s",
+                                               strip_trailing_ws(SvPV(ERRSV, PL_na)))));
        }
 
        /*
@@ -693,7 +824,7 @@ plperl_create_sub(char *s, bool trusted)
         */
        subref = newSVsv(POPs);
 
-       if (!SvROK(subref))
+       if (!SvROK(subref) || SvTYPE(SvRV(subref)) != SVt_PVCV)
        {
                PUTBACK;
                FREETMPS;
@@ -713,6 +844,7 @@ plperl_create_sub(char *s, bool trusted)
        return subref;
 }
 
+
 /**********************************************************************
  * plperl_init_shared_libs()           -
  *
@@ -734,10 +866,7 @@ plperl_init_shared_libs(pTHX)
        newXS("SPI::bootstrap", boot_SPI, file);
 }
 
-/**********************************************************************
- * plperl_call_perl_func()             - calls a perl function through the RV
- *                     stored in the prodesc structure. massages the input parms properly
- **********************************************************************/
+
 static SV  *
 plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
 {
@@ -745,58 +874,53 @@ plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
        SV                 *retval;
        int                     i;
        int                     count;
+       SV                 *sv;
 
        ENTER;
        SAVETMPS;
 
        PUSHMARK(SP);
-       XPUSHs(sv_2mortal(newSVpv("undef", 0)));
+
+       XPUSHs(&PL_sv_undef);           /* no trigger data */
+
        for (i = 0; i < desc->nargs; i++)
        {
-               if (desc->arg_is_rowtype[i])
+               if (fcinfo->argnull[i])
+                       XPUSHs(&PL_sv_undef);
+               else if (desc->arg_is_rowtype[i])
                {
-                       if (fcinfo->argnull[i])
-                               XPUSHs(&PL_sv_undef);
-                       else
-                       {
-                               HeapTupleHeader td;
-                               Oid                     tupType;
-                               int32           tupTypmod;
-                               TupleDesc       tupdesc;
-                               HeapTupleData tmptup;
-                               SV                 *hashref;
-
-                               td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
-                               /* Extract rowtype info and find a tupdesc */
-                               tupType = HeapTupleHeaderGetTypeId(td);
-                               tupTypmod = HeapTupleHeaderGetTypMod(td);
-                               tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
-                               /* Build a temporary HeapTuple control structure */
-                               tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
-                               tmptup.t_data = td;
-
-                               /*
-                                * plperl_build_tuple_argument better return a mortal SV.
-                                */
-                               hashref = plperl_build_tuple_argument(&tmptup, tupdesc);
-                               XPUSHs(hashref);
-                       }
+                       HeapTupleHeader td;
+                       Oid                     tupType;
+                       int32           tupTypmod;
+                       TupleDesc       tupdesc;
+                       HeapTupleData tmptup;
+                       SV                 *hashref;
+
+                       td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
+                       /* Extract rowtype info and find a tupdesc */
+                       tupType = HeapTupleHeaderGetTypeId(td);
+                       tupTypmod = HeapTupleHeaderGetTypMod(td);
+                       tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
+                       /* Build a temporary HeapTuple control structure */
+                       tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
+                       tmptup.t_data = td;
+
+                       hashref = plperl_hash_from_tuple(&tmptup, tupdesc);
+                       XPUSHs(sv_2mortal(hashref));
                }
                else
                {
-                       if (fcinfo->argnull[i])
-                               XPUSHs(&PL_sv_undef);
-                       else
-                       {
-                               char       *tmp;
-
-                               tmp = DatumGetCString(FunctionCall3(&(desc->arg_out_func[i]),
-                                                                                                       fcinfo->arg[i],
-                                                          ObjectIdGetDatum(desc->arg_typioparam[i]),
-                                                                                                       Int32GetDatum(-1)));
-                               XPUSHs(sv_2mortal(newSVpv(tmp, 0)));
-                               pfree(tmp);
-                       }
+                       char       *tmp;
+
+                       tmp = DatumGetCString(FunctionCall1(&(desc->arg_out_func[i]),
+                                                                                               fcinfo->arg[i]));
+                       sv = newSVpv(tmp, 0);
+#if PERL_BCDVERSION >= 0x5006000L
+                       if (GetDatabaseEncoding() == PG_UTF8)
+                               SvUTF8_on(sv);
+#endif
+                       XPUSHs(sv_2mortal(sv));
+                       pfree(tmp);
                }
        }
        PUTBACK;
@@ -816,11 +940,14 @@ plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
 
        if (SvTRUE(ERRSV))
        {
-               POPs;
+               (void) POPs;
                PUTBACK;
                FREETMPS;
                LEAVE;
-               elog(ERROR, "error from function: %s", SvPV(ERRSV, PL_na));
+               /* XXX need to find a way to assign an errcode here */
+               ereport(ERROR,
+                               (errmsg("error from Perl function: %s",
+                                               strip_trailing_ws(SvPV(ERRSV, PL_na)))));
        }
 
        retval = newSVsv(POPs);
@@ -832,15 +959,14 @@ plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
        return retval;
 }
 
-/**********************************************************************
- * plperl_call_perl_trigger_func()     - calls a perl function affected by trigger
- * through the RV stored in the prodesc structure. massages the input parms properly
- **********************************************************************/
+
 static SV  *
-plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo, SV *td)
+plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo,
+                                                         SV *td)
 {
        dSP;
        SV                 *retval;
+       Trigger    *tg_trigger;
        int                     i;
        int                     count;
 
@@ -848,12 +974,16 @@ plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo, S
        SAVETMPS;
 
        PUSHMARK(sp);
+
        XPUSHs(td);
-       for (i = 0; i < ((TriggerData *) fcinfo->context)->tg_trigger->tgnargs; i++)
-               XPUSHs(sv_2mortal(newSVpv(((TriggerData *) fcinfo->context)->tg_trigger->tgargs[i], 0)));
+
+       tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
+       for (i = 0; i < tg_trigger->tgnargs; i++)
+               XPUSHs(sv_2mortal(newSVpv(tg_trigger->tgargs[i], 0)));
        PUTBACK;
 
-       count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL | G_KEEPERR);
+       /* Do NOT use G_KEEPERR here */
+       count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
 
        SPAGAIN;
 
@@ -862,16 +992,19 @@ plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo, S
                PUTBACK;
                FREETMPS;
                LEAVE;
-               elog(ERROR, "plperl: didn't get a return item from function");
+               elog(ERROR, "didn't get a return item from trigger function");
        }
 
        if (SvTRUE(ERRSV))
        {
-               POPs;
+               (void) POPs;
                PUTBACK;
                FREETMPS;
                LEAVE;
-               elog(ERROR, "plperl: error from function: %s", SvPV(ERRSV, PL_na));
+               /* XXX need to find a way to assign an errcode here */
+               ereport(ERROR,
+                               (errmsg("error from Perl trigger function: %s",
+                                               strip_trailing_ws(SvPV(ERRSV, PL_na)))));
        }
 
        retval = newSVsv(POPs);
@@ -883,40 +1016,44 @@ plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo, S
        return retval;
 }
 
-/**********************************************************************
- * plperl_func_handler()               - Handler for regular function calls
- **********************************************************************/
+
 static Datum
 plperl_func_handler(PG_FUNCTION_ARGS)
 {
        plperl_proc_desc *prodesc;
        SV                 *perlret;
        Datum           retval;
+       ReturnSetInfo *rsi;
+       SV                 *array_ret = NULL;
+
+       /*
+        * Create the call_data beforing connecting to SPI, so that it is
+        * not allocated in the SPI memory context
+        */
+       current_call_data = (plperl_call_data *) palloc0(sizeof(plperl_call_data));
+       current_call_data->fcinfo = fcinfo;
+
+       if (SPI_connect() != SPI_OK_CONNECT)
+               elog(ERROR, "could not connect to SPI manager");
 
-       /* Find or compile the function */
        prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false);
+       current_call_data->prodesc = prodesc;
 
-       plperl_current_prodesc = prodesc;
+       rsi = (ReturnSetInfo *) fcinfo->resultinfo;
 
-       /************************************************************
-        * Call the Perl function if not returning set
-        ************************************************************/
-       if (!prodesc->fn_retisset)
-               perlret = plperl_call_perl_func(prodesc, fcinfo);
-       else
+       if (prodesc->fn_retisset)
        {
-               if (SRF_IS_FIRSTCALL()) /* call function only once */
-                       srf_perlret = plperl_call_perl_func(prodesc, fcinfo);
-               perlret = srf_perlret;
+               /* Check context before allowing the call to go through */
+               if (!rsi || !IsA(rsi, ReturnSetInfo) ||
+                       (rsi->allowedModes & SFRM_Materialize) == 0 ||
+                       rsi->expectedDesc == NULL)
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                        errmsg("set-valued function called in context that "
+                                                       "cannot accept a set")));
        }
 
-       if (prodesc->fn_retisset && SRF_IS_FIRSTCALL())
-       {
-               if (prodesc->fn_retistuple)
-                       g_column_keys = newAV();
-               if (SvTYPE(perlret) != SVt_RV)
-                       elog(ERROR, "plperl: set-returning function must return reference");
-       }
+       perlret = plperl_call_perl_func(prodesc, fcinfo);
 
        /************************************************************
         * Disconnect from SPI manager and then create the return
@@ -924,277 +1061,139 @@ plperl_func_handler(PG_FUNCTION_ARGS)
         * this must not be allocated in the SPI memory context
         * because SPI_finish would free it).
         ************************************************************/
-       if (SPI_finish() != SPI_OK_FINISH)
-               elog(ERROR, "SPI_finish() failed");
-
-       if (!(perlret && SvOK(perlret) && SvTYPE(perlret) != SVt_NULL))
-       {
-               /* return NULL if Perl code returned undef */
-               retval = (Datum) 0;
-               fcinfo->isnull = true;
-       }
-
-       if (prodesc->fn_retisset && !(perlret && SvTYPE(SvRV(perlret)) == SVt_PVAV))
-               elog(ERROR, "plperl: set-returning function must return reference to array");
-
-       if (prodesc->fn_retistuple && perlret && SvTYPE(perlret) != SVt_RV)
-               elog(ERROR, "plperl: composite-returning function must return a reference");
-
-       if (prodesc->fn_retistuple && fcinfo->resultinfo)       /* set of tuples */
-       {
-               /* SRF support */
-               HV                 *ret_hv;
-               AV                 *ret_av;
-
-               FuncCallContext *funcctx;
-               int                     call_cntr;
-               int                     max_calls;
-               TupleDesc       tupdesc;
-               TupleTableSlot *slot;
-               AttInMetadata *attinmeta;
-               bool            isset = 0;
-               char      **values = NULL;
-               ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
-
-               if (prodesc->fn_retisset && !rsinfo)
-                       ereport(ERROR,
-                                       (errcode(ERRCODE_SYNTAX_ERROR),
-                                        errmsg("returning a composite type is not allowed in this context"),
-                                        errhint("This function is intended for use in the FROM clause.")));
-
-
-               isset = plperl_is_set(perlret);
-
-               if (SvTYPE(SvRV(perlret)) == SVt_PVHV)
-                       ret_hv = (HV *) SvRV(perlret);
-               else
-                       ret_av = (AV *) SvRV(perlret);
-
-               if (SRF_IS_FIRSTCALL())
-               {
-                       MemoryContext oldcontext;
-                       int                     i;
-
-                       funcctx = SRF_FIRSTCALL_INIT();
-
-                       oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
-
-                       if (SvTYPE(SvRV(perlret)) == SVt_PVHV)
-                       {
-                               if (isset)
-                                       funcctx->max_calls = hv_iterinit(ret_hv);
-                               else
-                                       funcctx->max_calls = 1;
-                       }
-                       else
-                       {
-                               if (isset)
-                                       funcctx->max_calls = av_len(ret_av) + 1;
-                               else
-                                       funcctx->max_calls = 1;
-                       }
-
-                       tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
-
-                       g_attr_num = tupdesc->natts;
-
-                       for (i = 0; i < tupdesc->natts; i++)
-                               av_store(g_column_keys, i + 1, eval_pv(SPI_fname(tupdesc, i + 1), TRUE));
-
-                       slot = TupleDescGetSlot(tupdesc);
-                       funcctx->slot = slot;
-                       attinmeta = TupleDescGetAttInMetadata(tupdesc);
-                       funcctx->attinmeta = attinmeta;
-                       MemoryContextSwitchTo(oldcontext);
-               }
-
-               funcctx = SRF_PERCALL_SETUP();
-               call_cntr = funcctx->call_cntr;
-               max_calls = funcctx->max_calls;
-               slot = funcctx->slot;
-               attinmeta = funcctx->attinmeta;
-
-               if (call_cntr < max_calls)
-               {
-                       HeapTuple       tuple;
-                       Datum           result;
-                       int                     i;
-                       char       *column_key;
-                       char       *elem;
-
-                       if (isset)
-                       {
-                               HV                 *row_hv;
-                               SV                **svp;
-
-                               svp = av_fetch(ret_av, call_cntr, FALSE);
-
-                               row_hv = (HV *) SvRV(*svp);
+       if (SPI_finish() != SPI_OK_FINISH)
+               elog(ERROR, "SPI_finish() failed");
 
-                               values = (char **) palloc(g_attr_num * sizeof(char *));
+       if (prodesc->fn_retisset)
+       {
+               /*
+                * If the Perl function returned an arrayref, we pretend that it
+                * called return_next() for each element of the array, to handle old
+                * SRFs that didn't know about return_next(). Any other sort of return
+                * value is an error.
+                */
+               if (SvTYPE(perlret) == SVt_RV &&
+                       SvTYPE(SvRV(perlret)) == SVt_PVAV)
+               {
+                       int                     i = 0;
+                       SV                **svp = 0;
+                       AV                 *rav = (AV *) SvRV(perlret);
 
-                               for (i = 0; i < g_attr_num; i++)
-                               {
-                                       column_key = plperl_get_key(g_column_keys, i + 1);
-                                       elem = plperl_get_elem(row_hv, column_key);
-                                       if (elem)
-                                               values[i] = elem;
-                                       else
-                                               values[i] = NULL;
-                               }
-                       }
-                       else
+                       while ((svp = av_fetch(rav, i, FALSE)) != NULL)
                        {
-                               int                     i;
-
-                               values = (char **) palloc(g_attr_num * sizeof(char *));
-                               for (i = 0; i < g_attr_num; i++)
-                               {
-                                       column_key = SPI_fname(tupdesc, i + 1);
-                                       elem = plperl_get_elem(ret_hv, column_key);
-                                       if (elem)
-                                               values[i] = elem;
-                                       else
-                                               values[i] = NULL;
-                               }
+                               plperl_return_next(*svp);
+                               i++;
                        }
-                       tuple = BuildTupleFromCStrings(attinmeta, values);
-                       result = TupleGetDatum(slot, tuple);
-                       SRF_RETURN_NEXT(funcctx, result);
                }
-               else
+               else if (SvTYPE(perlret) != SVt_NULL)
                {
-                       SvREFCNT_dec(perlret);
-                       SRF_RETURN_DONE(funcctx);
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
+                                        errmsg("set-returning Perl function must return "
+                                                       "reference to array or use return_next")));
                }
-       }
-       else if (prodesc->fn_retisset)          /* set of non-tuples */
-       {
-               FuncCallContext *funcctx;
 
-               if (SRF_IS_FIRSTCALL())
+               rsi->returnMode = SFRM_Materialize;
+               if (current_call_data->tuple_store)
                {
-                       MemoryContext oldcontext;
-
-                       funcctx = SRF_FIRSTCALL_INIT();
-                       oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
-
-                       funcctx->max_calls = av_len((AV *) SvRV(perlret)) + 1;
+                       rsi->setResult = current_call_data->tuple_store;
+                       rsi->setDesc = current_call_data->ret_tdesc;
                }
+               retval = (Datum) 0;
+       }
+       else if (SvTYPE(perlret) == SVt_NULL)
+       {
+               /* Return NULL if Perl code returned undef */
+               if (rsi && IsA(rsi, ReturnSetInfo))
+                       rsi->isDone = ExprEndResult;
+               fcinfo->isnull = true;
+               retval = (Datum) 0;
+       }
+       else if (prodesc->fn_retistuple)
+       {
+               /* Return a perl hash converted to a Datum */
+               TupleDesc       td;
+               AttInMetadata *attinmeta;
+               HeapTuple       tup;
 
-               funcctx = SRF_PERCALL_SETUP();
-
-               if (funcctx->call_cntr < funcctx->max_calls)
+               if (!SvOK(perlret) || SvTYPE(perlret) != SVt_RV ||
+                       SvTYPE(SvRV(perlret)) != SVt_PVHV)
                {
-                       Datum           result;
-                       AV                 *array;
-                       SV                **svp;
-
-                       array = (AV *) SvRV(perlret);
-                       svp = av_fetch(array, funcctx->call_cntr, FALSE);
-
-                       if (SvTYPE(*svp) != SVt_NULL)
-                               result = FunctionCall3(&prodesc->result_in_func,
-                                                                          PointerGetDatum(SvPV(*svp, PL_na)),
-                                                       ObjectIdGetDatum(prodesc->result_typioparam),
-                                                                          Int32GetDatum(-1));
-                       else
-                       {
-                               fcinfo->isnull = true;
-                               result = (Datum) 0;
-                       }
-                       SRF_RETURN_NEXT(funcctx, result);
-                       fcinfo->isnull = false;
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_DATATYPE_MISMATCH),
+                                        errmsg("composite-returning Perl function "
+                                                       "must return reference to hash")));
                }
-               else
+
+               /* XXX should cache the attinmeta data instead of recomputing */
+               if (get_call_result_type(fcinfo, NULL, &td) != TYPEFUNC_COMPOSITE)
                {
-                       if (perlret)
-                               SvREFCNT_dec(perlret);
-                       SRF_RETURN_DONE(funcctx);
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                        errmsg("function returning record called in context "
+                                                       "that cannot accept type record")));
                }
+
+               attinmeta = TupleDescGetAttInMetadata(td);
+               tup = plperl_build_tuple_result((HV *) SvRV(perlret), attinmeta);
+               retval = HeapTupleGetDatum(tup);
        }
-       else if (!fcinfo->isnull)       /* non-null singleton */
+       else
        {
+               /* Return a perl string converted to a Datum */
+               char       *val;
 
-
-               if (prodesc->fn_retistuple)             /* singleton perl hash to Datum */
+               if (prodesc->fn_retisarray && SvROK(perlret) &&
+                       SvTYPE(SvRV(perlret)) == SVt_PVAV)
                {
-                       TupleDesc       td = lookup_rowtype_tupdesc(prodesc->ret_oid, (int32) -1);
-                       HV                 *perlhash = (HV *) SvRV(perlret);
-                       int                     i;
-                       char      **values;
-                       char       *key,
-                                          *val;
-                       AttInMetadata *attinmeta;
-                       HeapTuple       tup;
-
-                       if (!td)
-                               ereport(ERROR,
-                                               (errcode(ERRCODE_SYNTAX_ERROR),
-                                                errmsg("no TupleDesc info available")));
-
-                       values = (char **) palloc(td->natts * sizeof(char *));
-                       for (i = 0; i < td->natts; i++)
-                       {
-
-                               key = SPI_fname(td, i + 1);
-                               val = plperl_get_elem(perlhash, key);
-                               if (val)
-                                       values[i] = val;
-                               else
-                                       values[i] = NULL;
-                       }
-                       attinmeta = TupleDescGetAttInMetadata(td);
-                       tup = BuildTupleFromCStrings(attinmeta, values);
-                       retval = HeapTupleGetDatum(tup);
-
+                       array_ret = plperl_convert_to_pg_array(perlret);
+                       SvREFCNT_dec(perlret);
+                       perlret = array_ret;
                }
-               else
-/* perl string to Datum */
 
-                       retval = FunctionCall3(&prodesc->result_in_func,
-                                                                  PointerGetDatum(SvPV(perlret, PL_na)),
-                                                       ObjectIdGetDatum(prodesc->result_typioparam),
-                                                                  Int32GetDatum(-1));
+               val = SvPV(perlret, PL_na);
 
+               retval = FunctionCall3(&prodesc->result_in_func,
+                                                          CStringGetDatum(val),
+                                                          ObjectIdGetDatum(prodesc->result_typioparam),
+                                                          Int32GetDatum(-1));
        }
 
-       SvREFCNT_dec(perlret);
+       if (array_ret == NULL)
+               SvREFCNT_dec(perlret);
+
+       current_call_data = NULL;
        return retval;
 }
 
-/**********************************************************************
- * plperl_trigger_handler()            - Handler for trigger function calls
- **********************************************************************/
+
 static Datum
 plperl_trigger_handler(PG_FUNCTION_ARGS)
 {
        plperl_proc_desc *prodesc;
        SV                 *perlret;
        Datum           retval;
-       char       *tmp;
        SV                 *svTD;
        HV                 *hvTD;
 
-       /* Find or compile the function */
-       prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true);
+       /*
+        * Create the call_data beforing connecting to SPI, so that it is
+        * not allocated in the SPI memory context
+        */
+       current_call_data = (plperl_call_data *) palloc0(sizeof(plperl_call_data));
+       current_call_data->fcinfo = fcinfo;
 
-       plperl_current_prodesc = prodesc;
+       /* Connect to SPI manager */
+       if (SPI_connect() != SPI_OK_CONNECT)
+               elog(ERROR, "could not connect to SPI manager");
 
-       /************************************************************
-       * Call the Perl function
-       ************************************************************/
+       /* Find or compile the function */
+       prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true);
+       current_call_data->prodesc = prodesc;
 
-       /*
-        * call perl trigger function and build TD hash
-        */
        svTD = plperl_trigger_build_args(fcinfo);
        perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
-
-       hvTD = (HV *) SvRV(svTD);       /* convert SV TD structure to Perl Hash
-                                                                * structure */
-
-       tmp = SvPV(perlret, PL_na);
+       hvTD = (HV *) SvRV(svTD);
 
        /************************************************************
        * Disconnect from SPI manager and then create the return
@@ -1203,10 +1202,11 @@ plperl_trigger_handler(PG_FUNCTION_ARGS)
        * because SPI_finish would free it).
        ************************************************************/
        if (SPI_finish() != SPI_OK_FINISH)
-               elog(ERROR, "plperl: SPI_finish() failed");
+               elog(ERROR, "SPI_finish() failed");
 
-       if (!(perlret && SvOK(perlret)))
+       if (!(perlret && SvOK(perlret) && SvTYPE(perlret) != SVt_NULL))
        {
+               /* undef result means go ahead with original tuple */
                TriggerData *trigdata = ((TriggerData *) fcinfo->context);
 
                if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
@@ -1215,53 +1215,56 @@ plperl_trigger_handler(PG_FUNCTION_ARGS)
                        retval = (Datum) trigdata->tg_newtuple;
                else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
                        retval = (Datum) trigdata->tg_trigtuple;
+               else
+                       retval = (Datum) 0; /* can this happen? */
        }
        else
        {
-               if (!fcinfo->isnull)
-               {
+               HeapTuple       trv;
+               char       *tmp;
 
-                       HeapTuple       trv;
-
-                       if (strcasecmp(tmp, "SKIP") == 0)
-                               trv = NULL;
-                       else if (strcasecmp(tmp, "MODIFY") == 0)
-                       {
-                               TriggerData *trigdata = (TriggerData *) fcinfo->context;
+               tmp = SvPV(perlret, PL_na);
 
-                               if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
-                                       trv = plperl_modify_tuple(hvTD, trigdata, trigdata->tg_trigtuple, fcinfo->flinfo->fn_oid);
-                               else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
-                                       trv = plperl_modify_tuple(hvTD, trigdata, trigdata->tg_newtuple, fcinfo->flinfo->fn_oid);
-                               else
-                               {
-                                       trv = NULL;
-                                       elog(WARNING, "plperl: Ignoring modified tuple in DELETE trigger");
-                               }
-                       }
-                       else if (strcasecmp(tmp, "OK"))
-                       {
-                               trv = NULL;
-                               elog(ERROR, "plperl: Expected return to be undef, 'SKIP' or 'MODIFY'");
-                       }
+               if (pg_strcasecmp(tmp, "SKIP") == 0)
+                       trv = NULL;
+               else if (pg_strcasecmp(tmp, "MODIFY") == 0)
+               {
+                       TriggerData *trigdata = (TriggerData *) fcinfo->context;
+
+                       if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
+                               trv = plperl_modify_tuple(hvTD, trigdata,
+                                                                                 trigdata->tg_trigtuple);
+                       else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
+                               trv = plperl_modify_tuple(hvTD, trigdata,
+                                                                                 trigdata->tg_newtuple);
                        else
                        {
+                               ereport(WARNING,
+                                               (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
+                                          errmsg("ignoring modified tuple in DELETE trigger")));
                                trv = NULL;
-                               elog(ERROR, "plperl: Expected return to be undef, 'SKIP' or 'MODIFY'");
                        }
-                       retval = PointerGetDatum(trv);
                }
+               else
+               {
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
+                                        errmsg("result of Perl trigger function must be undef, "
+                                                       "\"SKIP\" or \"MODIFY\"")));
+                       trv = NULL;
+               }
+               retval = PointerGetDatum(trv);
        }
 
-       SvREFCNT_dec(perlret);
+       SvREFCNT_dec(svTD);
+       if (perlret)
+               SvREFCNT_dec(perlret);
 
-       fcinfo->isnull = false;
+       current_call_data = NULL;
        return retval;
 }
 
-/**********************************************************************
- * compile_plperl_function     - compile (or hopefully just look up) function
- **********************************************************************/
+
 static plperl_proc_desc *
 compile_plperl_function(Oid fn_oid, bool is_trigger)
 {
@@ -1271,6 +1274,7 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
        int                     proname_len;
        plperl_proc_desc *prodesc = NULL;
        int                     i;
+       SV                **svp;
 
        /* We'll need the pg_proc tuple in any case... */
        procTup = SearchSysCache(PROCOID,
@@ -1281,7 +1285,7 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
        procStruct = (Form_pg_proc) GETSTRUCT(procTup);
 
        /************************************************************
-        * Build our internal proc name from the functions Oid
+        * Build our internal proc name from the function's Oid
         ************************************************************/
        if (!is_trigger)
                sprintf(internal_proname, "__PLPerl_proc_%u", fn_oid);
@@ -1293,12 +1297,12 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
        /************************************************************
         * Lookup the internal proc name in the hashtable
         ************************************************************/
-       if (hv_exists(plperl_proc_hash, internal_proname, proname_len))
+       svp = hv_fetch(plperl_proc_hash, internal_proname, proname_len, FALSE);
+       if (svp)
        {
                bool            uptodate;
 
-               prodesc = (plperl_proc_desc *) SvIV(*hv_fetch(plperl_proc_hash,
-                                                                         internal_proname, proname_len, 0));
+               prodesc = (plperl_proc_desc *) SvIV(*svp);
 
                /************************************************************
                 * If it's present, must check whether it's still up to date.
@@ -1306,7 +1310,7 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
                 * function's pg_proc entry without changing its OID.
                 ************************************************************/
                uptodate = (prodesc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&
-                       prodesc->fn_cmin == HeapTupleHeaderGetCmin(procTup->t_data));
+                               prodesc->fn_cmin == HeapTupleHeaderGetCmin(procTup->t_data));
 
                if (!uptodate)
                {
@@ -1317,7 +1321,7 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
 
        /************************************************************
         * If we haven't found it in the hashtable, we analyze
-        * the functions arguments and returntype and store
+        * the function's arguments and return type and store
         * the in-/out-functions in the prodesc block and create
         * a new hashtable entry for it.
         *
@@ -1374,7 +1378,7 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
                if (!is_trigger)
                {
                        typeTup = SearchSysCache(TYPEOID,
-                                                               ObjectIdGetDatum(procStruct->prorettype),
+                                                                        ObjectIdGetDatum(procStruct->prorettype),
                                                                         0, 0, 0);
                        if (!HeapTupleIsValid(typeTup))
                        {
@@ -1397,7 +1401,8 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
                                        free(prodesc);
                                        ereport(ERROR,
                                                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                                                        errmsg("trigger functions may only be called as triggers")));
+                                                        errmsg("trigger functions may only be called "
+                                                                       "as triggers")));
                                }
                                else
                                {
@@ -1405,22 +1410,18 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
                                        free(prodesc);
                                        ereport(ERROR,
                                                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                                                errmsg("plperl functions cannot return type %s",
-                                                               format_type_be(procStruct->prorettype))));
+                                                        errmsg("plperl functions cannot return type %s",
+                                                                       format_type_be(procStruct->prorettype))));
                                }
                        }
 
-                       prodesc->fn_retisset = procStruct->proretset;           /* true, if function
-                                                                                                                                * returns set */
+                       prodesc->result_oid = procStruct->prorettype;
+                       prodesc->fn_retisset = procStruct->proretset;
+                       prodesc->fn_retistuple = (typeStruct->typtype == 'c' ||
+                                                                         procStruct->prorettype == RECORDOID);
 
-                       if (typeStruct->typtype == 'c' || procStruct->prorettype == RECORDOID)
-                       {
-                               prodesc->fn_retistuple = true;
-                               prodesc->ret_oid =
-                                       procStruct->prorettype == RECORDOID ?
-                                       typeStruct->typrelid :
-                                       procStruct->prorettype;
-                       }
+                       prodesc->fn_retisarray =
+                               (typeStruct->typlen == -1 && typeStruct->typelem);
 
                        perm_fmgr_info(typeStruct->typinput, &(prodesc->result_in_func));
                        prodesc->result_typioparam = getTypeIOParam(typeTup);
@@ -1438,14 +1439,14 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
                        for (i = 0; i < prodesc->nargs; i++)
                        {
                                typeTup = SearchSysCache(TYPEOID,
-                                                       ObjectIdGetDatum(procStruct->proargtypes[i]),
+                                                ObjectIdGetDatum(procStruct->proargtypes.values[i]),
                                                                                 0, 0, 0);
                                if (!HeapTupleIsValid(typeTup))
                                {
                                        free(prodesc->proname);
                                        free(prodesc);
                                        elog(ERROR, "cache lookup failed for type %u",
-                                                procStruct->proargtypes[i]);
+                                                procStruct->proargtypes.values[i]);
                                }
                                typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
 
@@ -1456,8 +1457,8 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
                                        free(prodesc);
                                        ereport(ERROR,
                                                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-                                                  errmsg("plperl functions cannot take type %s",
-                                                  format_type_be(procStruct->proargtypes[i]))));
+                                                        errmsg("plperl functions cannot take type %s",
+                                               format_type_be(procStruct->proargtypes.values[i]))));
                                }
 
                                if (typeStruct->typtype == 'c')
@@ -1467,7 +1468,6 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
                                        prodesc->arg_is_rowtype[i] = false;
                                        perm_fmgr_info(typeStruct->typoutput,
                                                                   &(prodesc->arg_out_func[i]));
-                                       prodesc->arg_typioparam[i] = getTypeIOParam(typeTup);
                                }
 
                                ReleaseSysCache(typeTup);
@@ -1478,7 +1478,6 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
                 * create the text of the anonymous subroutine.
                 * we do not use a named subroutine so that we can call directly
                 * through the reference.
-                *
                 ************************************************************/
                prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
                                                                          Anum_pg_proc_prosrc, &isnull);
@@ -1492,7 +1491,7 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
                 ************************************************************/
                prodesc->reference = plperl_create_sub(proc_source, prodesc->lanpltrusted);
                pfree(proc_source);
-               if (!prodesc->reference)
+               if (!prodesc->reference)        /* can this happen? */
                {
                        free(prodesc->proname);
                        free(prodesc);
@@ -1500,9 +1499,6 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
                                 internal_proname);
                }
 
-               /************************************************************
-                * Add the proc description block to the hashtable
-                ************************************************************/
                hv_store(plperl_proc_hash, internal_proname, proname_len,
                                 newSViv((IV) prodesc), 0);
        }
@@ -1513,79 +1509,59 @@ compile_plperl_function(Oid fn_oid, bool is_trigger)
 }
 
 
-/**********************************************************************
- * plperl_build_tuple_argument() - Build a string for a ref to a hash
- *                               from all attributes of a given tuple
- **********************************************************************/
+/* Build a hash from all attributes of a given tuple. */
+
 static SV  *
-plperl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc)
+plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
 {
+       HV                 *hv;
        int                     i;
-       SV                 *output;
-       Datum           attr;
-       bool            isnull;
-       char       *attname;
-       char       *outputstr;
-       HeapTuple       typeTup;
-       Oid                     typoutput;
-       Oid                     typioparam;
 
-       output = sv_2mortal(newSVpv("{", 0));
+       hv = newHV();
 
        for (i = 0; i < tupdesc->natts; i++)
        {
-               /* ignore dropped attributes */
+               Datum           attr;
+               bool            isnull;
+               char       *attname;
+               char       *outputstr;
+               Oid                     typoutput;
+               bool            typisvarlena;
+               int                     namelen;
+               SV                 *sv;
+
                if (tupdesc->attrs[i]->attisdropped)
                        continue;
 
-               /************************************************************
-                * Get the attribute name
-                ************************************************************/
-               attname = tupdesc->attrs[i]->attname.data;
-
-               /************************************************************
-                * Get the attributes value
-                ************************************************************/
+               attname = NameStr(tupdesc->attrs[i]->attname);
+               namelen = strlen(attname);
                attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
 
-               /************************************************************
-                *      If it is null it will be set to undef in the hash.
-                ************************************************************/
                if (isnull)
                {
-                       sv_catpvf(output, "'%s' => undef,", attname);
+                       /* Store (attname => undef) and move on. */
+                       hv_store(hv, attname, namelen, newSV(0), 0);
                        continue;
                }
 
-               /************************************************************
-                * Lookup the attribute type in the syscache
-                * for the output function
-                ************************************************************/
-               typeTup = SearchSysCache(TYPEOID,
-                                                  ObjectIdGetDatum(tupdesc->attrs[i]->atttypid),
-                                                                0, 0, 0);
-               if (!HeapTupleIsValid(typeTup))
-                       elog(ERROR, "cache lookup failed for type %u",
-                                tupdesc->attrs[i]->atttypid);
+               /* XXX should have a way to cache these lookups */
 
-               typoutput = ((Form_pg_type) GETSTRUCT(typeTup))->typoutput;
-               typioparam = getTypeIOParam(typeTup);
-               ReleaseSysCache(typeTup);
+               getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
+                                                 &typoutput, &typisvarlena);
+
+               outputstr = DatumGetCString(OidFunctionCall1(typoutput, attr));
+
+               sv = newSVpv(outputstr, 0);
+#if PERL_BCDVERSION >= 0x5006000L
+               if (GetDatabaseEncoding() == PG_UTF8)
+                       SvUTF8_on(sv);
+#endif
+               hv_store(hv, attname, namelen, sv, 0);
 
-               /************************************************************
-                * Append the attribute name and the value to the list.
-                ************************************************************/
-               outputstr = DatumGetCString(OidFunctionCall3(typoutput,
-                                                                                                        attr,
-                                                                                       ObjectIdGetDatum(typioparam),
-                                                  Int32GetDatum(tupdesc->attrs[i]->atttypmod)));
-               sv_catpvf(output, "'%s' => '%s',", attname, outputstr);
                pfree(outputstr);
        }
 
-       sv_catpv(output, "}");
-       output = perl_eval_pv(SvPV(output, PL_na), TRUE);
-       return output;
+       return newRV_noinc((SV *) hv);
 }
 
 
@@ -1593,46 +1569,74 @@ HV *
 plperl_spi_exec(char *query, int limit)
 {
        HV                 *ret_hv;
-       int                     spi_rv;
 
-       spi_rv = SPI_execute(query, plperl_current_prodesc->fn_readonly, limit);
-       ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed, spi_rv);
+       /*
+        * Execute the query inside a sub-transaction, so we can cope with errors
+        * sanely
+        */
+       MemoryContext oldcontext = CurrentMemoryContext;
+       ResourceOwner oldowner = CurrentResourceOwner;
 
-       return ret_hv;
-}
+       BeginInternalSubTransaction(NULL);
+       /* Want to run inside function's memory context */
+       MemoryContextSwitchTo(oldcontext);
 
-static HV  *
-plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
-{
-       int                     i;
-       char       *attname;
-       char       *attdata;
+       PG_TRY();
+       {
+               int                     spi_rv;
 
-       HV                 *array;
+               spi_rv = SPI_execute(query, current_call_data->prodesc->fn_readonly,
+                                                        limit);
+               ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
+                                                                                                spi_rv);
 
-       array = newHV();
+               /* Commit the inner transaction, return to outer xact context */
+               ReleaseCurrentSubTransaction();
+               MemoryContextSwitchTo(oldcontext);
+               CurrentResourceOwner = oldowner;
 
-       for (i = 0; i < tupdesc->natts; i++)
+               /*
+                * AtEOSubXact_SPI() should not have popped any SPI context, but just
+                * in case it did, make sure we remain connected.
+                */
+               SPI_restore_connection();
+       }
+       PG_CATCH();
        {
-               /************************************************************
-               * Get the attribute name
-               ************************************************************/
-               attname = tupdesc->attrs[i]->attname.data;
+               ErrorData  *edata;
 
-               /************************************************************
-               * Get the attributes value
-               ************************************************************/
-               attdata = SPI_getvalue(tuple, tupdesc, i + 1);
-               if (attdata)
-                       hv_store(array, attname, strlen(attname), newSVpv(attdata, 0), 0);
-               else
-                       hv_store(array, attname, strlen(attname), newSVpv("undef", 0), 0);
+               /* Save error info */
+               MemoryContextSwitchTo(oldcontext);
+               edata = CopyErrorData();
+               FlushErrorState();
+
+               /* Abort the inner transaction */
+               RollbackAndReleaseCurrentSubTransaction();
+               MemoryContextSwitchTo(oldcontext);
+               CurrentResourceOwner = oldowner;
+
+               /*
+                * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
+                * have left us in a disconnected state.  We need this hack to return
+                * to connected state.
+                */
+               SPI_restore_connection();
+
+               /* Punt the error to Perl */
+               croak("%s", edata->message);
+
+               /* Can't get here, but keep compiler quiet */
+               return NULL;
        }
-       return array;
+       PG_END_TRY();
+
+       return ret_hv;
 }
 
+
 static HV  *
-plperl_spi_execute_fetch_result(SPITupleTable *tuptable, int processed, int status)
+plperl_spi_execute_fetch_result(SPITupleTable *tuptable, int processed,
+                                                               int status)
 {
        HV                 *result;
 
@@ -1645,24 +1649,299 @@ plperl_spi_execute_fetch_result(SPITupleTable *tuptable, int processed, int stat
 
        if (status == SPI_OK_SELECT)
        {
-               if (processed)
+               AV                 *rows;
+               SV                 *row;
+               int                     i;
+
+               rows = newAV();
+               for (i = 0; i < processed; i++)
+               {
+                       row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc);
+                       av_push(rows, row);
+               }
+               hv_store(result, "rows", strlen("rows"),
+                                newRV_noinc((SV *) rows), 0);
+       }
+
+       SPI_freetuptable(tuptable);
+
+       return result;
+}
+
+
+/*
+ * Note: plperl_return_next is called both in Postgres and Perl contexts.
+ * We report any errors in Postgres fashion (via ereport).     If called in
+ * Perl context, it is SPI.xs's responsibility to catch the error and
+ * convert to a Perl error.  We assume (perhaps without adequate justification)
+ * that we need not abort the current transaction if the Perl code traps the
+ * error.
+ */
+void
+plperl_return_next(SV *sv)
+{
+       plperl_proc_desc *prodesc;
+       FunctionCallInfo fcinfo;
+       ReturnSetInfo *rsi;
+       MemoryContext old_cxt;
+       HeapTuple       tuple;
+
+       if (!sv)
+               return;
+
+       prodesc = current_call_data->prodesc;
+       fcinfo = current_call_data->fcinfo;
+       rsi = (ReturnSetInfo *) fcinfo->resultinfo;
+
+       if (!prodesc->fn_retisset)
+               ereport(ERROR,
+                               (errcode(ERRCODE_SYNTAX_ERROR),
+                                errmsg("cannot use return_next in a non-SETOF function")));
+
+       if (prodesc->fn_retistuple &&
+               !(SvOK(sv) && SvTYPE(sv) == SVt_RV && SvTYPE(SvRV(sv)) == SVt_PVHV))
+               ereport(ERROR,
+                               (errcode(ERRCODE_DATATYPE_MISMATCH),
+                                errmsg("setof-composite-returning Perl function "
+                                               "must call return_next with reference to hash")));
+
+       if (!current_call_data->ret_tdesc)
+       {
+               TupleDesc tupdesc;
+
+               Assert(!current_call_data->tuple_store);
+               Assert(!current_call_data->attinmeta);
+
+               /*
+                * This is the first call to return_next in the current
+                * PL/Perl function call, so memoize some lookups
+                */
+               if (prodesc->fn_retistuple)
+                       (void) get_call_result_type(fcinfo, NULL, &tupdesc);
+               else
+                       tupdesc = rsi->expectedDesc;
+
+               /*
+                * Make sure the tuple_store and ret_tdesc are sufficiently
+                * long-lived.
+                */
+               old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
+
+               current_call_data->ret_tdesc = CreateTupleDescCopy(tupdesc);
+               current_call_data->tuple_store =
+                       tuplestore_begin_heap(true, false, work_mem);
+               if (prodesc->fn_retistuple)
+               {
+                       current_call_data->attinmeta =
+                               TupleDescGetAttInMetadata(current_call_data->ret_tdesc);
+               }
+
+               MemoryContextSwitchTo(old_cxt);
+       }               
+
+       /*
+        * Producing the tuple we want to return requires making plenty of
+        * palloc() allocations that are not cleaned up. Since this
+        * function can be called many times before the current memory
+        * context is reset, we need to do those allocations in a
+        * temporary context.
+        */
+       if (!current_call_data->tmp_cxt)
+       {
+               current_call_data->tmp_cxt =
+                       AllocSetContextCreate(rsi->econtext->ecxt_per_tuple_memory,
+                                                                 "PL/Perl return_next temporary cxt",
+                                                                 ALLOCSET_DEFAULT_MINSIZE,
+                                                                 ALLOCSET_DEFAULT_INITSIZE,
+                                                                 ALLOCSET_DEFAULT_MAXSIZE);
+       }
+
+       old_cxt = MemoryContextSwitchTo(current_call_data->tmp_cxt);
+
+       if (prodesc->fn_retistuple)
+       {
+               tuple = plperl_build_tuple_result((HV *) SvRV(sv),
+                                                                                 current_call_data->attinmeta);
+       }
+       else
+       {
+               Datum           ret = (Datum) 0;
+               bool            isNull = true;
+
+               if (SvOK(sv) && SvTYPE(sv) != SVt_NULL)
                {
-                       AV                 *rows;
-                       HV                 *row;
-                       int                     i;
+                       char       *val = SvPV(sv, PL_na);
+
+                       ret = FunctionCall3(&prodesc->result_in_func,
+                                                               PointerGetDatum(val),
+                                                               ObjectIdGetDatum(prodesc->result_typioparam),
+                                                               Int32GetDatum(-1));
+                       isNull = false;
+               }
+
+               tuple = heap_form_tuple(current_call_data->ret_tdesc, &ret, &isNull);
+       }
+
+       /* Make sure to store the tuple in a long-lived memory context */
+       MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
+       tuplestore_puttuple(current_call_data->tuple_store, tuple);
+       MemoryContextSwitchTo(old_cxt);
 
-                       rows = newAV();
-                       for (i = 0; i < processed; i++)
+       MemoryContextReset(current_call_data->tmp_cxt);
+}
+
+
+SV *
+plperl_spi_query(char *query)
+{
+       SV                 *cursor;
+
+       /*
+        * Execute the query inside a sub-transaction, so we can cope with errors
+        * sanely
+        */
+       MemoryContext oldcontext = CurrentMemoryContext;
+       ResourceOwner oldowner = CurrentResourceOwner;
+
+       BeginInternalSubTransaction(NULL);
+       /* Want to run inside function's memory context */
+       MemoryContextSwitchTo(oldcontext);
+
+       PG_TRY();
+       {
+               void       *plan;
+               Portal          portal = NULL;
+
+               /* Create a cursor for the query */
+               plan = SPI_prepare(query, 0, NULL);
+               if (plan)
+                       portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
+               if (portal)
+                       cursor = newSVpv(portal->name, 0);
+               else
+                       cursor = newSV(0);
+
+               /* Commit the inner transaction, return to outer xact context */
+               ReleaseCurrentSubTransaction();
+               MemoryContextSwitchTo(oldcontext);
+               CurrentResourceOwner = oldowner;
+
+               /*
+                * AtEOSubXact_SPI() should not have popped any SPI context, but just
+                * in case it did, make sure we remain connected.
+                */
+               SPI_restore_connection();
+       }
+       PG_CATCH();
+       {
+               ErrorData  *edata;
+
+               /* Save error info */
+               MemoryContextSwitchTo(oldcontext);
+               edata = CopyErrorData();
+               FlushErrorState();
+
+               /* Abort the inner transaction */
+               RollbackAndReleaseCurrentSubTransaction();
+               MemoryContextSwitchTo(oldcontext);
+               CurrentResourceOwner = oldowner;
+
+               /*
+                * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
+                * have left us in a disconnected state.  We need this hack to return
+                * to connected state.
+                */
+               SPI_restore_connection();
+
+               /* Punt the error to Perl */
+               croak("%s", edata->message);
+
+               /* Can't get here, but keep compiler quiet */
+               return NULL;
+       }
+       PG_END_TRY();
+
+       return cursor;
+}
+
+
+SV *
+plperl_spi_fetchrow(char *cursor)
+{
+       SV                 *row;
+
+       /*
+        * Execute the FETCH inside a sub-transaction, so we can cope with errors
+        * sanely
+        */
+       MemoryContext oldcontext = CurrentMemoryContext;
+       ResourceOwner oldowner = CurrentResourceOwner;
+
+       BeginInternalSubTransaction(NULL);
+       /* Want to run inside function's memory context */
+       MemoryContextSwitchTo(oldcontext);
+
+       PG_TRY();
+       {
+               Portal          p = SPI_cursor_find(cursor);
+
+               if (!p)
+                       row = newSV(0);
+               else
+               {
+                       SPI_cursor_fetch(p, true, 1);
+                       if (SPI_processed == 0)
                        {
-                               row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc);
-                               av_store(rows, i, newRV_noinc((SV *) row));
+                               SPI_cursor_close(p);
+                               row = newSV(0);
                        }
-                       hv_store(result, "rows", strlen("rows"),
-                                        newRV_noinc((SV *) rows), 0);
+                       else
+                       {
+                               row = plperl_hash_from_tuple(SPI_tuptable->vals[0],
+                                                                                        SPI_tuptable->tupdesc);
+                       }
+                       SPI_freetuptable(SPI_tuptable);
                }
+
+               /* Commit the inner transaction, return to outer xact context */
+               ReleaseCurrentSubTransaction();
+               MemoryContextSwitchTo(oldcontext);
+               CurrentResourceOwner = oldowner;
+
+               /*
+                * AtEOSubXact_SPI() should not have popped any SPI context, but just
+                * in case it did, make sure we remain connected.
+                */
+               SPI_restore_connection();
        }
+       PG_CATCH();
+       {
+               ErrorData  *edata;
 
-       SPI_freetuptable(tuptable);
+               /* Save error info */
+               MemoryContextSwitchTo(oldcontext);
+               edata = CopyErrorData();
+               FlushErrorState();
 
-       return result;
+               /* Abort the inner transaction */
+               RollbackAndReleaseCurrentSubTransaction();
+               MemoryContextSwitchTo(oldcontext);
+               CurrentResourceOwner = oldowner;
+
+               /*
+                * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
+                * have left us in a disconnected state.  We need this hack to return
+                * to connected state.
+                */
+               SPI_restore_connection();
+
+               /* Punt the error to Perl */
+               croak("%s", edata->message);
+
+               /* Can't get here, but keep compiler quiet */
+               return NULL;
+       }
+       PG_END_TRY();
+
+       return row;
 }