LCOV - code coverage report
Current view: top level - src/pl/plperl - plperl.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 89.0 % 1433 1276
Test Date: 2026-03-24 02:15:55 Functions: 100.0 % 73 73
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /**********************************************************************
       2              :  * plperl.c - perl as a procedural language for PostgreSQL
       3              :  *
       4              :  *    src/pl/plperl/plperl.c
       5              :  *
       6              :  **********************************************************************/
       7              : 
       8              : #include "postgres.h"
       9              : 
      10              : /* system stuff */
      11              : #include <ctype.h>
      12              : #include <fcntl.h>
      13              : #include <limits.h>
      14              : #include <unistd.h>
      15              : 
      16              : /* postgreSQL stuff */
      17              : #include "access/htup_details.h"
      18              : #include "access/xact.h"
      19              : #include "catalog/pg_language.h"
      20              : #include "catalog/pg_proc.h"
      21              : #include "catalog/pg_type.h"
      22              : #include "commands/event_trigger.h"
      23              : #include "commands/trigger.h"
      24              : #include "executor/spi.h"
      25              : #include "funcapi.h"
      26              : #include "miscadmin.h"
      27              : #include "parser/parse_type.h"
      28              : #include "storage/ipc.h"
      29              : #include "tcop/tcopprot.h"
      30              : #include "utils/builtins.h"
      31              : #include "utils/fmgroids.h"
      32              : #include "utils/guc.h"
      33              : #include "utils/hsearch.h"
      34              : #include "utils/lsyscache.h"
      35              : #include "utils/memutils.h"
      36              : #include "utils/rel.h"
      37              : #include "utils/syscache.h"
      38              : #include "utils/tuplestore.h"
      39              : #include "utils/typcache.h"
      40              : 
      41              : /* define our text domain for translations */
      42              : #undef TEXTDOMAIN
      43              : #define TEXTDOMAIN PG_TEXTDOMAIN("plperl")
      44              : 
      45              : /* perl stuff */
      46              : /* string literal macros defining chunks of perl code */
      47              : #include "perlchunks.h"
      48              : #include "plperl.h"
      49              : /* defines PLPERL_SET_OPMASK */
      50              : #include "plperl_opmask.h"
      51              : 
      52              : EXTERN_C void boot_DynaLoader(pTHX_ CV *cv);
      53              : EXTERN_C void boot_PostgreSQL__InServer__Util(pTHX_ CV *cv);
      54              : EXTERN_C void boot_PostgreSQL__InServer__SPI(pTHX_ CV *cv);
      55              : 
      56           24 : PG_MODULE_MAGIC_EXT(
      57              :                     .name = "plperl",
      58              :                     .version = PG_VERSION
      59              : );
      60              : 
      61              : /**********************************************************************
      62              :  * Information associated with a Perl interpreter.  We have one interpreter
      63              :  * that is used for all plperlu (untrusted) functions.  For plperl (trusted)
      64              :  * functions, there is a separate interpreter for each effective SQL userid.
      65              :  * (This is needed to ensure that an unprivileged user can't inject Perl code
      66              :  * that'll be executed with the privileges of some other SQL user.)
      67              :  *
      68              :  * The plperl_interp_desc structs are kept in a Postgres hash table indexed
      69              :  * by userid OID, with OID 0 used for the single untrusted interpreter.
      70              :  * Once created, an interpreter is kept for the life of the process.
      71              :  *
      72              :  * We start out by creating a "held" interpreter, which we initialize
      73              :  * only as far as we can do without deciding if it will be trusted or
      74              :  * untrusted.  Later, when we first need to run a plperl or plperlu
      75              :  * function, we complete the initialization appropriately and move the
      76              :  * PerlInterpreter pointer into the plperl_interp_hash hashtable.  If after
      77              :  * that we need more interpreters, we create them as needed if we can, or
      78              :  * fail if the Perl build doesn't support multiple interpreters.
      79              :  *
      80              :  * The reason for all the dancing about with a held interpreter is to make
      81              :  * it possible for people to preload a lot of Perl code at postmaster startup
      82              :  * (using plperl.on_init) and then use that code in backends.  Of course this
      83              :  * will only work for the first interpreter created in any backend, but it's
      84              :  * still useful with that restriction.
      85              :  **********************************************************************/
      86              : typedef struct plperl_interp_desc
      87              : {
      88              :     Oid         user_id;        /* Hash key (must be first!) */
      89              :     PerlInterpreter *interp;    /* The interpreter */
      90              :     HTAB       *query_hash;     /* plperl_query_entry structs */
      91              : } plperl_interp_desc;
      92              : 
      93              : 
      94              : /**********************************************************************
      95              :  * The information we cache about loaded procedures
      96              :  *
      97              :  * The fn_refcount field counts the struct's reference from the hash table
      98              :  * shown below, plus one reference for each function call level that is using
      99              :  * the struct.  We can release the struct, and the associated Perl sub, when
     100              :  * the fn_refcount goes to zero.  Releasing the struct itself is done by
     101              :  * deleting the fn_cxt, which also gets rid of all subsidiary data.
     102              :  **********************************************************************/
     103              : typedef struct plperl_proc_desc
     104              : {
     105              :     char       *proname;        /* user name of procedure */
     106              :     MemoryContext fn_cxt;       /* memory context for this procedure */
     107              :     unsigned long fn_refcount;  /* number of active references */
     108              :     TransactionId fn_xmin;      /* xmin/TID of procedure's pg_proc tuple */
     109              :     ItemPointerData fn_tid;
     110              :     SV         *reference;      /* CODE reference for Perl sub */
     111              :     plperl_interp_desc *interp; /* interpreter it's created in */
     112              :     bool        fn_readonly;    /* is function readonly (not volatile)? */
     113              :     Oid         lang_oid;
     114              :     List       *trftypes;
     115              :     bool        lanpltrusted;   /* is it plperl, rather than plperlu? */
     116              :     bool        fn_retistuple;  /* true, if function returns tuple */
     117              :     bool        fn_retisset;    /* true, if function returns set */
     118              :     bool        fn_retisarray;  /* true if function returns array */
     119              :     /* Conversion info for function's result type: */
     120              :     Oid         result_oid;     /* Oid of result type */
     121              :     FmgrInfo    result_in_func; /* I/O function and arg for result type */
     122              :     Oid         result_typioparam;
     123              :     /* Per-argument info for function's argument types: */
     124              :     int         nargs;
     125              :     FmgrInfo   *arg_out_func;   /* output fns for arg types */
     126              :     bool       *arg_is_rowtype; /* is each arg composite? */
     127              :     Oid        *arg_arraytype;  /* InvalidOid if not an array */
     128              : } plperl_proc_desc;
     129              : 
     130              : #define increment_prodesc_refcount(prodesc)  \
     131              :     ((prodesc)->fn_refcount++)
     132              : #define decrement_prodesc_refcount(prodesc)  \
     133              :     do { \
     134              :         Assert((prodesc)->fn_refcount > 0); \
     135              :         if (--((prodesc)->fn_refcount) == 0) \
     136              :             free_plperl_function(prodesc); \
     137              :     } while(0)
     138              : 
     139              : /**********************************************************************
     140              :  * For speedy lookup, we maintain a hash table mapping from
     141              :  * function OID + trigger flag + user OID to plperl_proc_desc pointers.
     142              :  * The reason the plperl_proc_desc struct isn't directly part of the hash
     143              :  * entry is to simplify recovery from errors during compile_plperl_function.
     144              :  *
     145              :  * Note: if the same function is called by multiple userIDs within a session,
     146              :  * there will be a separate plperl_proc_desc entry for each userID in the case
     147              :  * of plperl functions, but only one entry for plperlu functions, because we
     148              :  * set user_id = 0 for that case.  If the user redeclares the same function
     149              :  * from plperl to plperlu or vice versa, there might be multiple
     150              :  * plperl_proc_ptr entries in the hashtable, but only one is valid.
     151              :  **********************************************************************/
     152              : typedef struct plperl_proc_key
     153              : {
     154              :     Oid         proc_id;        /* Function OID */
     155              : 
     156              :     /*
     157              :      * is_trigger is really a bool, but declare as Oid to ensure this struct
     158              :      * contains no padding
     159              :      */
     160              :     Oid         is_trigger;     /* is it a trigger function? */
     161              :     Oid         user_id;        /* User calling the function, or 0 */
     162              : } plperl_proc_key;
     163              : 
     164              : typedef struct plperl_proc_ptr
     165              : {
     166              :     plperl_proc_key proc_key;   /* Hash key (must be first!) */
     167              :     plperl_proc_desc *proc_ptr;
     168              : } plperl_proc_ptr;
     169              : 
     170              : /*
     171              :  * The information we cache for the duration of a single call to a
     172              :  * function.
     173              :  */
     174              : typedef struct plperl_call_data
     175              : {
     176              :     plperl_proc_desc *prodesc;
     177              :     FunctionCallInfo fcinfo;
     178              :     /* remaining fields are used only in a function returning set: */
     179              :     Tuplestorestate *tuple_store;
     180              :     TupleDesc   ret_tdesc;
     181              :     Oid         cdomain_oid;    /* 0 unless returning domain-over-composite */
     182              :     void       *cdomain_info;
     183              :     MemoryContext tmp_cxt;
     184              : } plperl_call_data;
     185              : 
     186              : /**********************************************************************
     187              :  * The information we cache about prepared and saved plans
     188              :  **********************************************************************/
     189              : typedef struct plperl_query_desc
     190              : {
     191              :     char        qname[24];
     192              :     MemoryContext plan_cxt;     /* context holding this struct */
     193              :     SPIPlanPtr  plan;
     194              :     int         nargs;
     195              :     Oid        *argtypes;
     196              :     FmgrInfo   *arginfuncs;
     197              :     Oid        *argtypioparams;
     198              : } plperl_query_desc;
     199              : 
     200              : /* hash table entry for query desc  */
     201              : 
     202              : typedef struct plperl_query_entry
     203              : {
     204              :     char        query_name[NAMEDATALEN];
     205              :     plperl_query_desc *query_data;
     206              : } plperl_query_entry;
     207              : 
     208              : /**********************************************************************
     209              :  * Information for PostgreSQL - Perl array conversion.
     210              :  **********************************************************************/
     211              : typedef struct plperl_array_info
     212              : {
     213              :     int         ndims;
     214              :     bool        elem_is_rowtype;    /* 't' if element type is a rowtype */
     215              :     Datum      *elements;
     216              :     bool       *nulls;
     217              :     int        *nelems;
     218              :     FmgrInfo    proc;
     219              :     FmgrInfo    transform_proc;
     220              : } plperl_array_info;
     221              : 
     222              : /**********************************************************************
     223              :  * Global data
     224              :  **********************************************************************/
     225              : 
     226              : static HTAB *plperl_interp_hash = NULL;
     227              : static HTAB *plperl_proc_hash = NULL;
     228              : static plperl_interp_desc *plperl_active_interp = NULL;
     229              : 
     230              : /* If we have an unassigned "held" interpreter, it's stored here */
     231              : static PerlInterpreter *plperl_held_interp = NULL;
     232              : 
     233              : /* GUC variables */
     234              : static bool plperl_use_strict = false;
     235              : static char *plperl_on_init = NULL;
     236              : static char *plperl_on_plperl_init = NULL;
     237              : static char *plperl_on_plperlu_init = NULL;
     238              : 
     239              : static bool plperl_ending = false;
     240              : static OP  *(*pp_require_orig) (pTHX) = NULL;
     241              : static char plperl_opmask[MAXO];
     242              : 
     243              : /* this is saved and restored by plperl_call_handler */
     244              : static plperl_call_data *current_call_data = NULL;
     245              : 
     246              : /**********************************************************************
     247              :  * Forward declarations
     248              :  **********************************************************************/
     249              : 
     250              : static PerlInterpreter *plperl_init_interp(void);
     251              : static void plperl_destroy_interp(PerlInterpreter **);
     252              : static void plperl_fini(int code, Datum arg);
     253              : static void set_interp_require(bool trusted);
     254              : 
     255              : static Datum plperl_func_handler(PG_FUNCTION_ARGS);
     256              : static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
     257              : static void plperl_event_trigger_handler(PG_FUNCTION_ARGS);
     258              : 
     259              : static void free_plperl_function(plperl_proc_desc *prodesc);
     260              : 
     261              : static plperl_proc_desc *compile_plperl_function(Oid fn_oid,
     262              :                                                  bool is_trigger,
     263              :                                                  bool is_event_trigger);
     264              : 
     265              : static SV  *plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc, bool include_generated);
     266              : static SV  *plperl_hash_from_datum(Datum attr);
     267              : static void check_spi_usage_allowed(void);
     268              : static SV  *plperl_ref_from_pg_array(Datum arg, Oid typid);
     269              : static SV  *split_array(plperl_array_info *info, int first, int last, int nest);
     270              : static SV  *make_array_ref(plperl_array_info *info, int first, int last);
     271              : static SV  *get_perl_array_ref(SV *sv);
     272              : static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
     273              :                                 FunctionCallInfo fcinfo,
     274              :                                 FmgrInfo *finfo, Oid typioparam,
     275              :                                 bool *isnull);
     276              : static void _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam);
     277              : static Datum plperl_array_to_datum(SV *src, Oid typid, int32 typmod);
     278              : static void array_to_datum_internal(AV *av, ArrayBuildState **astatep,
     279              :                                     int *ndims, int *dims, int cur_depth,
     280              :                                     Oid elemtypid, int32 typmod,
     281              :                                     FmgrInfo *finfo, Oid typioparam);
     282              : static Datum plperl_hash_to_datum(SV *src, TupleDesc td);
     283              : 
     284              : static void plperl_init_shared_libs(pTHX);
     285              : static void plperl_trusted_init(void);
     286              : static void plperl_untrusted_init(void);
     287              : static HV  *plperl_spi_execute_fetch_result(SPITupleTable *, uint64, int);
     288              : static void plperl_return_next_internal(SV *sv);
     289              : static char *hek2cstr(HE *he);
     290              : static SV **hv_store_string(HV *hv, const char *key, SV *val);
     291              : static SV **hv_fetch_string(HV *hv, const char *key);
     292              : static void plperl_create_sub(plperl_proc_desc *desc, const char *s, Oid fn_oid);
     293              : static SV  *plperl_call_perl_func(plperl_proc_desc *desc,
     294              :                                   FunctionCallInfo fcinfo);
     295              : static void plperl_compile_callback(void *arg);
     296              : static void plperl_exec_callback(void *arg);
     297              : static void plperl_inline_callback(void *arg);
     298              : static char *strip_trailing_ws(const char *msg);
     299              : static OP  *pp_require_safe(pTHX);
     300              : static void activate_interpreter(plperl_interp_desc *interp_desc);
     301              : 
     302              : #if defined(WIN32) && PERL_VERSION_LT(5, 28, 0)
     303              : static char *setlocale_perl(int category, char *locale);
     304              : #else
     305              : #define setlocale_perl(a,b)  Perl_setlocale(a,b)
     306              : #endif                          /* defined(WIN32) && PERL_VERSION_LT(5, 28, 0) */
     307              : 
     308              : /*
     309              :  * Decrement the refcount of the given SV within the active Perl interpreter
     310              :  *
     311              :  * This is handy because it reloads the active-interpreter pointer, saving
     312              :  * some notation in callers that switch the active interpreter.
     313              :  */
     314              : static inline void
     315          316 : SvREFCNT_dec_current(SV *sv)
     316              : {
     317          316 :     dTHX;
     318              : 
     319          316 :     SvREFCNT_dec(sv);
     320          316 : }
     321              : 
     322              : /*
     323              :  * convert a HE (hash entry) key to a cstr in the current database encoding
     324              :  */
     325              : static char *
     326          204 : hek2cstr(HE *he)
     327              : {
     328          204 :     dTHX;
     329              :     char       *ret;
     330              :     SV         *sv;
     331              : 
     332              :     /*
     333              :      * HeSVKEY_force will return a temporary mortal SV*, so we need to make
     334              :      * sure to free it with ENTER/SAVE/FREE/LEAVE
     335              :      */
     336          204 :     ENTER;
     337          204 :     SAVETMPS;
     338              : 
     339              :     /*-------------------------
     340              :      * Unfortunately, while HeUTF8 is true for most things > 256, for values
     341              :      * 128..255 it's not, but perl will treat them as unicode code points if
     342              :      * the utf8 flag is not set ( see The "Unicode Bug" in perldoc perlunicode
     343              :      * for more)
     344              :      *
     345              :      * So if we did the expected:
     346              :      *    if (HeUTF8(he))
     347              :      *        utf_u2e(key...);
     348              :      *    else // must be ascii
     349              :      *        return HePV(he);
     350              :      * we won't match columns with codepoints from 128..255
     351              :      *
     352              :      * For a more concrete example given a column with the name of the unicode
     353              :      * codepoint U+00ae (registered sign) and a UTF8 database and the perl
     354              :      * return_next { "\N{U+00ae}=>'text } would always fail as heUTF8 returns
     355              :      * 0 and HePV() would give us a char * with 1 byte contains the decimal
     356              :      * value 174
     357              :      *
     358              :      * Perl has the brains to know when it should utf8 encode 174 properly, so
     359              :      * here we force it into an SV so that perl will figure it out and do the
     360              :      * right thing
     361              :      *-------------------------
     362              :      */
     363              : 
     364          204 :     sv = HeSVKEY_force(he);
     365          204 :     if (HeUTF8(he))
     366            0 :         SvUTF8_on(sv);
     367          204 :     ret = sv2cstr(sv);
     368              : 
     369              :     /* free sv */
     370          204 :     FREETMPS;
     371          204 :     LEAVE;
     372              : 
     373          204 :     return ret;
     374              : }
     375              : 
     376              : 
     377              : /*
     378              :  * _PG_init()           - library load-time initialization
     379              :  *
     380              :  * DO NOT make this static nor change its name!
     381              :  */
     382              : void
     383           24 : _PG_init(void)
     384              : {
     385              :     /*
     386              :      * Be sure we do initialization only once.
     387              :      *
     388              :      * If initialization fails due to, e.g., plperl_init_interp() throwing an
     389              :      * exception, then we'll return here on the next usage and the user will
     390              :      * get a rather cryptic: ERROR:  attempt to redefine parameter
     391              :      * "plperl.use_strict"
     392              :      */
     393              :     static bool inited = false;
     394              :     HASHCTL     hash_ctl;
     395              : 
     396           24 :     if (inited)
     397            0 :         return;
     398              : 
     399              :     /*
     400              :      * Support localized messages.
     401              :      */
     402           24 :     pg_bindtextdomain(TEXTDOMAIN);
     403              : 
     404              :     /*
     405              :      * Initialize plperl's GUCs.
     406              :      */
     407           24 :     DefineCustomBoolVariable("plperl.use_strict",
     408              :                              gettext_noop("If true, trusted and untrusted Perl code will be compiled in strict mode."),
     409              :                              NULL,
     410              :                              &plperl_use_strict,
     411              :                              false,
     412              :                              PGC_USERSET, 0,
     413              :                              NULL, NULL, NULL);
     414              : 
     415              :     /*
     416              :      * plperl.on_init is marked PGC_SIGHUP to support the idea that it might
     417              :      * be executed in the postmaster (if plperl is loaded into the postmaster
     418              :      * via shared_preload_libraries).  This isn't really right either way,
     419              :      * though.
     420              :      */
     421           24 :     DefineCustomStringVariable("plperl.on_init",
     422              :                                gettext_noop("Perl initialization code to execute when a Perl interpreter is initialized."),
     423              :                                NULL,
     424              :                                &plperl_on_init,
     425              :                                NULL,
     426              :                                PGC_SIGHUP, 0,
     427              :                                NULL, NULL, NULL);
     428              : 
     429              :     /*
     430              :      * plperl.on_plperl_init is marked PGC_SUSET to avoid issues whereby a
     431              :      * user who might not even have USAGE privilege on the plperl language
     432              :      * could nonetheless use SET plperl.on_plperl_init='...' to influence the
     433              :      * behaviour of any existing plperl function that they can execute (which
     434              :      * might be SECURITY DEFINER, leading to a privilege escalation).  See
     435              :      * http://archives.postgresql.org/pgsql-hackers/2010-02/msg00281.php and
     436              :      * the overall thread.
     437              :      *
     438              :      * Note that because plperl.use_strict is USERSET, a nefarious user could
     439              :      * set it to be applied against other people's functions.  This is judged
     440              :      * OK since the worst result would be an error.  Your code oughta pass
     441              :      * use_strict anyway ;-)
     442              :      */
     443           24 :     DefineCustomStringVariable("plperl.on_plperl_init",
     444              :                                gettext_noop("Perl initialization code to execute once when plperl is first used."),
     445              :                                NULL,
     446              :                                &plperl_on_plperl_init,
     447              :                                NULL,
     448              :                                PGC_SUSET, 0,
     449              :                                NULL, NULL, NULL);
     450              : 
     451           24 :     DefineCustomStringVariable("plperl.on_plperlu_init",
     452              :                                gettext_noop("Perl initialization code to execute once when plperlu is first used."),
     453              :                                NULL,
     454              :                                &plperl_on_plperlu_init,
     455              :                                NULL,
     456              :                                PGC_SUSET, 0,
     457              :                                NULL, NULL, NULL);
     458              : 
     459           24 :     MarkGUCPrefixReserved("plperl");
     460              : 
     461              :     /*
     462              :      * Create hash tables.
     463              :      */
     464           24 :     hash_ctl.keysize = sizeof(Oid);
     465           24 :     hash_ctl.entrysize = sizeof(plperl_interp_desc);
     466           24 :     plperl_interp_hash = hash_create("PL/Perl interpreters",
     467              :                                      8,
     468              :                                      &hash_ctl,
     469              :                                      HASH_ELEM | HASH_BLOBS);
     470              : 
     471           24 :     hash_ctl.keysize = sizeof(plperl_proc_key);
     472           24 :     hash_ctl.entrysize = sizeof(plperl_proc_ptr);
     473           24 :     plperl_proc_hash = hash_create("PL/Perl procedures",
     474              :                                    32,
     475              :                                    &hash_ctl,
     476              :                                    HASH_ELEM | HASH_BLOBS);
     477              : 
     478              :     /*
     479              :      * Save the default opmask.
     480              :      */
     481           24 :     PLPERL_SET_OPMASK(plperl_opmask);
     482              : 
     483              :     /*
     484              :      * Create the first Perl interpreter, but only partially initialize it.
     485              :      */
     486           24 :     plperl_held_interp = plperl_init_interp();
     487              : 
     488           24 :     inited = true;
     489              : }
     490              : 
     491              : 
     492              : static void
     493           49 : set_interp_require(bool trusted)
     494              : {
     495           49 :     if (trusted)
     496              :     {
     497           31 :         PL_ppaddr[OP_REQUIRE] = pp_require_safe;
     498           31 :         PL_ppaddr[OP_DOFILE] = pp_require_safe;
     499              :     }
     500              :     else
     501              :     {
     502           18 :         PL_ppaddr[OP_REQUIRE] = pp_require_orig;
     503           18 :         PL_ppaddr[OP_DOFILE] = pp_require_orig;
     504              :     }
     505           49 : }
     506              : 
     507              : /*
     508              :  * Cleanup perl interpreters, including running END blocks.
     509              :  * Does not fully undo the actions of _PG_init() nor make it callable again.
     510              :  */
     511              : static void
     512           22 : plperl_fini(int code, Datum arg)
     513              : {
     514              :     HASH_SEQ_STATUS hash_seq;
     515              :     plperl_interp_desc *interp_desc;
     516              : 
     517           22 :     elog(DEBUG3, "plperl_fini");
     518              : 
     519              :     /*
     520              :      * Indicate that perl is terminating. Disables use of spi_* functions when
     521              :      * running END/DESTROY code. See check_spi_usage_allowed(). Could be
     522              :      * enabled in future, with care, using a transaction
     523              :      * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02743.php
     524              :      */
     525           22 :     plperl_ending = true;
     526              : 
     527              :     /* Only perform perl cleanup if we're exiting cleanly */
     528           22 :     if (code)
     529              :     {
     530            0 :         elog(DEBUG3, "plperl_fini: skipped");
     531            0 :         return;
     532              :     }
     533              : 
     534              :     /* Zap the "held" interpreter, if we still have it */
     535           22 :     plperl_destroy_interp(&plperl_held_interp);
     536              : 
     537              :     /* Zap any fully-initialized interpreters */
     538           22 :     hash_seq_init(&hash_seq, plperl_interp_hash);
     539           67 :     while ((interp_desc = hash_seq_search(&hash_seq)) != NULL)
     540              :     {
     541           23 :         if (interp_desc->interp)
     542              :         {
     543           23 :             activate_interpreter(interp_desc);
     544           23 :             plperl_destroy_interp(&interp_desc->interp);
     545              :         }
     546              :     }
     547              : 
     548           22 :     elog(DEBUG3, "plperl_fini: done");
     549              : }
     550              : 
     551              : 
     552              : /*
     553              :  * Select and activate an appropriate Perl interpreter.
     554              :  */
     555              : static void
     556          174 : select_perl_context(bool trusted)
     557              : {
     558              :     Oid         user_id;
     559              :     plperl_interp_desc *interp_desc;
     560              :     bool        found;
     561          174 :     PerlInterpreter *interp = NULL;
     562              : 
     563              :     /* Find or create the interpreter hashtable entry for this userid */
     564          174 :     if (trusted)
     565          149 :         user_id = GetUserId();
     566              :     else
     567           25 :         user_id = InvalidOid;
     568              : 
     569          174 :     interp_desc = hash_search(plperl_interp_hash, &user_id,
     570              :                               HASH_ENTER,
     571              :                               &found);
     572          174 :     if (!found)
     573              :     {
     574              :         /* Initialize newly-created hashtable entry */
     575           24 :         interp_desc->interp = NULL;
     576           24 :         interp_desc->query_hash = NULL;
     577              :     }
     578              : 
     579              :     /* Make sure we have a query_hash for this interpreter */
     580          174 :     if (interp_desc->query_hash == NULL)
     581              :     {
     582              :         HASHCTL     hash_ctl;
     583              : 
     584           24 :         hash_ctl.keysize = NAMEDATALEN;
     585           24 :         hash_ctl.entrysize = sizeof(plperl_query_entry);
     586           24 :         interp_desc->query_hash = hash_create("PL/Perl queries",
     587              :                                               32,
     588              :                                               &hash_ctl,
     589              :                                               HASH_ELEM | HASH_STRINGS);
     590              :     }
     591              : 
     592              :     /*
     593              :      * Quick exit if already have an interpreter
     594              :      */
     595          174 :     if (interp_desc->interp)
     596              :     {
     597          150 :         activate_interpreter(interp_desc);
     598          150 :         return;
     599              :     }
     600              : 
     601              :     /*
     602              :      * adopt held interp if free, else create new one if possible
     603              :      */
     604           24 :     if (plperl_held_interp != NULL)
     605              :     {
     606              :         /* first actual use of a perl interpreter */
     607           23 :         interp = plperl_held_interp;
     608              : 
     609              :         /*
     610              :          * Reset the plperl_held_interp pointer first; if we fail during init
     611              :          * we don't want to try again with the partially-initialized interp.
     612              :          */
     613           23 :         plperl_held_interp = NULL;
     614              : 
     615           23 :         if (trusted)
     616           19 :             plperl_trusted_init();
     617              :         else
     618            4 :             plperl_untrusted_init();
     619              : 
     620              :         /* successfully initialized, so arrange for cleanup */
     621           22 :         on_proc_exit(plperl_fini, 0);
     622              :     }
     623              :     else
     624              :     {
     625              : #ifdef MULTIPLICITY
     626              : 
     627              :         /*
     628              :          * plperl_init_interp will change Perl's idea of the active
     629              :          * interpreter.  Reset plperl_active_interp temporarily, so that if we
     630              :          * hit an error partway through here, we'll make sure to switch back
     631              :          * to a non-broken interpreter before running any other Perl
     632              :          * functions.
     633              :          */
     634            1 :         plperl_active_interp = NULL;
     635              : 
     636              :         /* Now build the new interpreter */
     637            1 :         interp = plperl_init_interp();
     638              : 
     639            1 :         if (trusted)
     640            0 :             plperl_trusted_init();
     641              :         else
     642            1 :             plperl_untrusted_init();
     643              : #else
     644              :         ereport(ERROR,
     645              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     646              :                  errmsg("cannot allocate multiple Perl interpreters on this platform")));
     647              : #endif
     648              :     }
     649              : 
     650           23 :     set_interp_require(trusted);
     651              : 
     652              :     /*
     653              :      * Since the timing of first use of PL/Perl can't be predicted, any
     654              :      * database interaction during initialization is problematic. Including,
     655              :      * but not limited to, security definer issues. So we only enable access
     656              :      * to the database AFTER on_*_init code has run. See
     657              :      * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02669.php
     658              :      */
     659              :     {
     660           23 :         dTHX;
     661              : 
     662           23 :         newXS("PostgreSQL::InServer::SPI::bootstrap",
     663              :               boot_PostgreSQL__InServer__SPI, __FILE__);
     664              : 
     665           23 :         eval_pv("PostgreSQL::InServer::SPI::bootstrap()", FALSE);
     666           23 :         if (SvTRUE(ERRSV))
     667            0 :             ereport(ERROR,
     668              :                     (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
     669              :                      errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
     670              :                      errcontext("while executing PostgreSQL::InServer::SPI::bootstrap")));
     671              :     }
     672              : 
     673              :     /* Fully initialized, so mark the hashtable entry valid */
     674           23 :     interp_desc->interp = interp;
     675              : 
     676              :     /* And mark this as the active interpreter */
     677           23 :     plperl_active_interp = interp_desc;
     678              : }
     679              : 
     680              : /*
     681              :  * Make the specified interpreter the active one
     682              :  *
     683              :  * A call with NULL does nothing.  This is so that "restoring" to a previously
     684              :  * null state of plperl_active_interp doesn't result in useless thrashing.
     685              :  */
     686              : static void
     687          951 : activate_interpreter(plperl_interp_desc *interp_desc)
     688              : {
     689          951 :     if (interp_desc && plperl_active_interp != interp_desc)
     690              :     {
     691              :         Assert(interp_desc->interp);
     692           26 :         PERL_SET_CONTEXT(interp_desc->interp);
     693              :         /* trusted iff user_id isn't InvalidOid */
     694           26 :         set_interp_require(OidIsValid(interp_desc->user_id));
     695           26 :         plperl_active_interp = interp_desc;
     696              :     }
     697          951 : }
     698              : 
     699              : /*
     700              :  * Create a new Perl interpreter.
     701              :  *
     702              :  * We initialize the interpreter as far as we can without knowing whether
     703              :  * it will become a trusted or untrusted interpreter; in particular, the
     704              :  * plperl.on_init code will get executed.  Later, either plperl_trusted_init
     705              :  * or plperl_untrusted_init must be called to complete the initialization.
     706              :  */
     707              : static PerlInterpreter *
     708           25 : plperl_init_interp(void)
     709              : {
     710              :     PerlInterpreter *plperl;
     711              : 
     712              :     static char *embedding[3 + 2] = {
     713              :         "", "-e", PLC_PERLBOOT
     714              :     };
     715           25 :     int         nargs = 3;
     716              : 
     717              : #ifdef WIN32
     718              : 
     719              :     /*
     720              :      * The perl library on startup does horrible things like call
     721              :      * setlocale(LC_ALL,""). We have protected against that on most platforms
     722              :      * by setting the environment appropriately. However, on Windows,
     723              :      * setlocale() does not consult the environment, so we need to save the
     724              :      * existing locale settings before perl has a chance to mangle them and
     725              :      * restore them after its dirty deeds are done.
     726              :      *
     727              :      * MSDN ref:
     728              :      * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_locale.asp
     729              :      *
     730              :      * It appears that we only need to do this on interpreter startup, and
     731              :      * subsequent calls to the interpreter don't mess with the locale
     732              :      * settings.
     733              :      *
     734              :      * We restore them using setlocale_perl(), defined below, so that Perl
     735              :      * doesn't have a different idea of the locale from Postgres.
     736              :      *
     737              :      */
     738              : 
     739              :     char       *loc;
     740              :     char       *save_collate,
     741              :                *save_ctype,
     742              :                *save_monetary,
     743              :                *save_numeric,
     744              :                *save_time;
     745              : 
     746              :     loc = setlocale(LC_COLLATE, NULL);
     747              :     save_collate = loc ? pstrdup(loc) : NULL;
     748              :     loc = setlocale(LC_CTYPE, NULL);
     749              :     save_ctype = loc ? pstrdup(loc) : NULL;
     750              :     loc = setlocale(LC_MONETARY, NULL);
     751              :     save_monetary = loc ? pstrdup(loc) : NULL;
     752              :     loc = setlocale(LC_NUMERIC, NULL);
     753              :     save_numeric = loc ? pstrdup(loc) : NULL;
     754              :     loc = setlocale(LC_TIME, NULL);
     755              :     save_time = loc ? pstrdup(loc) : NULL;
     756              : 
     757              : #define PLPERL_RESTORE_LOCALE(name, saved) \
     758              :     STMT_START { \
     759              :         if (saved != NULL) { setlocale_perl(name, saved); pfree(saved); } \
     760              :     } STMT_END
     761              : #endif                          /* WIN32 */
     762              : 
     763           25 :     if (plperl_on_init && *plperl_on_init)
     764              :     {
     765            0 :         embedding[nargs++] = "-e";
     766            0 :         embedding[nargs++] = plperl_on_init;
     767              :     }
     768              : 
     769              :     /*
     770              :      * The perl API docs state that PERL_SYS_INIT3 should be called before
     771              :      * allocating interpreters. Unfortunately, on some platforms this fails in
     772              :      * the Perl_do_taint() routine, which is called when the platform is using
     773              :      * the system's malloc() instead of perl's own. Other platforms, notably
     774              :      * Windows, fail if PERL_SYS_INIT3 is not called. So we call it if it's
     775              :      * available, unless perl is using the system malloc(), which is true when
     776              :      * MYMALLOC is set.
     777              :      */
     778              : #if defined(PERL_SYS_INIT3) && !defined(MYMALLOC)
     779              :     {
     780              :         static int  perl_sys_init_done;
     781              : 
     782              :         /* only call this the first time through, as per perlembed man page */
     783           25 :         if (!perl_sys_init_done)
     784              :         {
     785           24 :             char       *dummy_env[1] = {NULL};
     786              : 
     787           24 :             PERL_SYS_INIT3(&nargs, (char ***) &embedding, (char ***) &dummy_env);
     788              : 
     789              :             /*
     790              :              * For unclear reasons, PERL_SYS_INIT3 sets the SIGFPE handler to
     791              :              * SIG_IGN.  Aside from being extremely unfriendly behavior for a
     792              :              * library, this is dumb on the grounds that the results of a
     793              :              * SIGFPE in this state are undefined according to POSIX, and in
     794              :              * fact you get a forced process kill at least on Linux.  Hence,
     795              :              * restore the SIGFPE handler to the backend's standard setting.
     796              :              * (See Perl bug 114574 for more information.)
     797              :              */
     798           24 :             pqsignal(SIGFPE, FloatExceptionHandler);
     799              : 
     800           24 :             perl_sys_init_done = 1;
     801              :             /* quiet warning if PERL_SYS_INIT3 doesn't use the third argument */
     802           24 :             dummy_env[0] = NULL;
     803              :         }
     804              :     }
     805              : #endif
     806              : 
     807           25 :     plperl = perl_alloc();
     808           25 :     if (!plperl)
     809            0 :         elog(ERROR, "could not allocate Perl interpreter");
     810              : 
     811           25 :     PERL_SET_CONTEXT(plperl);
     812           25 :     perl_construct(plperl);
     813              : 
     814              :     /*
     815              :      * Run END blocks in perl_destruct instead of perl_run.  Note that dTHX
     816              :      * loads up a pointer to the current interpreter, so we have to postpone
     817              :      * it to here rather than put it at the function head.
     818              :      */
     819              :     {
     820           25 :         dTHX;
     821              : 
     822           25 :         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
     823              : 
     824              :         /*
     825              :          * Record the original function for the 'require' and 'dofile'
     826              :          * opcodes.  (They share the same implementation.)  Ensure it's used
     827              :          * for new interpreters.
     828              :          */
     829           25 :         if (!pp_require_orig)
     830           24 :             pp_require_orig = PL_ppaddr[OP_REQUIRE];
     831              :         else
     832              :         {
     833            1 :             PL_ppaddr[OP_REQUIRE] = pp_require_orig;
     834            1 :             PL_ppaddr[OP_DOFILE] = pp_require_orig;
     835              :         }
     836              : 
     837              : #ifdef PLPERL_ENABLE_OPMASK_EARLY
     838              : 
     839              :         /*
     840              :          * For regression testing to prove that the PLC_PERLBOOT and
     841              :          * PLC_TRUSTED code doesn't even compile any unsafe ops.  In future
     842              :          * there may be a valid need for them to do so, in which case this
     843              :          * could be softened (perhaps moved to plperl_trusted_init()) or
     844              :          * removed.
     845              :          */
     846              :         PL_op_mask = plperl_opmask;
     847              : #endif
     848              : 
     849           25 :         if (perl_parse(plperl, plperl_init_shared_libs,
     850              :                        nargs, embedding, NULL) != 0)
     851            0 :             ereport(ERROR,
     852              :                     (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
     853              :                      errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
     854              :                      errcontext("while parsing Perl initialization")));
     855              : 
     856           25 :         if (perl_run(plperl) != 0)
     857            0 :             ereport(ERROR,
     858              :                     (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
     859              :                      errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
     860              :                      errcontext("while running Perl initialization")));
     861              : 
     862              : #ifdef PLPERL_RESTORE_LOCALE
     863              :         PLPERL_RESTORE_LOCALE(LC_COLLATE, save_collate);
     864              :         PLPERL_RESTORE_LOCALE(LC_CTYPE, save_ctype);
     865              :         PLPERL_RESTORE_LOCALE(LC_MONETARY, save_monetary);
     866              :         PLPERL_RESTORE_LOCALE(LC_NUMERIC, save_numeric);
     867              :         PLPERL_RESTORE_LOCALE(LC_TIME, save_time);
     868              : #endif
     869              :     }
     870              : 
     871           25 :     return plperl;
     872              : }
     873              : 
     874              : 
     875              : /*
     876              :  * Our safe implementation of the require opcode.
     877              :  * This is safe because it's completely unable to load any code.
     878              :  * If the requested file/module has already been loaded it'll return true.
     879              :  * If not, it'll die.
     880              :  * So now "use Foo;" will work iff Foo has already been loaded.
     881              :  */
     882              : static OP  *
     883            8 : pp_require_safe(pTHX)
     884              : {
     885              :     dVAR;
     886            8 :     dSP;
     887              :     SV         *sv,
     888              :               **svp;
     889              :     char       *name;
     890              :     STRLEN      len;
     891              : 
     892            8 :     sv = POPs;
     893            8 :     name = SvPV(sv, len);
     894            8 :     if (!(name && len > 0 && *name))
     895            0 :         RETPUSHNO;
     896              : 
     897            8 :     svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
     898            8 :     if (svp && *svp != &PL_sv_undef)
     899            4 :         RETPUSHYES;
     900              : 
     901            4 :     DIE(aTHX_ "Unable to load %s into plperl", name);
     902              : 
     903              :     /*
     904              :      * In most Perl versions, DIE() expands to a return statement, so the next
     905              :      * line is not necessary.  But in versions between but not including
     906              :      * 5.11.1 and 5.13.3 it does not, so the next line is necessary to avoid a
     907              :      * "control reaches end of non-void function" warning from gcc.  Other
     908              :      * compilers such as Solaris Studio will, however, issue a "statement not
     909              :      * reached" warning instead.
     910              :      */
     911              :     return NULL;
     912              : }
     913              : 
     914              : 
     915              : /*
     916              :  * Destroy one Perl interpreter ... actually we just run END blocks.
     917              :  *
     918              :  * Caller must have ensured this interpreter is the active one.
     919              :  */
     920              : static void
     921           45 : plperl_destroy_interp(PerlInterpreter **interp)
     922              : {
     923           45 :     if (interp && *interp)
     924              :     {
     925              :         /*
     926              :          * Only a very minimal destruction is performed: - just call END
     927              :          * blocks.
     928              :          *
     929              :          * We could call perl_destruct() but we'd need to audit its actions
     930              :          * very carefully and work-around any that impact us. (Calling
     931              :          * sv_clean_objs() isn't an option because it's not part of perl's
     932              :          * public API so isn't portably available.) Meanwhile END blocks can
     933              :          * be used to perform manual cleanup.
     934              :          */
     935           23 :         dTHX;
     936              : 
     937              :         /* Run END blocks - based on perl's perl_destruct() */
     938           23 :         if (PL_exit_flags & PERL_EXIT_DESTRUCT_END)
     939              :         {
     940              :             dJMPENV;
     941           23 :             int         x = 0;
     942              : 
     943           23 :             JMPENV_PUSH(x);
     944              :             PERL_UNUSED_VAR(x);
     945           23 :             if (PL_endav && !PL_minus_c)
     946            0 :                 call_list(PL_scopestack_ix, PL_endav);
     947           23 :             JMPENV_POP;
     948              :         }
     949           23 :         LEAVE;
     950           23 :         FREETMPS;
     951              : 
     952           23 :         *interp = NULL;
     953              :     }
     954           45 : }
     955              : 
     956              : /*
     957              :  * Initialize the current Perl interpreter as a trusted interp
     958              :  */
     959              : static void
     960           19 : plperl_trusted_init(void)
     961              : {
     962           19 :     dTHX;
     963              :     HV         *stash;
     964              :     SV         *sv;
     965              :     char       *key;
     966              :     I32         klen;
     967              : 
     968              :     /* use original require while we set up */
     969           19 :     PL_ppaddr[OP_REQUIRE] = pp_require_orig;
     970           19 :     PL_ppaddr[OP_DOFILE] = pp_require_orig;
     971              : 
     972           19 :     eval_pv(PLC_TRUSTED, FALSE);
     973           19 :     if (SvTRUE(ERRSV))
     974            0 :         ereport(ERROR,
     975              :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
     976              :                  errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
     977              :                  errcontext("while executing PLC_TRUSTED")));
     978              : 
     979              :     /*
     980              :      * Force loading of utf8 module now to prevent errors that can arise from
     981              :      * the regex code later trying to load utf8 modules. See
     982              :      * http://rt.perl.org/rt3/Ticket/Display.html?id=47576
     983              :      */
     984           19 :     eval_pv("my $a=chr(0x100); return $a =~ /\\xa9/i", FALSE);
     985           19 :     if (SvTRUE(ERRSV))
     986            0 :         ereport(ERROR,
     987              :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
     988              :                  errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
     989              :                  errcontext("while executing utf8fix")));
     990              : 
     991              :     /*
     992              :      * Lock down the interpreter
     993              :      */
     994              : 
     995              :     /* switch to the safe require/dofile opcode for future code */
     996           19 :     PL_ppaddr[OP_REQUIRE] = pp_require_safe;
     997           19 :     PL_ppaddr[OP_DOFILE] = pp_require_safe;
     998              : 
     999              :     /*
    1000              :      * prevent (any more) unsafe opcodes being compiled PL_op_mask is per
    1001              :      * interpreter, so this only needs to be set once
    1002              :      */
    1003           19 :     PL_op_mask = plperl_opmask;
    1004              : 
    1005              :     /* delete the DynaLoader:: namespace so extensions can't be loaded */
    1006           19 :     stash = gv_stashpv("DynaLoader", GV_ADDWARN);
    1007           19 :     hv_iterinit(stash);
    1008           38 :     while ((sv = hv_iternextsv(stash, &key, &klen)))
    1009              :     {
    1010           19 :         if (!isGV_with_GP(sv) || !GvCV(sv))
    1011            0 :             continue;
    1012           19 :         SvREFCNT_dec(GvCV(sv)); /* free the CV */
    1013           19 :         GvCV_set(sv, NULL);     /* prevent call via GV */
    1014              :     }
    1015           19 :     hv_clear(stash);
    1016              : 
    1017              :     /* invalidate assorted caches */
    1018           19 :     ++PL_sub_generation;
    1019           19 :     hv_clear(PL_stashcache);
    1020              : 
    1021              :     /*
    1022              :      * Execute plperl.on_plperl_init in the locked-down interpreter
    1023              :      */
    1024           19 :     if (plperl_on_plperl_init && *plperl_on_plperl_init)
    1025              :     {
    1026            2 :         eval_pv(plperl_on_plperl_init, FALSE);
    1027              :         /* XXX need to find a way to determine a better errcode here */
    1028            2 :         if (SvTRUE(ERRSV))
    1029            1 :             ereport(ERROR,
    1030              :                     (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    1031              :                      errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
    1032              :                      errcontext("while executing plperl.on_plperl_init")));
    1033              :     }
    1034           18 : }
    1035              : 
    1036              : 
    1037              : /*
    1038              :  * Initialize the current Perl interpreter as an untrusted interp
    1039              :  */
    1040              : static void
    1041            5 : plperl_untrusted_init(void)
    1042              : {
    1043            5 :     dTHX;
    1044              : 
    1045              :     /*
    1046              :      * Nothing to do except execute plperl.on_plperlu_init
    1047              :      */
    1048            5 :     if (plperl_on_plperlu_init && *plperl_on_plperlu_init)
    1049              :     {
    1050            1 :         eval_pv(plperl_on_plperlu_init, FALSE);
    1051            1 :         if (SvTRUE(ERRSV))
    1052            0 :             ereport(ERROR,
    1053              :                     (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    1054              :                      errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
    1055              :                      errcontext("while executing plperl.on_plperlu_init")));
    1056              :     }
    1057            5 : }
    1058              : 
    1059              : 
    1060              : /*
    1061              :  * Perl likes to put a newline after its error messages; clean up such
    1062              :  */
    1063              : static char *
    1064           27 : strip_trailing_ws(const char *msg)
    1065              : {
    1066           27 :     char       *res = pstrdup(msg);
    1067           27 :     int         len = strlen(res);
    1068              : 
    1069           54 :     while (len > 0 && isspace((unsigned char) res[len - 1]))
    1070           27 :         res[--len] = '\0';
    1071           27 :     return res;
    1072              : }
    1073              : 
    1074              : 
    1075              : /* Build a tuple from a hash. */
    1076              : 
    1077              : static HeapTuple
    1078           80 : plperl_build_tuple_result(HV *perlhash, TupleDesc td)
    1079              : {
    1080           80 :     dTHX;
    1081              :     Datum      *values;
    1082              :     bool       *nulls;
    1083              :     HE         *he;
    1084              :     HeapTuple   tup;
    1085              : 
    1086           80 :     values = palloc0_array(Datum, td->natts);
    1087           80 :     nulls = palloc_array(bool, td->natts);
    1088           80 :     memset(nulls, true, sizeof(bool) * td->natts);
    1089              : 
    1090           80 :     hv_iterinit(perlhash);
    1091          266 :     while ((he = hv_iternext(perlhash)))
    1092              :     {
    1093          188 :         SV         *val = HeVAL(he);
    1094          188 :         char       *key = hek2cstr(he);
    1095          188 :         int         attn = SPI_fnumber(td, key);
    1096          188 :         Form_pg_attribute attr = TupleDescAttr(td, attn - 1);
    1097              : 
    1098          188 :         if (attn == SPI_ERROR_NOATTRIBUTE)
    1099            2 :             ereport(ERROR,
    1100              :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    1101              :                      errmsg("Perl hash contains nonexistent column \"%s\"",
    1102              :                             key)));
    1103          186 :         if (attn <= 0)
    1104            0 :             ereport(ERROR,
    1105              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1106              :                      errmsg("cannot set system attribute \"%s\"",
    1107              :                             key)));
    1108              : 
    1109          372 :         values[attn - 1] = plperl_sv_to_datum(val,
    1110              :                                               attr->atttypid,
    1111              :                                               attr->atttypmod,
    1112              :                                               NULL,
    1113              :                                               NULL,
    1114              :                                               InvalidOid,
    1115          186 :                                               &nulls[attn - 1]);
    1116              : 
    1117          186 :         pfree(key);
    1118              :     }
    1119           78 :     hv_iterinit(perlhash);
    1120              : 
    1121           78 :     tup = heap_form_tuple(td, values, nulls);
    1122           78 :     pfree(values);
    1123           78 :     pfree(nulls);
    1124           78 :     return tup;
    1125              : }
    1126              : 
    1127              : /* convert a hash reference to a datum */
    1128              : static Datum
    1129           41 : plperl_hash_to_datum(SV *src, TupleDesc td)
    1130              : {
    1131           41 :     HeapTuple   tup = plperl_build_tuple_result((HV *) SvRV(src), td);
    1132              : 
    1133           40 :     return HeapTupleGetDatum(tup);
    1134              : }
    1135              : 
    1136              : /*
    1137              :  * if we are an array ref return the reference. this is special in that if we
    1138              :  * are a PostgreSQL::InServer::ARRAY object we will return the 'magic' array.
    1139              :  */
    1140              : static SV  *
    1141          374 : get_perl_array_ref(SV *sv)
    1142              : {
    1143          374 :     dTHX;
    1144              : 
    1145          374 :     if (SvOK(sv) && SvROK(sv))
    1146              :     {
    1147          205 :         if (SvTYPE(SvRV(sv)) == SVt_PVAV)
    1148          152 :             return sv;
    1149           53 :         else if (sv_isa(sv, "PostgreSQL::InServer::ARRAY"))
    1150              :         {
    1151            1 :             HV         *hv = (HV *) SvRV(sv);
    1152            1 :             SV        **sav = hv_fetch_string(hv, "array");
    1153              : 
    1154            1 :             if (*sav && SvOK(*sav) && SvROK(*sav) &&
    1155            1 :                 SvTYPE(SvRV(*sav)) == SVt_PVAV)
    1156            1 :                 return *sav;
    1157              : 
    1158            0 :             elog(ERROR, "could not get array reference from PostgreSQL::InServer::ARRAY object");
    1159              :         }
    1160              :     }
    1161          221 :     return NULL;
    1162              : }
    1163              : 
    1164              : /*
    1165              :  * helper function for plperl_array_to_datum, recurses for multi-D arrays
    1166              :  *
    1167              :  * The ArrayBuildState is created only when we first find a scalar element;
    1168              :  * if we didn't do it like that, we'd need some other convention for knowing
    1169              :  * whether we'd already found any scalars (and thus the number of dimensions
    1170              :  * is frozen).
    1171              :  */
    1172              : static void
    1173          130 : array_to_datum_internal(AV *av, ArrayBuildState **astatep,
    1174              :                         int *ndims, int *dims, int cur_depth,
    1175              :                         Oid elemtypid, int32 typmod,
    1176              :                         FmgrInfo *finfo, Oid typioparam)
    1177              : {
    1178          130 :     dTHX;
    1179              :     int         i;
    1180          130 :     int         len = av_len(av) + 1;
    1181              : 
    1182          375 :     for (i = 0; i < len; i++)
    1183              :     {
    1184              :         /* fetch the array element */
    1185          250 :         SV        **svp = av_fetch(av, i, FALSE);
    1186              : 
    1187              :         /* see if this element is an array, if so get that */
    1188          250 :         SV         *sav = svp ? get_perl_array_ref(*svp) : NULL;
    1189              : 
    1190              :         /* multi-dimensional array? */
    1191          250 :         if (sav)
    1192              :         {
    1193           98 :             AV         *nav = (AV *) SvRV(sav);
    1194              : 
    1195              :             /* set size when at first element in this level, else compare */
    1196           98 :             if (i == 0 && *ndims == cur_depth)
    1197              :             {
    1198              :                 /* array after some scalars at same level? */
    1199           22 :                 if (*astatep != NULL)
    1200            1 :                     ereport(ERROR,
    1201              :                             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    1202              :                              errmsg("multidimensional arrays must have array expressions with matching dimensions")));
    1203              :                 /* too many dimensions? */
    1204           21 :                 if (cur_depth + 1 > MAXDIM)
    1205            0 :                     ereport(ERROR,
    1206              :                             (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1207              :                              errmsg("number of array dimensions exceeds the maximum allowed (%d)",
    1208              :                                     MAXDIM)));
    1209              :                 /* OK, add a dimension */
    1210           21 :                 dims[*ndims] = av_len(nav) + 1;
    1211           21 :                 (*ndims)++;
    1212              :             }
    1213           76 :             else if (cur_depth >= *ndims ||
    1214           75 :                      av_len(nav) + 1 != dims[cur_depth])
    1215            2 :                 ereport(ERROR,
    1216              :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    1217              :                          errmsg("multidimensional arrays must have array expressions with matching dimensions")));
    1218              : 
    1219              :             /* recurse to fetch elements of this sub-array */
    1220           95 :             array_to_datum_internal(nav, astatep,
    1221              :                                     ndims, dims, cur_depth + 1,
    1222              :                                     elemtypid, typmod,
    1223              :                                     finfo, typioparam);
    1224              :         }
    1225              :         else
    1226              :         {
    1227              :             Datum       dat;
    1228              :             bool        isnull;
    1229              : 
    1230              :             /* scalar after some sub-arrays at same level? */
    1231          152 :             if (*ndims != cur_depth)
    1232            1 :                 ereport(ERROR,
    1233              :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    1234              :                          errmsg("multidimensional arrays must have array expressions with matching dimensions")));
    1235              : 
    1236          151 :             dat = plperl_sv_to_datum(svp ? *svp : NULL,
    1237              :                                      elemtypid,
    1238              :                                      typmod,
    1239              :                                      NULL,
    1240              :                                      finfo,
    1241              :                                      typioparam,
    1242              :                                      &isnull);
    1243              : 
    1244              :             /* Create ArrayBuildState if we didn't already */
    1245          151 :             if (*astatep == NULL)
    1246           31 :                 *astatep = initArrayResult(elemtypid,
    1247              :                                            CurrentMemoryContext, true);
    1248              : 
    1249              :             /* ... and save the element value in it */
    1250          151 :             (void) accumArrayResult(*astatep, dat, isnull,
    1251              :                                     elemtypid, CurrentMemoryContext);
    1252              :         }
    1253              :     }
    1254          125 : }
    1255              : 
    1256              : /*
    1257              :  * convert perl array ref to a datum
    1258              :  */
    1259              : static Datum
    1260           37 : plperl_array_to_datum(SV *src, Oid typid, int32 typmod)
    1261              : {
    1262           37 :     dTHX;
    1263           37 :     AV         *nav = (AV *) SvRV(src);
    1264           37 :     ArrayBuildState *astate = NULL;
    1265              :     Oid         elemtypid;
    1266              :     FmgrInfo    finfo;
    1267              :     Oid         typioparam;
    1268              :     int         dims[MAXDIM];
    1269              :     int         lbs[MAXDIM];
    1270           37 :     int         ndims = 1;
    1271              :     int         i;
    1272              : 
    1273           37 :     elemtypid = get_element_type(typid);
    1274           37 :     if (!elemtypid)
    1275            2 :         ereport(ERROR,
    1276              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    1277              :                  errmsg("cannot convert Perl array to non-array type %s",
    1278              :                         format_type_be(typid))));
    1279              : 
    1280           35 :     _sv_to_datum_finfo(elemtypid, &finfo, &typioparam);
    1281              : 
    1282           35 :     memset(dims, 0, sizeof(dims));
    1283           35 :     dims[0] = av_len(nav) + 1;
    1284              : 
    1285           35 :     array_to_datum_internal(nav, &astate,
    1286              :                             &ndims, dims, 1,
    1287              :                             elemtypid, typmod,
    1288              :                             &finfo, typioparam);
    1289              : 
    1290              :     /* ensure we get zero-D array for no inputs, as per PG convention */
    1291           31 :     if (astate == NULL)
    1292            2 :         return PointerGetDatum(construct_empty_array(elemtypid));
    1293              : 
    1294           75 :     for (i = 0; i < ndims; i++)
    1295           46 :         lbs[i] = 1;
    1296              : 
    1297           29 :     return makeMdArrayResult(astate, ndims, dims, lbs,
    1298              :                              CurrentMemoryContext, true);
    1299              : }
    1300              : 
    1301              : /* Get the information needed to convert data to the specified PG type */
    1302              : static void
    1303          206 : _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam)
    1304              : {
    1305              :     Oid         typinput;
    1306              : 
    1307              :     /* XXX would be better to cache these lookups */
    1308          206 :     getTypeInputInfo(typid,
    1309              :                      &typinput, typioparam);
    1310          206 :     fmgr_info(typinput, finfo);
    1311          206 : }
    1312              : 
    1313              : /*
    1314              :  * convert Perl SV to PG datum of type typid, typmod typmod
    1315              :  *
    1316              :  * Pass the PL/Perl function's fcinfo when attempting to convert to the
    1317              :  * function's result type; otherwise pass NULL.  This is used when we need to
    1318              :  * resolve the actual result type of a function returning RECORD.
    1319              :  *
    1320              :  * finfo and typioparam should be the results of _sv_to_datum_finfo for the
    1321              :  * given typid, or NULL/InvalidOid to let this function do the lookups.
    1322              :  *
    1323              :  * *isnull is an output parameter.
    1324              :  */
    1325              : static Datum
    1326          649 : plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
    1327              :                    FunctionCallInfo fcinfo,
    1328              :                    FmgrInfo *finfo, Oid typioparam,
    1329              :                    bool *isnull)
    1330              : {
    1331              :     FmgrInfo    tmp;
    1332              :     Oid         funcid;
    1333              : 
    1334              :     /* we might recurse */
    1335          649 :     check_stack_depth();
    1336              : 
    1337          649 :     *isnull = false;
    1338              : 
    1339              :     /*
    1340              :      * Return NULL if result is undef, or if we're in a function returning
    1341              :      * VOID.  In the latter case, we should pay no attention to the last Perl
    1342              :      * statement's result, and this is a convenient means to ensure that.
    1343              :      */
    1344          649 :     if (!sv || !SvOK(sv) || typid == VOIDOID)
    1345              :     {
    1346              :         /* look up type info if they did not pass it */
    1347           39 :         if (!finfo)
    1348              :         {
    1349            5 :             _sv_to_datum_finfo(typid, &tmp, &typioparam);
    1350            5 :             finfo = &tmp;
    1351              :         }
    1352           39 :         *isnull = true;
    1353              :         /* must call typinput in case it wants to reject NULL */
    1354           39 :         return InputFunctionCall(finfo, NULL, typioparam, typmod);
    1355              :     }
    1356          610 :     else if ((funcid = get_transform_tosql(typid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
    1357           78 :         return OidFunctionCall1(funcid, PointerGetDatum(sv));
    1358          532 :     else if (SvROK(sv))
    1359              :     {
    1360              :         /* handle references */
    1361           82 :         SV         *sav = get_perl_array_ref(sv);
    1362              : 
    1363           82 :         if (sav)
    1364              :         {
    1365              :             /* handle an arrayref */
    1366           37 :             return plperl_array_to_datum(sav, typid, typmod);
    1367              :         }
    1368           45 :         else if (SvTYPE(SvRV(sv)) == SVt_PVHV)
    1369              :         {
    1370              :             /* handle a hashref */
    1371              :             Datum       ret;
    1372              :             TupleDesc   td;
    1373              :             bool        isdomain;
    1374              : 
    1375           44 :             if (!type_is_rowtype(typid))
    1376            2 :                 ereport(ERROR,
    1377              :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    1378              :                          errmsg("cannot convert Perl hash to non-composite type %s",
    1379              :                                 format_type_be(typid))));
    1380              : 
    1381           42 :             td = lookup_rowtype_tupdesc_domain(typid, typmod, true);
    1382           42 :             if (td != NULL)
    1383              :             {
    1384              :                 /* Did we look through a domain? */
    1385           34 :                 isdomain = (typid != td->tdtypeid);
    1386              :             }
    1387              :             else
    1388              :             {
    1389              :                 /* Must be RECORD, try to resolve based on call info */
    1390              :                 TypeFuncClass funcclass;
    1391              : 
    1392            8 :                 if (fcinfo)
    1393            8 :                     funcclass = get_call_result_type(fcinfo, &typid, &td);
    1394              :                 else
    1395            0 :                     funcclass = TYPEFUNC_OTHER;
    1396            8 :                 if (funcclass != TYPEFUNC_COMPOSITE &&
    1397              :                     funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
    1398            1 :                     ereport(ERROR,
    1399              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1400              :                              errmsg("function returning record called in context "
    1401              :                                     "that cannot accept type record")));
    1402              :                 Assert(td);
    1403            7 :                 isdomain = (funcclass == TYPEFUNC_COMPOSITE_DOMAIN);
    1404              :             }
    1405              : 
    1406           41 :             ret = plperl_hash_to_datum(sv, td);
    1407              : 
    1408           40 :             if (isdomain)
    1409            4 :                 domain_check(ret, false, typid, NULL, NULL);
    1410              : 
    1411              :             /* Release on the result of get_call_result_type is harmless */
    1412           38 :             ReleaseTupleDesc(td);
    1413              : 
    1414           38 :             return ret;
    1415              :         }
    1416              : 
    1417              :         /*
    1418              :          * If it's a reference to something else, such as a scalar, just
    1419              :          * recursively look through the reference.
    1420              :          */
    1421            1 :         return plperl_sv_to_datum(SvRV(sv), typid, typmod,
    1422              :                                   fcinfo, finfo, typioparam,
    1423              :                                   isnull);
    1424              :     }
    1425              :     else
    1426              :     {
    1427              :         /* handle a string/number */
    1428              :         Datum       ret;
    1429          450 :         char       *str = sv2cstr(sv);
    1430              : 
    1431              :         /* did not pass in any typeinfo? look it up */
    1432          449 :         if (!finfo)
    1433              :         {
    1434          166 :             _sv_to_datum_finfo(typid, &tmp, &typioparam);
    1435          166 :             finfo = &tmp;
    1436              :         }
    1437              : 
    1438          449 :         ret = InputFunctionCall(finfo, str, typioparam, typmod);
    1439          448 :         pfree(str);
    1440              : 
    1441          448 :         return ret;
    1442              :     }
    1443              : }
    1444              : 
    1445              : /* Convert the perl SV to a string returned by the type output function */
    1446              : char *
    1447           16 : plperl_sv_to_literal(SV *sv, char *fqtypename)
    1448              : {
    1449              :     Oid         typid;
    1450              :     Oid         typoutput;
    1451              :     Datum       datum;
    1452              :     bool        typisvarlena,
    1453              :                 isnull;
    1454              : 
    1455           16 :     check_spi_usage_allowed();
    1456              : 
    1457           16 :     typid = DatumGetObjectId(DirectFunctionCall1(regtypein, CStringGetDatum(fqtypename)));
    1458           16 :     if (!OidIsValid(typid))
    1459            0 :         ereport(ERROR,
    1460              :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    1461              :                  errmsg("lookup failed for type %s", fqtypename)));
    1462              : 
    1463           16 :     datum = plperl_sv_to_datum(sv,
    1464              :                                typid, -1,
    1465              :                                NULL, NULL, InvalidOid,
    1466              :                                &isnull);
    1467              : 
    1468           15 :     if (isnull)
    1469            1 :         return NULL;
    1470              : 
    1471           14 :     getTypeOutputInfo(typid,
    1472              :                       &typoutput, &typisvarlena);
    1473              : 
    1474           14 :     return OidOutputFunctionCall(typoutput, datum);
    1475              : }
    1476              : 
    1477              : /*
    1478              :  * Convert PostgreSQL array datum to a perl array reference.
    1479              :  *
    1480              :  * typid is arg's OID, which must be an array type.
    1481              :  */
    1482              : static SV  *
    1483           17 : plperl_ref_from_pg_array(Datum arg, Oid typid)
    1484              : {
    1485           17 :     dTHX;
    1486           17 :     ArrayType  *ar = DatumGetArrayTypeP(arg);
    1487           17 :     Oid         elementtype = ARR_ELEMTYPE(ar);
    1488              :     int16       typlen;
    1489              :     bool        typbyval;
    1490              :     char        typalign,
    1491              :                 typdelim;
    1492              :     Oid         typioparam;
    1493              :     Oid         typoutputfunc;
    1494              :     Oid         transform_funcid;
    1495              :     int         i,
    1496              :                 nitems,
    1497              :                *dims;
    1498              :     plperl_array_info *info;
    1499              :     SV         *av;
    1500              :     HV         *hv;
    1501              : 
    1502              :     /*
    1503              :      * Currently we make no effort to cache any of the stuff we look up here,
    1504              :      * which is bad.
    1505              :      */
    1506           17 :     info = palloc0_object(plperl_array_info);
    1507              : 
    1508              :     /* get element type information, including output conversion function */
    1509           17 :     get_type_io_data(elementtype, IOFunc_output,
    1510              :                      &typlen, &typbyval, &typalign,
    1511              :                      &typdelim, &typioparam, &typoutputfunc);
    1512              : 
    1513              :     /* Check for a transform function */
    1514           17 :     transform_funcid = get_transform_fromsql(elementtype,
    1515           17 :                                              current_call_data->prodesc->lang_oid,
    1516           17 :                                              current_call_data->prodesc->trftypes);
    1517              : 
    1518              :     /* Look up transform or output function as appropriate */
    1519           17 :     if (OidIsValid(transform_funcid))
    1520            1 :         fmgr_info(transform_funcid, &info->transform_proc);
    1521              :     else
    1522           16 :         fmgr_info(typoutputfunc, &info->proc);
    1523              : 
    1524           17 :     info->elem_is_rowtype = type_is_rowtype(elementtype);
    1525              : 
    1526              :     /* Get the number and bounds of array dimensions */
    1527           17 :     info->ndims = ARR_NDIM(ar);
    1528           17 :     dims = ARR_DIMS(ar);
    1529              : 
    1530              :     /* No dimensions? Return an empty array */
    1531           17 :     if (info->ndims == 0)
    1532              :     {
    1533            1 :         av = newRV_noinc((SV *) newAV());
    1534              :     }
    1535              :     else
    1536              :     {
    1537           16 :         deconstruct_array(ar, elementtype, typlen, typbyval,
    1538              :                           typalign, &info->elements, &info->nulls,
    1539              :                           &nitems);
    1540              : 
    1541              :         /* Get total number of elements in each dimension */
    1542           16 :         info->nelems = palloc_array(int, info->ndims);
    1543           16 :         info->nelems[0] = nitems;
    1544           28 :         for (i = 1; i < info->ndims; i++)
    1545           12 :             info->nelems[i] = info->nelems[i - 1] / dims[i - 1];
    1546              : 
    1547           16 :         av = split_array(info, 0, nitems, 0);
    1548              :     }
    1549              : 
    1550           17 :     hv = newHV();
    1551           17 :     (void) hv_store(hv, "array", 5, av, 0);
    1552           17 :     (void) hv_store(hv, "typeoid", 7, newSVuv(typid), 0);
    1553              : 
    1554           17 :     return sv_bless(newRV_noinc((SV *) hv),
    1555              :                     gv_stashpv("PostgreSQL::InServer::ARRAY", 0));
    1556              : }
    1557              : 
    1558              : /*
    1559              :  * Recursively form array references from splices of the initial array
    1560              :  */
    1561              : static SV  *
    1562           96 : split_array(plperl_array_info *info, int first, int last, int nest)
    1563              : {
    1564           96 :     dTHX;
    1565              :     int         i;
    1566              :     AV         *result;
    1567              : 
    1568              :     /* we should only be called when we have something to split */
    1569              :     Assert(info->ndims > 0);
    1570              : 
    1571              :     /* since this function recurses, it could be driven to stack overflow */
    1572           96 :     check_stack_depth();
    1573              : 
    1574              :     /*
    1575              :      * Base case, return a reference to a single-dimensional array
    1576              :      */
    1577           96 :     if (nest >= info->ndims - 1)
    1578           57 :         return make_array_ref(info, first, last);
    1579              : 
    1580           39 :     result = newAV();
    1581          119 :     for (i = first; i < last; i += info->nelems[nest + 1])
    1582              :     {
    1583              :         /* Recursively form references to arrays of lower dimensions */
    1584           80 :         SV         *ref = split_array(info, i, i + info->nelems[nest + 1], nest + 1);
    1585              : 
    1586           80 :         av_push(result, ref);
    1587              :     }
    1588           39 :     return newRV_noinc((SV *) result);
    1589              : }
    1590              : 
    1591              : /*
    1592              :  * Create a Perl reference from a one-dimensional C array, converting
    1593              :  * composite type elements to hash references.
    1594              :  */
    1595              : static SV  *
    1596           57 : make_array_ref(plperl_array_info *info, int first, int last)
    1597              : {
    1598           57 :     dTHX;
    1599              :     int         i;
    1600           57 :     AV         *result = newAV();
    1601              : 
    1602          193 :     for (i = first; i < last; i++)
    1603              :     {
    1604          136 :         if (info->nulls[i])
    1605              :         {
    1606              :             /*
    1607              :              * We can't use &PL_sv_undef here.  See "AVs, HVs and undefined
    1608              :              * values" in perlguts.
    1609              :              */
    1610            4 :             av_push(result, newSV(0));
    1611              :         }
    1612              :         else
    1613              :         {
    1614          132 :             Datum       itemvalue = info->elements[i];
    1615              : 
    1616          132 :             if (info->transform_proc.fn_oid)
    1617            2 :                 av_push(result, (SV *) DatumGetPointer(FunctionCall1(&info->transform_proc, itemvalue)));
    1618          130 :             else if (info->elem_is_rowtype)
    1619              :                 /* Handle composite type elements */
    1620            4 :                 av_push(result, plperl_hash_from_datum(itemvalue));
    1621              :             else
    1622              :             {
    1623          126 :                 char       *val = OutputFunctionCall(&info->proc, itemvalue);
    1624              : 
    1625          126 :                 av_push(result, cstr2sv(val));
    1626              :             }
    1627              :         }
    1628              :     }
    1629           57 :     return newRV_noinc((SV *) result);
    1630              : }
    1631              : 
    1632              : /* Set up the arguments for a trigger call. */
    1633              : static SV  *
    1634           30 : plperl_trigger_build_args(FunctionCallInfo fcinfo)
    1635              : {
    1636           30 :     dTHX;
    1637              :     TriggerData *tdata;
    1638              :     TupleDesc   tupdesc;
    1639              :     int         i;
    1640              :     char       *level;
    1641              :     char       *event;
    1642              :     char       *relid;
    1643              :     char       *when;
    1644              :     HV         *hv;
    1645              : 
    1646           30 :     hv = newHV();
    1647           30 :     hv_ksplit(hv, 12);          /* pre-grow the hash */
    1648              : 
    1649           30 :     tdata = (TriggerData *) fcinfo->context;
    1650           30 :     tupdesc = tdata->tg_relation->rd_att;
    1651              : 
    1652           30 :     relid = DatumGetCString(DirectFunctionCall1(oidout,
    1653              :                                                 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
    1654              : 
    1655           30 :     hv_store_string(hv, "name", cstr2sv(tdata->tg_trigger->tgname));
    1656           30 :     hv_store_string(hv, "relid", cstr2sv(relid));
    1657              : 
    1658              :     /*
    1659              :      * Note: In BEFORE trigger, stored generated columns are not computed yet,
    1660              :      * so don't make them accessible in NEW row.
    1661              :      */
    1662              : 
    1663           30 :     if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
    1664              :     {
    1665           12 :         event = "INSERT";
    1666           12 :         if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
    1667           12 :             hv_store_string(hv, "new",
    1668              :                             plperl_hash_from_tuple(tdata->tg_trigtuple,
    1669              :                                                    tupdesc,
    1670           12 :                                                    !TRIGGER_FIRED_BEFORE(tdata->tg_event)));
    1671              :     }
    1672           18 :     else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
    1673              :     {
    1674           10 :         event = "DELETE";
    1675           10 :         if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
    1676           10 :             hv_store_string(hv, "old",
    1677              :                             plperl_hash_from_tuple(tdata->tg_trigtuple,
    1678              :                                                    tupdesc,
    1679              :                                                    true));
    1680              :     }
    1681            8 :     else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
    1682              :     {
    1683            8 :         event = "UPDATE";
    1684            8 :         if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
    1685              :         {
    1686            7 :             hv_store_string(hv, "old",
    1687              :                             plperl_hash_from_tuple(tdata->tg_trigtuple,
    1688              :                                                    tupdesc,
    1689              :                                                    true));
    1690            7 :             hv_store_string(hv, "new",
    1691              :                             plperl_hash_from_tuple(tdata->tg_newtuple,
    1692              :                                                    tupdesc,
    1693            7 :                                                    !TRIGGER_FIRED_BEFORE(tdata->tg_event)));
    1694              :         }
    1695              :     }
    1696            0 :     else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
    1697            0 :         event = "TRUNCATE";
    1698              :     else
    1699            0 :         event = "UNKNOWN";
    1700              : 
    1701           30 :     hv_store_string(hv, "event", cstr2sv(event));
    1702           30 :     hv_store_string(hv, "argc", newSViv(tdata->tg_trigger->tgnargs));
    1703              : 
    1704           30 :     if (tdata->tg_trigger->tgnargs > 0)
    1705              :     {
    1706           12 :         AV         *av = newAV();
    1707              : 
    1708           12 :         av_extend(av, tdata->tg_trigger->tgnargs);
    1709           30 :         for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
    1710           18 :             av_push(av, cstr2sv(tdata->tg_trigger->tgargs[i]));
    1711           12 :         hv_store_string(hv, "args", newRV_noinc((SV *) av));
    1712              :     }
    1713              : 
    1714           30 :     hv_store_string(hv, "relname",
    1715           30 :                     cstr2sv(SPI_getrelname(tdata->tg_relation)));
    1716              : 
    1717           30 :     hv_store_string(hv, "table_name",
    1718           30 :                     cstr2sv(SPI_getrelname(tdata->tg_relation)));
    1719              : 
    1720           30 :     hv_store_string(hv, "table_schema",
    1721           30 :                     cstr2sv(SPI_getnspname(tdata->tg_relation)));
    1722              : 
    1723           30 :     if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
    1724           23 :         when = "BEFORE";
    1725            7 :     else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
    1726            4 :         when = "AFTER";
    1727            3 :     else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
    1728            3 :         when = "INSTEAD OF";
    1729              :     else
    1730            0 :         when = "UNKNOWN";
    1731           30 :     hv_store_string(hv, "when", cstr2sv(when));
    1732              : 
    1733           30 :     if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
    1734           29 :         level = "ROW";
    1735            1 :     else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
    1736            1 :         level = "STATEMENT";
    1737              :     else
    1738            0 :         level = "UNKNOWN";
    1739           30 :     hv_store_string(hv, "level", cstr2sv(level));
    1740              : 
    1741           30 :     return newRV_noinc((SV *) hv);
    1742              : }
    1743              : 
    1744              : 
    1745              : /* Set up the arguments for an event trigger call. */
    1746              : static SV  *
    1747           10 : plperl_event_trigger_build_args(FunctionCallInfo fcinfo)
    1748              : {
    1749           10 :     dTHX;
    1750              :     EventTriggerData *tdata;
    1751              :     HV         *hv;
    1752              : 
    1753           10 :     hv = newHV();
    1754              : 
    1755           10 :     tdata = (EventTriggerData *) fcinfo->context;
    1756              : 
    1757           10 :     hv_store_string(hv, "event", cstr2sv(tdata->event));
    1758           10 :     hv_store_string(hv, "tag", cstr2sv(GetCommandTagName(tdata->tag)));
    1759              : 
    1760           10 :     return newRV_noinc((SV *) hv);
    1761              : }
    1762              : 
    1763              : /* Construct the modified new tuple to be returned from a trigger. */
    1764              : static HeapTuple
    1765            6 : plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup)
    1766              : {
    1767            6 :     dTHX;
    1768              :     SV        **svp;
    1769              :     HV         *hvNew;
    1770              :     HE         *he;
    1771              :     HeapTuple   rtup;
    1772              :     TupleDesc   tupdesc;
    1773              :     int         natts;
    1774              :     Datum      *modvalues;
    1775              :     bool       *modnulls;
    1776              :     bool       *modrepls;
    1777              : 
    1778            6 :     svp = hv_fetch_string(hvTD, "new");
    1779            6 :     if (!svp)
    1780            0 :         ereport(ERROR,
    1781              :                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    1782              :                  errmsg("$_TD->{new} does not exist")));
    1783            6 :     if (!SvOK(*svp) || !SvROK(*svp) || SvTYPE(SvRV(*svp)) != SVt_PVHV)
    1784            0 :         ereport(ERROR,
    1785              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    1786              :                  errmsg("$_TD->{new} is not a hash reference")));
    1787            6 :     hvNew = (HV *) SvRV(*svp);
    1788              : 
    1789            6 :     tupdesc = tdata->tg_relation->rd_att;
    1790            6 :     natts = tupdesc->natts;
    1791              : 
    1792            6 :     modvalues = (Datum *) palloc0(natts * sizeof(Datum));
    1793            6 :     modnulls = (bool *) palloc0(natts * sizeof(bool));
    1794            6 :     modrepls = (bool *) palloc0(natts * sizeof(bool));
    1795              : 
    1796            6 :     hv_iterinit(hvNew);
    1797           21 :     while ((he = hv_iternext(hvNew)))
    1798              :     {
    1799           16 :         char       *key = hek2cstr(he);
    1800           16 :         SV         *val = HeVAL(he);
    1801           16 :         int         attn = SPI_fnumber(tupdesc, key);
    1802           16 :         Form_pg_attribute attr = TupleDescAttr(tupdesc, attn - 1);
    1803              : 
    1804           16 :         if (attn == SPI_ERROR_NOATTRIBUTE)
    1805            0 :             ereport(ERROR,
    1806              :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    1807              :                      errmsg("Perl hash contains nonexistent column \"%s\"",
    1808              :                             key)));
    1809           16 :         if (attn <= 0)
    1810            0 :             ereport(ERROR,
    1811              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1812              :                      errmsg("cannot set system attribute \"%s\"",
    1813              :                             key)));
    1814           16 :         if (attr->attgenerated)
    1815            1 :             ereport(ERROR,
    1816              :                     (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    1817              :                      errmsg("cannot set generated column \"%s\"",
    1818              :                             key)));
    1819              : 
    1820           30 :         modvalues[attn - 1] = plperl_sv_to_datum(val,
    1821              :                                                  attr->atttypid,
    1822              :                                                  attr->atttypmod,
    1823              :                                                  NULL,
    1824              :                                                  NULL,
    1825              :                                                  InvalidOid,
    1826           15 :                                                  &modnulls[attn - 1]);
    1827           15 :         modrepls[attn - 1] = true;
    1828              : 
    1829           15 :         pfree(key);
    1830              :     }
    1831            5 :     hv_iterinit(hvNew);
    1832              : 
    1833            5 :     rtup = heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls);
    1834              : 
    1835            5 :     pfree(modvalues);
    1836            5 :     pfree(modnulls);
    1837            5 :     pfree(modrepls);
    1838              : 
    1839            5 :     return rtup;
    1840              : }
    1841              : 
    1842              : 
    1843              : /*
    1844              :  * There are three externally visible pieces to plperl: plperl_call_handler,
    1845              :  * plperl_inline_handler, and plperl_validator.
    1846              :  */
    1847              : 
    1848              : /*
    1849              :  * The call handler is called to run normal functions (including trigger
    1850              :  * functions) that are defined in pg_proc.
    1851              :  */
    1852           22 : PG_FUNCTION_INFO_V1(plperl_call_handler);
    1853              : 
    1854              : Datum
    1855          274 : plperl_call_handler(PG_FUNCTION_ARGS)
    1856              : {
    1857          274 :     Datum       retval = (Datum) 0;
    1858          274 :     plperl_call_data *volatile save_call_data = current_call_data;
    1859          274 :     plperl_interp_desc *volatile oldinterp = plperl_active_interp;
    1860              :     plperl_call_data this_call_data;
    1861              : 
    1862              :     /* Initialize current-call status record */
    1863         2192 :     MemSet(&this_call_data, 0, sizeof(this_call_data));
    1864          274 :     this_call_data.fcinfo = fcinfo;
    1865              : 
    1866          274 :     PG_TRY();
    1867              :     {
    1868          274 :         current_call_data = &this_call_data;
    1869          274 :         if (CALLED_AS_TRIGGER(fcinfo))
    1870           30 :             retval = plperl_trigger_handler(fcinfo);
    1871          244 :         else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
    1872              :         {
    1873           10 :             plperl_event_trigger_handler(fcinfo);
    1874           10 :             retval = (Datum) 0;
    1875              :         }
    1876              :         else
    1877          234 :             retval = plperl_func_handler(fcinfo);
    1878              :     }
    1879           42 :     PG_FINALLY();
    1880              :     {
    1881          274 :         current_call_data = save_call_data;
    1882          274 :         activate_interpreter(oldinterp);
    1883          274 :         if (this_call_data.prodesc)
    1884          273 :             decrement_prodesc_refcount(this_call_data.prodesc);
    1885              :     }
    1886          274 :     PG_END_TRY();
    1887              : 
    1888          232 :     return retval;
    1889              : }
    1890              : 
    1891              : /*
    1892              :  * The inline handler runs anonymous code blocks (DO blocks).
    1893              :  */
    1894           12 : PG_FUNCTION_INFO_V1(plperl_inline_handler);
    1895              : 
    1896              : Datum
    1897           22 : plperl_inline_handler(PG_FUNCTION_ARGS)
    1898              : {
    1899           22 :     LOCAL_FCINFO(fake_fcinfo, 0);
    1900           22 :     InlineCodeBlock *codeblock = (InlineCodeBlock *) PG_GETARG_POINTER(0);
    1901              :     FmgrInfo    flinfo;
    1902              :     plperl_proc_desc desc;
    1903           22 :     plperl_call_data *volatile save_call_data = current_call_data;
    1904           22 :     plperl_interp_desc *volatile oldinterp = plperl_active_interp;
    1905              :     plperl_call_data this_call_data;
    1906              :     ErrorContextCallback pl_error_context;
    1907              : 
    1908              :     /* Initialize current-call status record */
    1909          176 :     MemSet(&this_call_data, 0, sizeof(this_call_data));
    1910              : 
    1911              :     /* Set up a callback for error reporting */
    1912           22 :     pl_error_context.callback = plperl_inline_callback;
    1913           22 :     pl_error_context.previous = error_context_stack;
    1914           22 :     pl_error_context.arg = NULL;
    1915           22 :     error_context_stack = &pl_error_context;
    1916              : 
    1917              :     /*
    1918              :      * Set up a fake fcinfo and descriptor with just enough info to satisfy
    1919              :      * plperl_call_perl_func().  In particular note that this sets things up
    1920              :      * with no arguments passed, and a result type of VOID.
    1921              :      */
    1922          110 :     MemSet(fake_fcinfo, 0, SizeForFunctionCallInfo(0));
    1923          154 :     MemSet(&flinfo, 0, sizeof(flinfo));
    1924          462 :     MemSet(&desc, 0, sizeof(desc));
    1925           22 :     fake_fcinfo->flinfo = &flinfo;
    1926           22 :     flinfo.fn_oid = InvalidOid;
    1927           22 :     flinfo.fn_mcxt = CurrentMemoryContext;
    1928              : 
    1929           22 :     desc.proname = "inline_code_block";
    1930           22 :     desc.fn_readonly = false;
    1931              : 
    1932           22 :     desc.lang_oid = codeblock->langOid;
    1933           22 :     desc.trftypes = NIL;
    1934           22 :     desc.lanpltrusted = codeblock->langIsTrusted;
    1935              : 
    1936           22 :     desc.fn_retistuple = false;
    1937           22 :     desc.fn_retisset = false;
    1938           22 :     desc.fn_retisarray = false;
    1939           22 :     desc.result_oid = InvalidOid;
    1940           22 :     desc.nargs = 0;
    1941           22 :     desc.reference = NULL;
    1942              : 
    1943           22 :     this_call_data.fcinfo = fake_fcinfo;
    1944           22 :     this_call_data.prodesc = &desc;
    1945              :     /* we do not bother with refcounting the fake prodesc */
    1946              : 
    1947           22 :     PG_TRY();
    1948              :     {
    1949              :         SV         *perlret;
    1950              : 
    1951           22 :         current_call_data = &this_call_data;
    1952              : 
    1953           22 :         SPI_connect_ext(codeblock->atomic ? 0 : SPI_OPT_NONATOMIC);
    1954              : 
    1955           22 :         select_perl_context(desc.lanpltrusted);
    1956              : 
    1957           21 :         plperl_create_sub(&desc, codeblock->source_text, 0);
    1958              : 
    1959           16 :         if (!desc.reference)    /* can this happen? */
    1960            0 :             elog(ERROR, "could not create internal procedure for anonymous code block");
    1961              : 
    1962           16 :         perlret = plperl_call_perl_func(&desc, fake_fcinfo);
    1963              : 
    1964           11 :         SvREFCNT_dec_current(perlret);
    1965              : 
    1966           11 :         if (SPI_finish() != SPI_OK_FINISH)
    1967            0 :             elog(ERROR, "SPI_finish() failed");
    1968              :     }
    1969           11 :     PG_FINALLY();
    1970              :     {
    1971           22 :         if (desc.reference)
    1972           16 :             SvREFCNT_dec_current(desc.reference);
    1973           22 :         current_call_data = save_call_data;
    1974           22 :         activate_interpreter(oldinterp);
    1975              :     }
    1976           22 :     PG_END_TRY();
    1977              : 
    1978           11 :     error_context_stack = pl_error_context.previous;
    1979              : 
    1980           11 :     PG_RETURN_VOID();
    1981              : }
    1982              : 
    1983              : /*
    1984              :  * The validator is called during CREATE FUNCTION to validate the function
    1985              :  * being created/replaced. The precise behavior of the validator may be
    1986              :  * modified by the check_function_bodies GUC.
    1987              :  */
    1988           22 : PG_FUNCTION_INFO_V1(plperl_validator);
    1989              : 
    1990              : Datum
    1991          152 : plperl_validator(PG_FUNCTION_ARGS)
    1992              : {
    1993          152 :     Oid         funcoid = PG_GETARG_OID(0);
    1994              :     HeapTuple   tuple;
    1995              :     Form_pg_proc proc;
    1996              :     char        functyptype;
    1997              :     int         numargs;
    1998              :     Oid        *argtypes;
    1999              :     char      **argnames;
    2000              :     char       *argmodes;
    2001          152 :     bool        is_trigger = false;
    2002          152 :     bool        is_event_trigger = false;
    2003              :     int         i;
    2004              : 
    2005          152 :     if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
    2006            0 :         PG_RETURN_VOID();
    2007              : 
    2008              :     /* Get the new function's pg_proc entry */
    2009          152 :     tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
    2010          152 :     if (!HeapTupleIsValid(tuple))
    2011            0 :         elog(ERROR, "cache lookup failed for function %u", funcoid);
    2012          152 :     proc = (Form_pg_proc) GETSTRUCT(tuple);
    2013              : 
    2014          152 :     functyptype = get_typtype(proc->prorettype);
    2015              : 
    2016              :     /* Disallow pseudotype result */
    2017              :     /* except for TRIGGER, EVTTRIGGER, RECORD, or VOID */
    2018          152 :     if (functyptype == TYPTYPE_PSEUDO)
    2019              :     {
    2020           38 :         if (proc->prorettype == TRIGGEROID)
    2021            8 :             is_trigger = true;
    2022           30 :         else if (proc->prorettype == EVENT_TRIGGEROID)
    2023            1 :             is_event_trigger = true;
    2024           29 :         else if (proc->prorettype != RECORDOID &&
    2025           18 :                  proc->prorettype != VOIDOID)
    2026            0 :             ereport(ERROR,
    2027              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2028              :                      errmsg("PL/Perl functions cannot return type %s",
    2029              :                             format_type_be(proc->prorettype))));
    2030              :     }
    2031              : 
    2032              :     /* Disallow pseudotypes in arguments (either IN or OUT) */
    2033          152 :     numargs = get_func_arg_info(tuple,
    2034              :                                 &argtypes, &argnames, &argmodes);
    2035          225 :     for (i = 0; i < numargs; i++)
    2036              :     {
    2037           73 :         if (get_typtype(argtypes[i]) == TYPTYPE_PSEUDO &&
    2038            1 :             argtypes[i] != RECORDOID)
    2039            0 :             ereport(ERROR,
    2040              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2041              :                      errmsg("PL/Perl functions cannot accept type %s",
    2042              :                             format_type_be(argtypes[i]))));
    2043              :     }
    2044              : 
    2045          152 :     ReleaseSysCache(tuple);
    2046              : 
    2047              :     /* Postpone body checks if !check_function_bodies */
    2048          152 :     if (check_function_bodies)
    2049              :     {
    2050          152 :         (void) compile_plperl_function(funcoid, is_trigger, is_event_trigger);
    2051              :     }
    2052              : 
    2053              :     /* the result of a validator is ignored */
    2054          149 :     PG_RETURN_VOID();
    2055              : }
    2056              : 
    2057              : 
    2058              : /*
    2059              :  * plperlu likewise requires three externally visible functions:
    2060              :  * plperlu_call_handler, plperlu_inline_handler, and plperlu_validator.
    2061              :  * These are currently just aliases that send control to the plperl
    2062              :  * handler functions, and we decide whether a particular function is
    2063              :  * trusted or not by inspecting the actual pg_language tuple.
    2064              :  */
    2065              : 
    2066            8 : PG_FUNCTION_INFO_V1(plperlu_call_handler);
    2067              : 
    2068              : Datum
    2069           50 : plperlu_call_handler(PG_FUNCTION_ARGS)
    2070              : {
    2071           50 :     return plperl_call_handler(fcinfo);
    2072              : }
    2073              : 
    2074            5 : PG_FUNCTION_INFO_V1(plperlu_inline_handler);
    2075              : 
    2076              : Datum
    2077            1 : plperlu_inline_handler(PG_FUNCTION_ARGS)
    2078              : {
    2079            1 :     return plperl_inline_handler(fcinfo);
    2080              : }
    2081              : 
    2082            9 : PG_FUNCTION_INFO_V1(plperlu_validator);
    2083              : 
    2084              : Datum
    2085           24 : plperlu_validator(PG_FUNCTION_ARGS)
    2086              : {
    2087              :     /* call plperl validator with our fcinfo so it gets our oid */
    2088           24 :     return plperl_validator(fcinfo);
    2089              : }
    2090              : 
    2091              : 
    2092              : /*
    2093              :  * Uses mkfunc to create a subroutine whose text is
    2094              :  * supplied in s, and returns a reference to it
    2095              :  */
    2096              : static void
    2097          173 : plperl_create_sub(plperl_proc_desc *prodesc, const char *s, Oid fn_oid)
    2098              : {
    2099          173 :     dTHX;
    2100          173 :     dSP;
    2101              :     char        subname[NAMEDATALEN + 40];
    2102          173 :     HV         *pragma_hv = newHV();
    2103          173 :     SV         *subref = NULL;
    2104              :     int         count;
    2105              : 
    2106          173 :     sprintf(subname, "%s__%u", prodesc->proname, fn_oid);
    2107              : 
    2108          173 :     if (plperl_use_strict)
    2109            1 :         hv_store_string(pragma_hv, "strict", (SV *) newAV());
    2110              : 
    2111          173 :     ENTER;
    2112          173 :     SAVETMPS;
    2113          173 :     PUSHMARK(SP);
    2114          173 :     EXTEND(SP, 4);
    2115          173 :     PUSHs(sv_2mortal(cstr2sv(subname)));
    2116          173 :     PUSHs(sv_2mortal(newRV_noinc((SV *) pragma_hv)));
    2117              : 
    2118              :     /*
    2119              :      * Use 'false' for $prolog in mkfunc, which is kept for compatibility in
    2120              :      * case a module such as PostgreSQL::PLPerl::NYTprof replaces the function
    2121              :      * compiler.
    2122              :      */
    2123          173 :     PUSHs(&PL_sv_no);
    2124          173 :     PUSHs(sv_2mortal(cstr2sv(s)));
    2125          173 :     PUTBACK;
    2126              : 
    2127              :     /*
    2128              :      * G_KEEPERR seems to be needed here, else we don't recognize compile
    2129              :      * errors properly.  Perhaps it's because there's another level of eval
    2130              :      * inside mkfunc?
    2131              :      */
    2132          173 :     count = call_pv("PostgreSQL::InServer::mkfunc",
    2133              :                     G_SCALAR | G_EVAL | G_KEEPERR);
    2134          173 :     SPAGAIN;
    2135              : 
    2136          173 :     if (count == 1)
    2137              :     {
    2138          173 :         SV         *sub_rv = (SV *) POPs;
    2139              : 
    2140          173 :         if (sub_rv && SvROK(sub_rv) && SvTYPE(SvRV(sub_rv)) == SVt_PVCV)
    2141              :         {
    2142          165 :             subref = newRV_inc(SvRV(sub_rv));
    2143              :         }
    2144              :     }
    2145              : 
    2146          173 :     PUTBACK;
    2147          173 :     FREETMPS;
    2148          173 :     LEAVE;
    2149              : 
    2150          173 :     if (SvTRUE(ERRSV))
    2151            8 :         ereport(ERROR,
    2152              :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2153              :                  errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
    2154              : 
    2155          165 :     if (!subref)
    2156            0 :         ereport(ERROR,
    2157              :                 (errcode(ERRCODE_SYNTAX_ERROR),
    2158              :                  errmsg("didn't get a CODE reference from compiling function \"%s\"",
    2159              :                         prodesc->proname)));
    2160              : 
    2161          165 :     prodesc->reference = subref;
    2162          165 : }
    2163              : 
    2164              : 
    2165              : /**********************************************************************
    2166              :  * plperl_init_shared_libs()        -
    2167              :  **********************************************************************/
    2168              : 
    2169              : static void
    2170           25 : plperl_init_shared_libs(pTHX)
    2171              : {
    2172           25 :     char       *file = __FILE__;
    2173              : 
    2174           25 :     newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
    2175           25 :     newXS("PostgreSQL::InServer::Util::bootstrap",
    2176              :           boot_PostgreSQL__InServer__Util, file);
    2177              :     /* newXS for...::SPI::bootstrap is in select_perl_context() */
    2178           25 : }
    2179              : 
    2180              : 
    2181              : static SV  *
    2182          249 : plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
    2183              : {
    2184          249 :     dTHX;
    2185          249 :     dSP;
    2186              :     SV         *retval;
    2187              :     int         i;
    2188              :     int         count;
    2189          249 :     Oid        *argtypes = NULL;
    2190          249 :     int         nargs = 0;
    2191              : 
    2192          249 :     ENTER;
    2193          249 :     SAVETMPS;
    2194              : 
    2195          249 :     PUSHMARK(SP);
    2196          249 :     EXTEND(sp, desc->nargs);
    2197              : 
    2198              :     /* Get signature for true functions; inline blocks have no args. */
    2199          249 :     if (fcinfo->flinfo->fn_oid)
    2200          233 :         get_func_signature(fcinfo->flinfo->fn_oid, &argtypes, &nargs);
    2201              :     Assert(nargs == desc->nargs);
    2202              : 
    2203          441 :     for (i = 0; i < desc->nargs; i++)
    2204              :     {
    2205          192 :         if (fcinfo->args[i].isnull)
    2206            4 :             PUSHs(&PL_sv_undef);
    2207          188 :         else if (desc->arg_is_rowtype[i])
    2208              :         {
    2209           11 :             SV         *sv = plperl_hash_from_datum(fcinfo->args[i].value);
    2210              : 
    2211           11 :             PUSHs(sv_2mortal(sv));
    2212              :         }
    2213              :         else
    2214              :         {
    2215              :             SV         *sv;
    2216              :             Oid         funcid;
    2217              : 
    2218          177 :             if (OidIsValid(desc->arg_arraytype[i]))
    2219           13 :                 sv = plperl_ref_from_pg_array(fcinfo->args[i].value, desc->arg_arraytype[i]);
    2220          164 :             else if ((funcid = get_transform_fromsql(argtypes[i], current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
    2221           57 :                 sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, fcinfo->args[i].value));
    2222              :             else
    2223              :             {
    2224              :                 char       *tmp;
    2225              : 
    2226          107 :                 tmp = OutputFunctionCall(&(desc->arg_out_func[i]),
    2227              :                                          fcinfo->args[i].value);
    2228          107 :                 sv = cstr2sv(tmp);
    2229          107 :                 pfree(tmp);
    2230              :             }
    2231              : 
    2232          177 :             PUSHs(sv_2mortal(sv));
    2233              :         }
    2234              :     }
    2235          249 :     PUTBACK;
    2236              : 
    2237              :     /* Do NOT use G_KEEPERR here */
    2238          249 :     count = call_sv(desc->reference, G_SCALAR | G_EVAL);
    2239              : 
    2240          248 :     SPAGAIN;
    2241              : 
    2242          248 :     if (count != 1)
    2243              :     {
    2244            0 :         PUTBACK;
    2245            0 :         FREETMPS;
    2246            0 :         LEAVE;
    2247            0 :         ereport(ERROR,
    2248              :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    2249              :                  errmsg("didn't get a return item from function")));
    2250              :     }
    2251              : 
    2252          248 :     if (SvTRUE(ERRSV))
    2253              :     {
    2254           18 :         (void) POPs;
    2255           18 :         PUTBACK;
    2256           18 :         FREETMPS;
    2257           18 :         LEAVE;
    2258              :         /* XXX need to find a way to determine a better errcode here */
    2259           18 :         ereport(ERROR,
    2260              :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    2261              :                  errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
    2262              :     }
    2263              : 
    2264          230 :     retval = newSVsv(POPs);
    2265              : 
    2266          230 :     PUTBACK;
    2267          230 :     FREETMPS;
    2268          230 :     LEAVE;
    2269              : 
    2270          230 :     return retval;
    2271              : }
    2272              : 
    2273              : 
    2274              : static SV  *
    2275           30 : plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo,
    2276              :                               SV *td)
    2277              : {
    2278           30 :     dTHX;
    2279           30 :     dSP;
    2280              :     SV         *retval,
    2281              :                *TDsv;
    2282              :     int         i,
    2283              :                 count;
    2284           30 :     Trigger    *tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
    2285              : 
    2286           30 :     ENTER;
    2287           30 :     SAVETMPS;
    2288              : 
    2289           30 :     TDsv = get_sv("main::_TD", 0);
    2290           30 :     if (!TDsv)
    2291            0 :         ereport(ERROR,
    2292              :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    2293              :                  errmsg("couldn't fetch $_TD")));
    2294              : 
    2295           30 :     save_item(TDsv);            /* local $_TD */
    2296           30 :     sv_setsv(TDsv, td);
    2297              : 
    2298           30 :     PUSHMARK(sp);
    2299           30 :     EXTEND(sp, tg_trigger->tgnargs);
    2300              : 
    2301           48 :     for (i = 0; i < tg_trigger->tgnargs; i++)
    2302           18 :         PUSHs(sv_2mortal(cstr2sv(tg_trigger->tgargs[i])));
    2303           30 :     PUTBACK;
    2304              : 
    2305              :     /* Do NOT use G_KEEPERR here */
    2306           30 :     count = call_sv(desc->reference, G_SCALAR | G_EVAL);
    2307              : 
    2308           30 :     SPAGAIN;
    2309              : 
    2310           30 :     if (count != 1)
    2311              :     {
    2312            0 :         PUTBACK;
    2313            0 :         FREETMPS;
    2314            0 :         LEAVE;
    2315            0 :         ereport(ERROR,
    2316              :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    2317              :                  errmsg("didn't get a return item from trigger function")));
    2318              :     }
    2319              : 
    2320           30 :     if (SvTRUE(ERRSV))
    2321              :     {
    2322            0 :         (void) POPs;
    2323            0 :         PUTBACK;
    2324            0 :         FREETMPS;
    2325            0 :         LEAVE;
    2326              :         /* XXX need to find a way to determine a better errcode here */
    2327            0 :         ereport(ERROR,
    2328              :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    2329              :                  errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
    2330              :     }
    2331              : 
    2332           30 :     retval = newSVsv(POPs);
    2333              : 
    2334           30 :     PUTBACK;
    2335           30 :     FREETMPS;
    2336           30 :     LEAVE;
    2337              : 
    2338           30 :     return retval;
    2339              : }
    2340              : 
    2341              : 
    2342              : static void
    2343           10 : plperl_call_perl_event_trigger_func(plperl_proc_desc *desc,
    2344              :                                     FunctionCallInfo fcinfo,
    2345              :                                     SV *td)
    2346              : {
    2347           10 :     dTHX;
    2348           10 :     dSP;
    2349              :     SV         *retval,
    2350              :                *TDsv;
    2351              :     int         count;
    2352              : 
    2353           10 :     ENTER;
    2354           10 :     SAVETMPS;
    2355              : 
    2356           10 :     TDsv = get_sv("main::_TD", 0);
    2357           10 :     if (!TDsv)
    2358            0 :         ereport(ERROR,
    2359              :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    2360              :                  errmsg("couldn't fetch $_TD")));
    2361              : 
    2362           10 :     save_item(TDsv);            /* local $_TD */
    2363           10 :     sv_setsv(TDsv, td);
    2364              : 
    2365           10 :     PUSHMARK(sp);
    2366           10 :     PUTBACK;
    2367              : 
    2368              :     /* Do NOT use G_KEEPERR here */
    2369           10 :     count = call_sv(desc->reference, G_SCALAR | G_EVAL);
    2370              : 
    2371           10 :     SPAGAIN;
    2372              : 
    2373           10 :     if (count != 1)
    2374              :     {
    2375            0 :         PUTBACK;
    2376            0 :         FREETMPS;
    2377            0 :         LEAVE;
    2378            0 :         ereport(ERROR,
    2379              :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    2380              :                  errmsg("didn't get a return item from trigger function")));
    2381              :     }
    2382              : 
    2383           10 :     if (SvTRUE(ERRSV))
    2384              :     {
    2385            0 :         (void) POPs;
    2386            0 :         PUTBACK;
    2387            0 :         FREETMPS;
    2388            0 :         LEAVE;
    2389              :         /* XXX need to find a way to determine a better errcode here */
    2390            0 :         ereport(ERROR,
    2391              :                 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
    2392              :                  errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
    2393              :     }
    2394              : 
    2395           10 :     retval = newSVsv(POPs);
    2396              :     (void) retval;              /* silence compiler warning */
    2397              : 
    2398           10 :     PUTBACK;
    2399           10 :     FREETMPS;
    2400           10 :     LEAVE;
    2401           10 : }
    2402              : 
    2403              : static Datum
    2404          234 : plperl_func_handler(PG_FUNCTION_ARGS)
    2405              : {
    2406              :     bool        nonatomic;
    2407              :     plperl_proc_desc *prodesc;
    2408              :     SV         *perlret;
    2409          234 :     Datum       retval = 0;
    2410              :     ReturnSetInfo *rsi;
    2411              :     ErrorContextCallback pl_error_context;
    2412              : 
    2413          476 :     nonatomic = fcinfo->context &&
    2414          242 :         IsA(fcinfo->context, CallContext) &&
    2415            8 :         !castNode(CallContext, fcinfo->context)->atomic;
    2416              : 
    2417          234 :     SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0);
    2418              : 
    2419          234 :     prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, false);
    2420          233 :     current_call_data->prodesc = prodesc;
    2421          233 :     increment_prodesc_refcount(prodesc);
    2422              : 
    2423              :     /* Set a callback for error reporting */
    2424          233 :     pl_error_context.callback = plperl_exec_callback;
    2425          233 :     pl_error_context.previous = error_context_stack;
    2426          233 :     pl_error_context.arg = prodesc->proname;
    2427          233 :     error_context_stack = &pl_error_context;
    2428              : 
    2429          233 :     rsi = (ReturnSetInfo *) fcinfo->resultinfo;
    2430              : 
    2431          233 :     if (prodesc->fn_retisset)
    2432              :     {
    2433              :         /* Check context before allowing the call to go through */
    2434           43 :         if (!rsi || !IsA(rsi, ReturnSetInfo))
    2435            0 :             ereport(ERROR,
    2436              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2437              :                      errmsg("set-valued function called in context that cannot accept a set")));
    2438              : 
    2439           43 :         if (!(rsi->allowedModes & SFRM_Materialize))
    2440            0 :             ereport(ERROR,
    2441              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2442              :                      errmsg("materialize mode required, but it is not allowed in this context")));
    2443              :     }
    2444              : 
    2445          233 :     activate_interpreter(prodesc->interp);
    2446              : 
    2447          233 :     perlret = plperl_call_perl_func(prodesc, fcinfo);
    2448              : 
    2449              :     /************************************************************
    2450              :      * Disconnect from SPI manager and then create the return
    2451              :      * values datum (if the input function does a palloc for it
    2452              :      * this must not be allocated in the SPI memory context
    2453              :      * because SPI_finish would free it).
    2454              :      ************************************************************/
    2455          219 :     if (SPI_finish() != SPI_OK_FINISH)
    2456            0 :         elog(ERROR, "SPI_finish() failed");
    2457              : 
    2458          219 :     if (prodesc->fn_retisset)
    2459              :     {
    2460              :         SV         *sav;
    2461              : 
    2462              :         /*
    2463              :          * If the Perl function returned an arrayref, we pretend that it
    2464              :          * called return_next() for each element of the array, to handle old
    2465              :          * SRFs that didn't know about return_next(). Any other sort of return
    2466              :          * value is an error, except undef which means return an empty set.
    2467              :          */
    2468           42 :         sav = get_perl_array_ref(perlret);
    2469           42 :         if (sav)
    2470              :         {
    2471           18 :             dTHX;
    2472           18 :             int         i = 0;
    2473           18 :             SV        **svp = 0;
    2474           18 :             AV         *rav = (AV *) SvRV(sav);
    2475              : 
    2476           64 :             while ((svp = av_fetch(rav, i, FALSE)) != NULL)
    2477              :             {
    2478           54 :                 plperl_return_next_internal(*svp);
    2479           46 :                 i++;
    2480              :             }
    2481              :         }
    2482           24 :         else if (SvOK(perlret))
    2483              :         {
    2484            2 :             ereport(ERROR,
    2485              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2486              :                      errmsg("set-returning PL/Perl function must return "
    2487              :                             "reference to array or use return_next")));
    2488              :         }
    2489              : 
    2490           32 :         rsi->returnMode = SFRM_Materialize;
    2491           32 :         if (current_call_data->tuple_store)
    2492              :         {
    2493           26 :             rsi->setResult = current_call_data->tuple_store;
    2494           26 :             rsi->setDesc = current_call_data->ret_tdesc;
    2495              :         }
    2496           32 :         retval = (Datum) 0;
    2497              :     }
    2498          177 :     else if (prodesc->result_oid)
    2499              :     {
    2500          177 :         retval = plperl_sv_to_datum(perlret,
    2501              :                                     prodesc->result_oid,
    2502              :                                     -1,
    2503              :                                     fcinfo,
    2504              :                                     &prodesc->result_in_func,
    2505              :                                     prodesc->result_typioparam,
    2506              :                                     &fcinfo->isnull);
    2507              : 
    2508          161 :         if (fcinfo->isnull && rsi && IsA(rsi, ReturnSetInfo))
    2509            3 :             rsi->isDone = ExprEndResult;
    2510              :     }
    2511              : 
    2512              :     /* Restore the previous error callback */
    2513          193 :     error_context_stack = pl_error_context.previous;
    2514              : 
    2515          193 :     SvREFCNT_dec_current(perlret);
    2516              : 
    2517          193 :     return retval;
    2518              : }
    2519              : 
    2520              : 
    2521              : static Datum
    2522           30 : plperl_trigger_handler(PG_FUNCTION_ARGS)
    2523              : {
    2524              :     plperl_proc_desc *prodesc;
    2525              :     SV         *perlret;
    2526              :     Datum       retval;
    2527              :     SV         *svTD;
    2528              :     HV         *hvTD;
    2529              :     ErrorContextCallback pl_error_context;
    2530              :     TriggerData *tdata;
    2531              :     int         rc PG_USED_FOR_ASSERTS_ONLY;
    2532              : 
    2533              :     /* Connect to SPI manager */
    2534           30 :     SPI_connect();
    2535              : 
    2536              :     /* Make transition tables visible to this SPI connection */
    2537           30 :     tdata = (TriggerData *) fcinfo->context;
    2538           30 :     rc = SPI_register_trigger_data(tdata);
    2539              :     Assert(rc >= 0);
    2540              : 
    2541              :     /* Find or compile the function */
    2542           30 :     prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true, false);
    2543           30 :     current_call_data->prodesc = prodesc;
    2544           30 :     increment_prodesc_refcount(prodesc);
    2545              : 
    2546              :     /* Set a callback for error reporting */
    2547           30 :     pl_error_context.callback = plperl_exec_callback;
    2548           30 :     pl_error_context.previous = error_context_stack;
    2549           30 :     pl_error_context.arg = prodesc->proname;
    2550           30 :     error_context_stack = &pl_error_context;
    2551              : 
    2552           30 :     activate_interpreter(prodesc->interp);
    2553              : 
    2554           30 :     svTD = plperl_trigger_build_args(fcinfo);
    2555           30 :     perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
    2556           30 :     hvTD = (HV *) SvRV(svTD);
    2557              : 
    2558              :     /************************************************************
    2559              :     * Disconnect from SPI manager and then create the return
    2560              :     * values datum (if the input function does a palloc for it
    2561              :     * this must not be allocated in the SPI memory context
    2562              :     * because SPI_finish would free it).
    2563              :     ************************************************************/
    2564           30 :     if (SPI_finish() != SPI_OK_FINISH)
    2565            0 :         elog(ERROR, "SPI_finish() failed");
    2566              : 
    2567           30 :     if (perlret == NULL || !SvOK(perlret))
    2568           21 :     {
    2569              :         /* undef result means go ahead with original tuple */
    2570           21 :         TriggerData *trigdata = ((TriggerData *) fcinfo->context);
    2571              : 
    2572           21 :         if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
    2573            7 :             retval = PointerGetDatum(trigdata->tg_trigtuple);
    2574           14 :         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
    2575            5 :             retval = PointerGetDatum(trigdata->tg_newtuple);
    2576            9 :         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
    2577            9 :             retval = PointerGetDatum(trigdata->tg_trigtuple);
    2578            0 :         else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
    2579            0 :             retval = PointerGetDatum(trigdata->tg_trigtuple);
    2580              :         else
    2581            0 :             retval = (Datum) 0; /* can this happen? */
    2582              :     }
    2583              :     else
    2584              :     {
    2585              :         HeapTuple   trv;
    2586              :         char       *tmp;
    2587              : 
    2588            9 :         tmp = sv2cstr(perlret);
    2589              : 
    2590            9 :         if (pg_strcasecmp(tmp, "SKIP") == 0)
    2591            3 :             trv = NULL;
    2592            6 :         else if (pg_strcasecmp(tmp, "MODIFY") == 0)
    2593              :         {
    2594            6 :             TriggerData *trigdata = (TriggerData *) fcinfo->context;
    2595              : 
    2596            6 :             if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
    2597            4 :                 trv = plperl_modify_tuple(hvTD, trigdata,
    2598              :                                           trigdata->tg_trigtuple);
    2599            2 :             else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
    2600            2 :                 trv = plperl_modify_tuple(hvTD, trigdata,
    2601              :                                           trigdata->tg_newtuple);
    2602              :             else
    2603              :             {
    2604            0 :                 ereport(WARNING,
    2605              :                         (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2606              :                          errmsg("ignoring modified row in DELETE trigger")));
    2607            0 :                 trv = NULL;
    2608              :             }
    2609              :         }
    2610              :         else
    2611              :         {
    2612            0 :             ereport(ERROR,
    2613              :                     (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2614              :                      errmsg("result of PL/Perl trigger function must be undef, "
    2615              :                             "\"SKIP\", or \"MODIFY\"")));
    2616              :             trv = NULL;
    2617              :         }
    2618            8 :         retval = PointerGetDatum(trv);
    2619            8 :         pfree(tmp);
    2620              :     }
    2621              : 
    2622              :     /* Restore the previous error callback */
    2623           29 :     error_context_stack = pl_error_context.previous;
    2624              : 
    2625           29 :     SvREFCNT_dec_current(svTD);
    2626           29 :     if (perlret)
    2627           29 :         SvREFCNT_dec_current(perlret);
    2628              : 
    2629           29 :     return retval;
    2630              : }
    2631              : 
    2632              : 
    2633              : static void
    2634           10 : plperl_event_trigger_handler(PG_FUNCTION_ARGS)
    2635              : {
    2636              :     plperl_proc_desc *prodesc;
    2637              :     SV         *svTD;
    2638              :     ErrorContextCallback pl_error_context;
    2639              : 
    2640              :     /* Connect to SPI manager */
    2641           10 :     SPI_connect();
    2642              : 
    2643              :     /* Find or compile the function */
    2644           10 :     prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, true);
    2645           10 :     current_call_data->prodesc = prodesc;
    2646           10 :     increment_prodesc_refcount(prodesc);
    2647              : 
    2648              :     /* Set a callback for error reporting */
    2649           10 :     pl_error_context.callback = plperl_exec_callback;
    2650           10 :     pl_error_context.previous = error_context_stack;
    2651           10 :     pl_error_context.arg = prodesc->proname;
    2652           10 :     error_context_stack = &pl_error_context;
    2653              : 
    2654           10 :     activate_interpreter(prodesc->interp);
    2655              : 
    2656           10 :     svTD = plperl_event_trigger_build_args(fcinfo);
    2657           10 :     plperl_call_perl_event_trigger_func(prodesc, fcinfo, svTD);
    2658              : 
    2659           10 :     if (SPI_finish() != SPI_OK_FINISH)
    2660            0 :         elog(ERROR, "SPI_finish() failed");
    2661              : 
    2662              :     /* Restore the previous error callback */
    2663           10 :     error_context_stack = pl_error_context.previous;
    2664              : 
    2665           10 :     SvREFCNT_dec_current(svTD);
    2666           10 : }
    2667              : 
    2668              : 
    2669              : static bool
    2670          629 : validate_plperl_function(plperl_proc_ptr *proc_ptr, HeapTuple procTup)
    2671              : {
    2672          629 :     if (proc_ptr && proc_ptr->proc_ptr)
    2673              :     {
    2674          301 :         plperl_proc_desc *prodesc = proc_ptr->proc_ptr;
    2675              :         bool        uptodate;
    2676              : 
    2677              :         /************************************************************
    2678              :          * If it's present, must check whether it's still up to date.
    2679              :          * This is needed because CREATE OR REPLACE FUNCTION can modify the
    2680              :          * function's pg_proc entry without changing its OID.
    2681              :          ************************************************************/
    2682          574 :         uptodate = (prodesc->fn_xmin == HeapTupleHeaderGetRawXmin(procTup->t_data) &&
    2683          273 :                     ItemPointerEquals(&prodesc->fn_tid, &procTup->t_self));
    2684              : 
    2685          301 :         if (uptodate)
    2686          273 :             return true;
    2687              : 
    2688              :         /* Otherwise, unlink the obsoleted entry from the hashtable ... */
    2689           28 :         proc_ptr->proc_ptr = NULL;
    2690              :         /* ... and release the corresponding refcount, probably deleting it */
    2691           28 :         decrement_prodesc_refcount(prodesc);
    2692              :     }
    2693              : 
    2694          356 :     return false;
    2695              : }
    2696              : 
    2697              : 
    2698              : static void
    2699           28 : free_plperl_function(plperl_proc_desc *prodesc)
    2700              : {
    2701              :     Assert(prodesc->fn_refcount == 0);
    2702              :     /* Release CODE reference, if we have one, from the appropriate interp */
    2703           28 :     if (prodesc->reference)
    2704              :     {
    2705           28 :         plperl_interp_desc *oldinterp = plperl_active_interp;
    2706              : 
    2707           28 :         activate_interpreter(prodesc->interp);
    2708           28 :         SvREFCNT_dec_current(prodesc->reference);
    2709           28 :         activate_interpreter(oldinterp);
    2710              :     }
    2711              :     /* Release all PG-owned data for this proc */
    2712           28 :     MemoryContextDelete(prodesc->fn_cxt);
    2713           28 : }
    2714              : 
    2715              : 
    2716              : static plperl_proc_desc *
    2717          426 : compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
    2718              : {
    2719              :     HeapTuple   procTup;
    2720              :     Form_pg_proc procStruct;
    2721              :     plperl_proc_key proc_key;
    2722              :     plperl_proc_ptr *proc_ptr;
    2723          426 :     plperl_proc_desc *volatile prodesc = NULL;
    2724          426 :     volatile MemoryContext proc_cxt = NULL;
    2725          426 :     plperl_interp_desc *oldinterp = plperl_active_interp;
    2726              :     ErrorContextCallback plperl_error_context;
    2727              : 
    2728              :     /* We'll need the pg_proc tuple in any case... */
    2729          426 :     procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
    2730          426 :     if (!HeapTupleIsValid(procTup))
    2731            0 :         elog(ERROR, "cache lookup failed for function %u", fn_oid);
    2732          426 :     procStruct = (Form_pg_proc) GETSTRUCT(procTup);
    2733              : 
    2734              :     /*
    2735              :      * Try to find function in plperl_proc_hash.  The reason for this
    2736              :      * overcomplicated-seeming lookup procedure is that we don't know whether
    2737              :      * it's plperl or plperlu, and don't want to spend a lookup in pg_language
    2738              :      * to find out.
    2739              :      */
    2740          426 :     proc_key.proc_id = fn_oid;
    2741          426 :     proc_key.is_trigger = is_trigger;
    2742          426 :     proc_key.user_id = GetUserId();
    2743          426 :     proc_ptr = hash_search(plperl_proc_hash, &proc_key,
    2744              :                            HASH_FIND, NULL);
    2745          426 :     if (validate_plperl_function(proc_ptr, procTup))
    2746              :     {
    2747              :         /* Found valid plperl entry */
    2748          223 :         ReleaseSysCache(procTup);
    2749          223 :         return proc_ptr->proc_ptr;
    2750              :     }
    2751              : 
    2752              :     /* If not found or obsolete, maybe it's plperlu */
    2753          203 :     proc_key.user_id = InvalidOid;
    2754          203 :     proc_ptr = hash_search(plperl_proc_hash, &proc_key,
    2755              :                            HASH_FIND, NULL);
    2756          203 :     if (validate_plperl_function(proc_ptr, procTup))
    2757              :     {
    2758              :         /* Found valid plperlu entry */
    2759           50 :         ReleaseSysCache(procTup);
    2760           50 :         return proc_ptr->proc_ptr;
    2761              :     }
    2762              : 
    2763              :     /************************************************************
    2764              :      * If we haven't found it in the hashtable, we analyze
    2765              :      * the function's arguments and return type and store
    2766              :      * the in-/out-functions in the prodesc block,
    2767              :      * then we load the procedure into the Perl interpreter,
    2768              :      * and last we create a new hashtable entry for it.
    2769              :      ************************************************************/
    2770              : 
    2771              :     /* Set a callback for reporting compilation errors */
    2772          153 :     plperl_error_context.callback = plperl_compile_callback;
    2773          153 :     plperl_error_context.previous = error_context_stack;
    2774          153 :     plperl_error_context.arg = NameStr(procStruct->proname);
    2775          153 :     error_context_stack = &plperl_error_context;
    2776              : 
    2777          153 :     PG_TRY();
    2778              :     {
    2779              :         HeapTuple   langTup;
    2780              :         HeapTuple   typeTup;
    2781              :         Form_pg_language langStruct;
    2782              :         Form_pg_type typeStruct;
    2783              :         Datum       protrftypes_datum;
    2784              :         Datum       prosrcdatum;
    2785              :         bool        isnull;
    2786              :         char       *proc_source;
    2787              :         MemoryContext oldcontext;
    2788              : 
    2789              :         /************************************************************
    2790              :          * Allocate a context that will hold all PG data for the procedure.
    2791              :          ************************************************************/
    2792          153 :         proc_cxt = AllocSetContextCreate(TopMemoryContext,
    2793              :                                          "PL/Perl function",
    2794              :                                          ALLOCSET_SMALL_SIZES);
    2795              : 
    2796              :         /************************************************************
    2797              :          * Allocate and fill a new procedure description block.
    2798              :          * struct prodesc and subsidiary data must all live in proc_cxt.
    2799              :          ************************************************************/
    2800          153 :         oldcontext = MemoryContextSwitchTo(proc_cxt);
    2801          153 :         prodesc = palloc0_object(plperl_proc_desc);
    2802          153 :         prodesc->proname = pstrdup(NameStr(procStruct->proname));
    2803          153 :         MemoryContextSetIdentifier(proc_cxt, prodesc->proname);
    2804          153 :         prodesc->fn_cxt = proc_cxt;
    2805          153 :         prodesc->fn_refcount = 0;
    2806          153 :         prodesc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
    2807          153 :         prodesc->fn_tid = procTup->t_self;
    2808          153 :         prodesc->nargs = procStruct->pronargs;
    2809          153 :         prodesc->arg_out_func = (FmgrInfo *) palloc0(prodesc->nargs * sizeof(FmgrInfo));
    2810          153 :         prodesc->arg_is_rowtype = (bool *) palloc0(prodesc->nargs * sizeof(bool));
    2811          153 :         prodesc->arg_arraytype = (Oid *) palloc0(prodesc->nargs * sizeof(Oid));
    2812          153 :         MemoryContextSwitchTo(oldcontext);
    2813              : 
    2814              :         /* Remember if function is STABLE/IMMUTABLE */
    2815          153 :         prodesc->fn_readonly =
    2816          153 :             (procStruct->provolatile != PROVOLATILE_VOLATILE);
    2817              : 
    2818              :         /* Fetch protrftypes */
    2819          153 :         protrftypes_datum = SysCacheGetAttr(PROCOID, procTup,
    2820              :                                             Anum_pg_proc_protrftypes, &isnull);
    2821          153 :         MemoryContextSwitchTo(proc_cxt);
    2822          153 :         prodesc->trftypes = isnull ? NIL : oid_array_to_list(protrftypes_datum);
    2823          153 :         MemoryContextSwitchTo(oldcontext);
    2824              : 
    2825              :         /************************************************************
    2826              :          * Lookup the pg_language tuple by Oid
    2827              :          ************************************************************/
    2828          153 :         langTup = SearchSysCache1(LANGOID,
    2829              :                                   ObjectIdGetDatum(procStruct->prolang));
    2830          153 :         if (!HeapTupleIsValid(langTup))
    2831            0 :             elog(ERROR, "cache lookup failed for language %u",
    2832              :                  procStruct->prolang);
    2833          153 :         langStruct = (Form_pg_language) GETSTRUCT(langTup);
    2834          153 :         prodesc->lang_oid = langStruct->oid;
    2835          153 :         prodesc->lanpltrusted = langStruct->lanpltrusted;
    2836          153 :         ReleaseSysCache(langTup);
    2837              : 
    2838              :         /************************************************************
    2839              :          * Get the required information for input conversion of the
    2840              :          * return value.
    2841              :          ************************************************************/
    2842          153 :         if (!is_trigger && !is_event_trigger)
    2843              :         {
    2844          144 :             Oid         rettype = procStruct->prorettype;
    2845              : 
    2846          144 :             typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettype));
    2847          144 :             if (!HeapTupleIsValid(typeTup))
    2848            0 :                 elog(ERROR, "cache lookup failed for type %u", rettype);
    2849          144 :             typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
    2850              : 
    2851              :             /* Disallow pseudotype result, except VOID or RECORD */
    2852          144 :             if (typeStruct->typtype == TYPTYPE_PSEUDO)
    2853              :             {
    2854           30 :                 if (rettype == VOIDOID ||
    2855              :                     rettype == RECORDOID)
    2856              :                      /* okay */ ;
    2857            1 :                 else if (rettype == TRIGGEROID ||
    2858              :                          rettype == EVENT_TRIGGEROID)
    2859            1 :                     ereport(ERROR,
    2860              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2861              :                              errmsg("trigger functions can only be called "
    2862              :                                     "as triggers")));
    2863              :                 else
    2864            0 :                     ereport(ERROR,
    2865              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2866              :                              errmsg("PL/Perl functions cannot return type %s",
    2867              :                                     format_type_be(rettype))));
    2868              :             }
    2869              : 
    2870          143 :             prodesc->result_oid = rettype;
    2871          143 :             prodesc->fn_retisset = procStruct->proretset;
    2872          143 :             prodesc->fn_retistuple = type_is_rowtype(rettype);
    2873          143 :             prodesc->fn_retisarray = IsTrueArrayType(typeStruct);
    2874              : 
    2875          143 :             fmgr_info_cxt(typeStruct->typinput,
    2876          143 :                           &(prodesc->result_in_func),
    2877              :                           proc_cxt);
    2878          143 :             prodesc->result_typioparam = getTypeIOParam(typeTup);
    2879              : 
    2880          143 :             ReleaseSysCache(typeTup);
    2881              :         }
    2882              : 
    2883              :         /************************************************************
    2884              :          * Get the required information for output conversion
    2885              :          * of all procedure arguments
    2886              :          ************************************************************/
    2887          152 :         if (!is_trigger && !is_event_trigger)
    2888              :         {
    2889              :             int         i;
    2890              : 
    2891          208 :             for (i = 0; i < prodesc->nargs; i++)
    2892              :             {
    2893           65 :                 Oid         argtype = procStruct->proargtypes.values[i];
    2894              : 
    2895           65 :                 typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype));
    2896           65 :                 if (!HeapTupleIsValid(typeTup))
    2897            0 :                     elog(ERROR, "cache lookup failed for type %u", argtype);
    2898           65 :                 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
    2899              : 
    2900              :                 /* Disallow pseudotype argument, except RECORD */
    2901           65 :                 if (typeStruct->typtype == TYPTYPE_PSEUDO &&
    2902              :                     argtype != RECORDOID)
    2903            0 :                     ereport(ERROR,
    2904              :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2905              :                              errmsg("PL/Perl functions cannot accept type %s",
    2906              :                                     format_type_be(argtype))));
    2907              : 
    2908           65 :                 if (type_is_rowtype(argtype))
    2909            6 :                     prodesc->arg_is_rowtype[i] = true;
    2910              :                 else
    2911              :                 {
    2912           59 :                     prodesc->arg_is_rowtype[i] = false;
    2913           59 :                     fmgr_info_cxt(typeStruct->typoutput,
    2914           59 :                                   &(prodesc->arg_out_func[i]),
    2915              :                                   proc_cxt);
    2916              :                 }
    2917              : 
    2918              :                 /* Identify array-type arguments */
    2919           65 :                 if (IsTrueArrayType(typeStruct))
    2920            7 :                     prodesc->arg_arraytype[i] = argtype;
    2921              :                 else
    2922           58 :                     prodesc->arg_arraytype[i] = InvalidOid;
    2923              : 
    2924           65 :                 ReleaseSysCache(typeTup);
    2925              :             }
    2926              :         }
    2927              : 
    2928              :         /************************************************************
    2929              :          * create the text of the anonymous subroutine.
    2930              :          * we do not use a named subroutine so that we can call directly
    2931              :          * through the reference.
    2932              :          ************************************************************/
    2933          152 :         prosrcdatum = SysCacheGetAttrNotNull(PROCOID, procTup,
    2934              :                                              Anum_pg_proc_prosrc);
    2935          152 :         proc_source = TextDatumGetCString(prosrcdatum);
    2936              : 
    2937              :         /************************************************************
    2938              :          * Create the procedure in the appropriate interpreter
    2939              :          ************************************************************/
    2940              : 
    2941          152 :         select_perl_context(prodesc->lanpltrusted);
    2942              : 
    2943          152 :         prodesc->interp = plperl_active_interp;
    2944              : 
    2945          152 :         plperl_create_sub(prodesc, proc_source, fn_oid);
    2946              : 
    2947          149 :         activate_interpreter(oldinterp);
    2948              : 
    2949          149 :         pfree(proc_source);
    2950              : 
    2951          149 :         if (!prodesc->reference) /* can this happen? */
    2952            0 :             elog(ERROR, "could not create PL/Perl internal procedure");
    2953              : 
    2954              :         /************************************************************
    2955              :          * OK, link the procedure into the correct hashtable entry.
    2956              :          * Note we assume that the hashtable entry either doesn't exist yet,
    2957              :          * or we already cleared its proc_ptr during the validation attempts
    2958              :          * above.  So no need to decrement an old refcount here.
    2959              :          ************************************************************/
    2960          149 :         proc_key.user_id = prodesc->lanpltrusted ? GetUserId() : InvalidOid;
    2961              : 
    2962          149 :         proc_ptr = hash_search(plperl_proc_hash, &proc_key,
    2963              :                                HASH_ENTER, NULL);
    2964              :         /* We assume these two steps can't throw an error: */
    2965          149 :         proc_ptr->proc_ptr = prodesc;
    2966          149 :         increment_prodesc_refcount(prodesc);
    2967              :     }
    2968            4 :     PG_CATCH();
    2969              :     {
    2970              :         /*
    2971              :          * If we got as far as creating a reference, we should be able to use
    2972              :          * free_plperl_function() to clean up.  If not, then at most we have
    2973              :          * some PG memory resources in proc_cxt, which we can just delete.
    2974              :          */
    2975            4 :         if (prodesc && prodesc->reference)
    2976            0 :             free_plperl_function(prodesc);
    2977            4 :         else if (proc_cxt)
    2978            4 :             MemoryContextDelete(proc_cxt);
    2979              : 
    2980              :         /* Be sure to restore the previous interpreter, too, for luck */
    2981            4 :         activate_interpreter(oldinterp);
    2982              : 
    2983            4 :         PG_RE_THROW();
    2984              :     }
    2985          149 :     PG_END_TRY();
    2986              : 
    2987              :     /* restore previous error callback */
    2988          149 :     error_context_stack = plperl_error_context.previous;
    2989              : 
    2990          149 :     ReleaseSysCache(procTup);
    2991              : 
    2992          149 :     return prodesc;
    2993              : }
    2994              : 
    2995              : /* Build a hash from a given composite/row datum */
    2996              : static SV  *
    2997           57 : plperl_hash_from_datum(Datum attr)
    2998              : {
    2999              :     HeapTupleHeader td;
    3000              :     Oid         tupType;
    3001              :     int32       tupTypmod;
    3002              :     TupleDesc   tupdesc;
    3003              :     HeapTupleData tmptup;
    3004              :     SV         *sv;
    3005              : 
    3006           57 :     td = DatumGetHeapTupleHeader(attr);
    3007              : 
    3008              :     /* Extract rowtype info and find a tupdesc */
    3009           57 :     tupType = HeapTupleHeaderGetTypeId(td);
    3010           57 :     tupTypmod = HeapTupleHeaderGetTypMod(td);
    3011           57 :     tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
    3012              : 
    3013              :     /* Build a temporary HeapTuple control structure */
    3014           57 :     tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
    3015           57 :     tmptup.t_data = td;
    3016              : 
    3017           57 :     sv = plperl_hash_from_tuple(&tmptup, tupdesc, true);
    3018           57 :     ReleaseTupleDesc(tupdesc);
    3019              : 
    3020           57 :     return sv;
    3021              : }
    3022              : 
    3023              : /* Build a hash from all attributes of a given tuple. */
    3024              : static SV  *
    3025          192 : plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
    3026              : {
    3027          192 :     dTHX;
    3028              :     HV         *hv;
    3029              :     int         i;
    3030              : 
    3031              :     /* since this function recurses, it could be driven to stack overflow */
    3032          192 :     check_stack_depth();
    3033              : 
    3034          192 :     hv = newHV();
    3035          192 :     hv_ksplit(hv, tupdesc->natts);   /* pre-grow the hash */
    3036              : 
    3037          476 :     for (i = 0; i < tupdesc->natts; i++)
    3038              :     {
    3039              :         Datum       attr;
    3040              :         bool        isnull,
    3041              :                     typisvarlena;
    3042              :         char       *attname;
    3043              :         Oid         typoutput;
    3044          284 :         Form_pg_attribute att = TupleDescAttr(tupdesc, i);
    3045              : 
    3046          284 :         if (att->attisdropped)
    3047           19 :             continue;
    3048              : 
    3049          284 :         if (att->attgenerated)
    3050              :         {
    3051              :             /* don't include unless requested */
    3052           18 :             if (!include_generated)
    3053            6 :                 continue;
    3054              :             /* never include virtual columns */
    3055           12 :             if (att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
    3056            6 :                 continue;
    3057              :         }
    3058              : 
    3059          272 :         attname = NameStr(att->attname);
    3060          272 :         attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
    3061              : 
    3062          272 :         if (isnull)
    3063              :         {
    3064              :             /*
    3065              :              * Store (attname => undef) and move on.  Note we can't use
    3066              :              * &PL_sv_undef here; see "AVs, HVs and undefined values" in
    3067              :              * perlguts for an explanation.
    3068              :              */
    3069            7 :             hv_store_string(hv, attname, newSV(0));
    3070            7 :             continue;
    3071              :         }
    3072              : 
    3073          265 :         if (type_is_rowtype(att->atttypid))
    3074              :         {
    3075           42 :             SV         *sv = plperl_hash_from_datum(attr);
    3076              : 
    3077           42 :             hv_store_string(hv, attname, sv);
    3078              :         }
    3079              :         else
    3080              :         {
    3081              :             SV         *sv;
    3082              :             Oid         funcid;
    3083              : 
    3084          223 :             if (OidIsValid(get_base_element_type(att->atttypid)))
    3085            4 :                 sv = plperl_ref_from_pg_array(attr, att->atttypid);
    3086          219 :             else if ((funcid = get_transform_fromsql(att->atttypid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
    3087            7 :                 sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, attr));
    3088              :             else
    3089              :             {
    3090              :                 char       *outputstr;
    3091              : 
    3092              :                 /* XXX should have a way to cache these lookups */
    3093          212 :                 getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
    3094              : 
    3095          212 :                 outputstr = OidOutputFunctionCall(typoutput, attr);
    3096          212 :                 sv = cstr2sv(outputstr);
    3097          212 :                 pfree(outputstr);
    3098              :             }
    3099              : 
    3100          223 :             hv_store_string(hv, attname, sv);
    3101              :         }
    3102              :     }
    3103          192 :     return newRV_noinc((SV *) hv);
    3104              : }
    3105              : 
    3106              : 
    3107              : static void
    3108          326 : check_spi_usage_allowed(void)
    3109              : {
    3110              :     /* see comment in plperl_fini() */
    3111          326 :     if (plperl_ending)
    3112              :     {
    3113              :         /* simple croak as we don't want to involve PostgreSQL code */
    3114            0 :         croak("SPI functions can not be used in END blocks");
    3115              :     }
    3116              : 
    3117              :     /*
    3118              :      * Disallow SPI usage if we're not executing a fully-compiled plperl
    3119              :      * function.  It might seem impossible to get here in that case, but there
    3120              :      * are cases where Perl will try to execute code during compilation.  If
    3121              :      * we proceed we are likely to crash trying to dereference the prodesc
    3122              :      * pointer.  Working around that might be possible, but it seems unwise
    3123              :      * because it'd allow code execution to happen while validating a
    3124              :      * function, which is undesirable.
    3125              :      */
    3126          326 :     if (current_call_data == NULL || current_call_data->prodesc == NULL)
    3127              :     {
    3128              :         /* simple croak as we don't want to involve PostgreSQL code */
    3129            0 :         croak("SPI functions can not be used during function compilation");
    3130              :     }
    3131          326 : }
    3132              : 
    3133              : 
    3134              : HV *
    3135           57 : plperl_spi_exec(char *query, int limit)
    3136              : {
    3137              :     HV         *ret_hv;
    3138              : 
    3139              :     /*
    3140              :      * Execute the query inside a sub-transaction, so we can cope with errors
    3141              :      * sanely
    3142              :      */
    3143           57 :     MemoryContext oldcontext = CurrentMemoryContext;
    3144           57 :     ResourceOwner oldowner = CurrentResourceOwner;
    3145              : 
    3146           57 :     check_spi_usage_allowed();
    3147              : 
    3148           57 :     BeginInternalSubTransaction(NULL);
    3149              :     /* Want to run inside function's memory context */
    3150           57 :     MemoryContextSwitchTo(oldcontext);
    3151              : 
    3152           57 :     PG_TRY();
    3153              :     {
    3154              :         int         spi_rv;
    3155              : 
    3156           57 :         pg_verifymbstr(query, strlen(query), false);
    3157              : 
    3158           57 :         spi_rv = SPI_execute(query, current_call_data->prodesc->fn_readonly,
    3159              :                              limit);
    3160           51 :         ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
    3161              :                                                  spi_rv);
    3162              : 
    3163              :         /* Commit the inner transaction, return to outer xact context */
    3164           51 :         ReleaseCurrentSubTransaction();
    3165           51 :         MemoryContextSwitchTo(oldcontext);
    3166           51 :         CurrentResourceOwner = oldowner;
    3167              :     }
    3168            6 :     PG_CATCH();
    3169              :     {
    3170              :         ErrorData  *edata;
    3171              : 
    3172              :         /* Save error info */
    3173            6 :         MemoryContextSwitchTo(oldcontext);
    3174            6 :         edata = CopyErrorData();
    3175            6 :         FlushErrorState();
    3176              : 
    3177              :         /* Abort the inner transaction */
    3178            6 :         RollbackAndReleaseCurrentSubTransaction();
    3179            6 :         MemoryContextSwitchTo(oldcontext);
    3180            6 :         CurrentResourceOwner = oldowner;
    3181              : 
    3182              :         /* Punt the error to Perl */
    3183            6 :         croak_cstr(edata->message);
    3184              : 
    3185              :         /* Can't get here, but keep compiler quiet */
    3186            0 :         return NULL;
    3187              :     }
    3188           51 :     PG_END_TRY();
    3189              : 
    3190           51 :     return ret_hv;
    3191              : }
    3192              : 
    3193              : 
    3194              : static HV  *
    3195           57 : plperl_spi_execute_fetch_result(SPITupleTable *tuptable, uint64 processed,
    3196              :                                 int status)
    3197              : {
    3198           57 :     dTHX;
    3199              :     HV         *result;
    3200              : 
    3201           57 :     check_spi_usage_allowed();
    3202              : 
    3203           57 :     result = newHV();
    3204              : 
    3205           57 :     hv_store_string(result, "status",
    3206              :                     cstr2sv(SPI_result_code_string(status)));
    3207           57 :     hv_store_string(result, "processed",
    3208              :                     (processed > (uint64) UV_MAX) ?
    3209              :                     newSVnv((NV) processed) :
    3210              :                     newSVuv((UV) processed));
    3211              : 
    3212           57 :     if (status > 0 && tuptable)
    3213              :     {
    3214              :         AV         *rows;
    3215              :         SV         *row;
    3216              :         uint64      i;
    3217              : 
    3218              :         /* Prevent overflow in call to av_extend() */
    3219           11 :         if (processed > (uint64) AV_SIZE_MAX)
    3220            0 :             ereport(ERROR,
    3221              :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    3222              :                      errmsg("query result has too many rows to fit in a Perl array")));
    3223              : 
    3224           11 :         rows = newAV();
    3225           11 :         av_extend(rows, processed);
    3226           83 :         for (i = 0; i < processed; i++)
    3227              :         {
    3228           72 :             row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc, true);
    3229           72 :             av_push(rows, row);
    3230              :         }
    3231           11 :         hv_store_string(result, "rows",
    3232              :                         newRV_noinc((SV *) rows));
    3233              :     }
    3234              : 
    3235           57 :     SPI_freetuptable(tuptable);
    3236              : 
    3237           57 :     return result;
    3238              : }
    3239              : 
    3240              : 
    3241              : /*
    3242              :  * plperl_return_next catches any error and converts it to a Perl error.
    3243              :  * We assume (perhaps without adequate justification) that we need not abort
    3244              :  * the current transaction if the Perl code traps the error.
    3245              :  */
    3246              : void
    3247           87 : plperl_return_next(SV *sv)
    3248              : {
    3249           87 :     MemoryContext oldcontext = CurrentMemoryContext;
    3250              : 
    3251           87 :     check_spi_usage_allowed();
    3252              : 
    3253           87 :     PG_TRY();
    3254              :     {
    3255           87 :         plperl_return_next_internal(sv);
    3256              :     }
    3257            0 :     PG_CATCH();
    3258              :     {
    3259              :         ErrorData  *edata;
    3260              : 
    3261              :         /* Must reset elog.c's state */
    3262            0 :         MemoryContextSwitchTo(oldcontext);
    3263            0 :         edata = CopyErrorData();
    3264            0 :         FlushErrorState();
    3265              : 
    3266              :         /* Punt the error to Perl */
    3267            0 :         croak_cstr(edata->message);
    3268              :     }
    3269           87 :     PG_END_TRY();
    3270           87 : }
    3271              : 
    3272              : /*
    3273              :  * plperl_return_next_internal reports any errors in Postgres fashion
    3274              :  * (via ereport).
    3275              :  */
    3276              : static void
    3277          141 : plperl_return_next_internal(SV *sv)
    3278              : {
    3279              :     plperl_proc_desc *prodesc;
    3280              :     FunctionCallInfo fcinfo;
    3281              :     ReturnSetInfo *rsi;
    3282              :     MemoryContext old_cxt;
    3283              : 
    3284          141 :     if (!sv)
    3285            0 :         return;
    3286              : 
    3287          141 :     prodesc = current_call_data->prodesc;
    3288          141 :     fcinfo = current_call_data->fcinfo;
    3289          141 :     rsi = (ReturnSetInfo *) fcinfo->resultinfo;
    3290              : 
    3291          141 :     if (!prodesc->fn_retisset)
    3292            0 :         ereport(ERROR,
    3293              :                 (errcode(ERRCODE_SYNTAX_ERROR),
    3294              :                  errmsg("cannot use return_next in a non-SETOF function")));
    3295              : 
    3296          141 :     if (!current_call_data->ret_tdesc)
    3297              :     {
    3298              :         TupleDesc   tupdesc;
    3299              : 
    3300              :         Assert(!current_call_data->tuple_store);
    3301              : 
    3302              :         /*
    3303              :          * This is the first call to return_next in the current PL/Perl
    3304              :          * function call, so identify the output tuple type and create a
    3305              :          * tuplestore to hold the result rows.
    3306              :          */
    3307           34 :         if (prodesc->fn_retistuple)
    3308              :         {
    3309              :             TypeFuncClass funcclass;
    3310              :             Oid         typid;
    3311              : 
    3312           17 :             funcclass = get_call_result_type(fcinfo, &typid, &tupdesc);
    3313           17 :             if (funcclass != TYPEFUNC_COMPOSITE &&
    3314              :                 funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
    3315            2 :                 ereport(ERROR,
    3316              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3317              :                          errmsg("function returning record called in context "
    3318              :                                 "that cannot accept type record")));
    3319              :             /* if domain-over-composite, remember the domain's type OID */
    3320           15 :             if (funcclass == TYPEFUNC_COMPOSITE_DOMAIN)
    3321            2 :                 current_call_data->cdomain_oid = typid;
    3322              :         }
    3323              :         else
    3324              :         {
    3325           17 :             tupdesc = rsi->expectedDesc;
    3326              :             /* Protect assumption below that we return exactly one column */
    3327           17 :             if (tupdesc == NULL || tupdesc->natts != 1)
    3328            0 :                 elog(ERROR, "expected single-column result descriptor for non-composite SETOF result");
    3329              :         }
    3330              : 
    3331              :         /*
    3332              :          * Make sure the tuple_store and ret_tdesc are sufficiently
    3333              :          * long-lived.
    3334              :          */
    3335           32 :         old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
    3336              : 
    3337           32 :         current_call_data->ret_tdesc = CreateTupleDescCopy(tupdesc);
    3338           64 :         current_call_data->tuple_store =
    3339           32 :             tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
    3340              :                                   false, work_mem);
    3341              : 
    3342           32 :         MemoryContextSwitchTo(old_cxt);
    3343              :     }
    3344              : 
    3345              :     /*
    3346              :      * Producing the tuple we want to return requires making plenty of
    3347              :      * palloc() allocations that are not cleaned up. Since this function can
    3348              :      * be called many times before the current memory context is reset, we
    3349              :      * need to do those allocations in a temporary context.
    3350              :      */
    3351          139 :     if (!current_call_data->tmp_cxt)
    3352              :     {
    3353           32 :         current_call_data->tmp_cxt =
    3354           32 :             AllocSetContextCreate(CurrentMemoryContext,
    3355              :                                   "PL/Perl return_next temporary cxt",
    3356              :                                   ALLOCSET_DEFAULT_SIZES);
    3357              :     }
    3358              : 
    3359          139 :     old_cxt = MemoryContextSwitchTo(current_call_data->tmp_cxt);
    3360              : 
    3361          139 :     if (prodesc->fn_retistuple)
    3362              :     {
    3363              :         HeapTuple   tuple;
    3364              : 
    3365           43 :         if (!(SvOK(sv) && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV))
    3366            4 :             ereport(ERROR,
    3367              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3368              :                      errmsg("SETOF-composite-returning PL/Perl function "
    3369              :                             "must call return_next with reference to hash")));
    3370              : 
    3371           39 :         tuple = plperl_build_tuple_result((HV *) SvRV(sv),
    3372           39 :                                           current_call_data->ret_tdesc);
    3373              : 
    3374           38 :         if (OidIsValid(current_call_data->cdomain_oid))
    3375            4 :             domain_check(HeapTupleGetDatum(tuple), false,
    3376            4 :                          current_call_data->cdomain_oid,
    3377            4 :                          &current_call_data->cdomain_info,
    3378            4 :                          rsi->econtext->ecxt_per_query_memory);
    3379              : 
    3380           37 :         tuplestore_puttuple(current_call_data->tuple_store, tuple);
    3381              :     }
    3382           96 :     else if (prodesc->result_oid)
    3383              :     {
    3384              :         Datum       ret[1];
    3385              :         bool        isNull[1];
    3386              : 
    3387           96 :         ret[0] = plperl_sv_to_datum(sv,
    3388              :                                     prodesc->result_oid,
    3389              :                                     -1,
    3390              :                                     fcinfo,
    3391              :                                     &prodesc->result_in_func,
    3392              :                                     prodesc->result_typioparam,
    3393              :                                     &isNull[0]);
    3394              : 
    3395           96 :         tuplestore_putvalues(current_call_data->tuple_store,
    3396           96 :                              current_call_data->ret_tdesc,
    3397              :                              ret, isNull);
    3398              :     }
    3399              : 
    3400          133 :     MemoryContextSwitchTo(old_cxt);
    3401          133 :     MemoryContextReset(current_call_data->tmp_cxt);
    3402              : }
    3403              : 
    3404              : 
    3405              : SV *
    3406            9 : plperl_spi_query(char *query)
    3407              : {
    3408              :     SV         *cursor;
    3409              : 
    3410              :     /*
    3411              :      * Execute the query inside a sub-transaction, so we can cope with errors
    3412              :      * sanely
    3413              :      */
    3414            9 :     MemoryContext oldcontext = CurrentMemoryContext;
    3415            9 :     ResourceOwner oldowner = CurrentResourceOwner;
    3416              : 
    3417            9 :     check_spi_usage_allowed();
    3418              : 
    3419            9 :     BeginInternalSubTransaction(NULL);
    3420              :     /* Want to run inside function's memory context */
    3421            9 :     MemoryContextSwitchTo(oldcontext);
    3422              : 
    3423            9 :     PG_TRY();
    3424              :     {
    3425              :         SPIPlanPtr  plan;
    3426              :         Portal      portal;
    3427              : 
    3428              :         /* Make sure the query is validly encoded */
    3429            9 :         pg_verifymbstr(query, strlen(query), false);
    3430              : 
    3431              :         /* Create a cursor for the query */
    3432            9 :         plan = SPI_prepare(query, 0, NULL);
    3433            9 :         if (plan == NULL)
    3434            0 :             elog(ERROR, "SPI_prepare() failed:%s",
    3435              :                  SPI_result_code_string(SPI_result));
    3436              : 
    3437            9 :         portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
    3438            9 :         SPI_freeplan(plan);
    3439            9 :         if (portal == NULL)
    3440            0 :             elog(ERROR, "SPI_cursor_open() failed:%s",
    3441              :                  SPI_result_code_string(SPI_result));
    3442            9 :         cursor = cstr2sv(portal->name);
    3443              : 
    3444            9 :         PinPortal(portal);
    3445              : 
    3446              :         /* Commit the inner transaction, return to outer xact context */
    3447            9 :         ReleaseCurrentSubTransaction();
    3448            9 :         MemoryContextSwitchTo(oldcontext);
    3449            9 :         CurrentResourceOwner = oldowner;
    3450              :     }
    3451            0 :     PG_CATCH();
    3452              :     {
    3453              :         ErrorData  *edata;
    3454              : 
    3455              :         /* Save error info */
    3456            0 :         MemoryContextSwitchTo(oldcontext);
    3457            0 :         edata = CopyErrorData();
    3458            0 :         FlushErrorState();
    3459              : 
    3460              :         /* Abort the inner transaction */
    3461            0 :         RollbackAndReleaseCurrentSubTransaction();
    3462            0 :         MemoryContextSwitchTo(oldcontext);
    3463            0 :         CurrentResourceOwner = oldowner;
    3464              : 
    3465              :         /* Punt the error to Perl */
    3466            0 :         croak_cstr(edata->message);
    3467              : 
    3468              :         /* Can't get here, but keep compiler quiet */
    3469            0 :         return NULL;
    3470              :     }
    3471            9 :     PG_END_TRY();
    3472              : 
    3473            9 :     return cursor;
    3474              : }
    3475              : 
    3476              : 
    3477              : SV *
    3478           36 : plperl_spi_fetchrow(char *cursor)
    3479              : {
    3480              :     SV         *row;
    3481              : 
    3482              :     /*
    3483              :      * Execute the FETCH inside a sub-transaction, so we can cope with errors
    3484              :      * sanely
    3485              :      */
    3486           36 :     MemoryContext oldcontext = CurrentMemoryContext;
    3487           36 :     ResourceOwner oldowner = CurrentResourceOwner;
    3488              : 
    3489           36 :     check_spi_usage_allowed();
    3490              : 
    3491           36 :     BeginInternalSubTransaction(NULL);
    3492              :     /* Want to run inside function's memory context */
    3493           36 :     MemoryContextSwitchTo(oldcontext);
    3494              : 
    3495           36 :     PG_TRY();
    3496              :     {
    3497           36 :         dTHX;
    3498           36 :         Portal      p = SPI_cursor_find(cursor);
    3499              : 
    3500           36 :         if (!p)
    3501              :         {
    3502            0 :             row = &PL_sv_undef;
    3503              :         }
    3504              :         else
    3505              :         {
    3506           36 :             SPI_cursor_fetch(p, true, 1);
    3507           36 :             if (SPI_processed == 0)
    3508              :             {
    3509            9 :                 UnpinPortal(p);
    3510            9 :                 SPI_cursor_close(p);
    3511            9 :                 row = &PL_sv_undef;
    3512              :             }
    3513              :             else
    3514              :             {
    3515           27 :                 row = plperl_hash_from_tuple(SPI_tuptable->vals[0],
    3516           27 :                                              SPI_tuptable->tupdesc,
    3517              :                                              true);
    3518              :             }
    3519           36 :             SPI_freetuptable(SPI_tuptable);
    3520              :         }
    3521              : 
    3522              :         /* Commit the inner transaction, return to outer xact context */
    3523           36 :         ReleaseCurrentSubTransaction();
    3524           36 :         MemoryContextSwitchTo(oldcontext);
    3525           36 :         CurrentResourceOwner = oldowner;
    3526              :     }
    3527            0 :     PG_CATCH();
    3528              :     {
    3529              :         ErrorData  *edata;
    3530              : 
    3531              :         /* Save error info */
    3532            0 :         MemoryContextSwitchTo(oldcontext);
    3533            0 :         edata = CopyErrorData();
    3534            0 :         FlushErrorState();
    3535              : 
    3536              :         /* Abort the inner transaction */
    3537            0 :         RollbackAndReleaseCurrentSubTransaction();
    3538            0 :         MemoryContextSwitchTo(oldcontext);
    3539            0 :         CurrentResourceOwner = oldowner;
    3540              : 
    3541              :         /* Punt the error to Perl */
    3542            0 :         croak_cstr(edata->message);
    3543              : 
    3544              :         /* Can't get here, but keep compiler quiet */
    3545            0 :         return NULL;
    3546              :     }
    3547           36 :     PG_END_TRY();
    3548              : 
    3549           36 :     return row;
    3550              : }
    3551              : 
    3552              : void
    3553            1 : plperl_spi_cursor_close(char *cursor)
    3554              : {
    3555              :     Portal      p;
    3556              : 
    3557            1 :     check_spi_usage_allowed();
    3558              : 
    3559            1 :     p = SPI_cursor_find(cursor);
    3560              : 
    3561            1 :     if (p)
    3562              :     {
    3563            1 :         UnpinPortal(p);
    3564            1 :         SPI_cursor_close(p);
    3565              :     }
    3566            1 : }
    3567              : 
    3568              : SV *
    3569            8 : plperl_spi_prepare(char *query, int argc, SV **argv)
    3570              : {
    3571            8 :     volatile SPIPlanPtr plan = NULL;
    3572            8 :     volatile MemoryContext plan_cxt = NULL;
    3573            8 :     plperl_query_desc *volatile qdesc = NULL;
    3574            8 :     plperl_query_entry *volatile hash_entry = NULL;
    3575            8 :     MemoryContext oldcontext = CurrentMemoryContext;
    3576            8 :     ResourceOwner oldowner = CurrentResourceOwner;
    3577              :     MemoryContext work_cxt;
    3578              :     bool        found;
    3579              :     int         i;
    3580              : 
    3581            8 :     check_spi_usage_allowed();
    3582              : 
    3583            8 :     BeginInternalSubTransaction(NULL);
    3584            8 :     MemoryContextSwitchTo(oldcontext);
    3585              : 
    3586            8 :     PG_TRY();
    3587              :     {
    3588            8 :         CHECK_FOR_INTERRUPTS();
    3589              : 
    3590              :         /************************************************************
    3591              :          * Allocate the new querydesc structure
    3592              :          *
    3593              :          * The qdesc struct, as well as all its subsidiary data, lives in its
    3594              :          * plan_cxt.  But note that the SPIPlan does not.
    3595              :          ************************************************************/
    3596            8 :         plan_cxt = AllocSetContextCreate(TopMemoryContext,
    3597              :                                          "PL/Perl spi_prepare query",
    3598              :                                          ALLOCSET_SMALL_SIZES);
    3599            8 :         MemoryContextSwitchTo(plan_cxt);
    3600            8 :         qdesc = palloc0_object(plperl_query_desc);
    3601            8 :         snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
    3602            8 :         qdesc->plan_cxt = plan_cxt;
    3603            8 :         qdesc->nargs = argc;
    3604            8 :         qdesc->argtypes = (Oid *) palloc(argc * sizeof(Oid));
    3605            8 :         qdesc->arginfuncs = (FmgrInfo *) palloc(argc * sizeof(FmgrInfo));
    3606            8 :         qdesc->argtypioparams = (Oid *) palloc(argc * sizeof(Oid));
    3607            8 :         MemoryContextSwitchTo(oldcontext);
    3608              : 
    3609              :         /************************************************************
    3610              :          * Do the following work in a short-lived context so that we don't
    3611              :          * leak a lot of memory in the PL/Perl function's SPI Proc context.
    3612              :          ************************************************************/
    3613            8 :         work_cxt = AllocSetContextCreate(CurrentMemoryContext,
    3614              :                                          "PL/Perl spi_prepare workspace",
    3615              :                                          ALLOCSET_DEFAULT_SIZES);
    3616            8 :         MemoryContextSwitchTo(work_cxt);
    3617              : 
    3618              :         /************************************************************
    3619              :          * Resolve argument type names and then look them up by oid
    3620              :          * in the system cache, and remember the required information
    3621              :          * for input conversion.
    3622              :          ************************************************************/
    3623           15 :         for (i = 0; i < argc; i++)
    3624              :         {
    3625              :             Oid         typId,
    3626              :                         typInput,
    3627              :                         typIOParam;
    3628              :             int32       typmod;
    3629              :             char       *typstr;
    3630              : 
    3631            8 :             typstr = sv2cstr(argv[i]);
    3632            8 :             (void) parseTypeString(typstr, &typId, &typmod, NULL);
    3633            7 :             pfree(typstr);
    3634              : 
    3635            7 :             getTypeInputInfo(typId, &typInput, &typIOParam);
    3636              : 
    3637            7 :             qdesc->argtypes[i] = typId;
    3638            7 :             fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
    3639            7 :             qdesc->argtypioparams[i] = typIOParam;
    3640              :         }
    3641              : 
    3642              :         /* Make sure the query is validly encoded */
    3643            7 :         pg_verifymbstr(query, strlen(query), false);
    3644              : 
    3645              :         /************************************************************
    3646              :          * Prepare the plan and check for errors
    3647              :          ************************************************************/
    3648            7 :         plan = SPI_prepare(query, argc, qdesc->argtypes);
    3649              : 
    3650            7 :         if (plan == NULL)
    3651            0 :             elog(ERROR, "SPI_prepare() failed:%s",
    3652              :                  SPI_result_code_string(SPI_result));
    3653              : 
    3654              :         /************************************************************
    3655              :          * Save the plan into permanent memory (right now it's in the
    3656              :          * SPI procCxt, which will go away at function end).
    3657              :          ************************************************************/
    3658            7 :         if (SPI_keepplan(plan))
    3659            0 :             elog(ERROR, "SPI_keepplan() failed");
    3660            7 :         qdesc->plan = plan;
    3661              : 
    3662              :         /************************************************************
    3663              :          * Insert a hashtable entry for the plan.
    3664              :          ************************************************************/
    3665           14 :         hash_entry = hash_search(plperl_active_interp->query_hash,
    3666            7 :                                  qdesc->qname,
    3667              :                                  HASH_ENTER, &found);
    3668            7 :         hash_entry->query_data = qdesc;
    3669              : 
    3670              :         /* Get rid of workspace */
    3671            7 :         MemoryContextDelete(work_cxt);
    3672              : 
    3673              :         /* Commit the inner transaction, return to outer xact context */
    3674            7 :         ReleaseCurrentSubTransaction();
    3675            7 :         MemoryContextSwitchTo(oldcontext);
    3676            7 :         CurrentResourceOwner = oldowner;
    3677              :     }
    3678            1 :     PG_CATCH();
    3679              :     {
    3680              :         ErrorData  *edata;
    3681              : 
    3682              :         /* Save error info */
    3683            1 :         MemoryContextSwitchTo(oldcontext);
    3684            1 :         edata = CopyErrorData();
    3685            1 :         FlushErrorState();
    3686              : 
    3687              :         /* Drop anything we managed to allocate */
    3688            1 :         if (hash_entry)
    3689            0 :             hash_search(plperl_active_interp->query_hash,
    3690            0 :                         qdesc->qname,
    3691              :                         HASH_REMOVE, NULL);
    3692            1 :         if (plan_cxt)
    3693            1 :             MemoryContextDelete(plan_cxt);
    3694            1 :         if (plan)
    3695            0 :             SPI_freeplan(plan);
    3696              : 
    3697              :         /* Abort the inner transaction */
    3698            1 :         RollbackAndReleaseCurrentSubTransaction();
    3699            1 :         MemoryContextSwitchTo(oldcontext);
    3700            1 :         CurrentResourceOwner = oldowner;
    3701              : 
    3702              :         /* Punt the error to Perl */
    3703            1 :         croak_cstr(edata->message);
    3704              : 
    3705              :         /* Can't get here, but keep compiler quiet */
    3706            0 :         return NULL;
    3707              :     }
    3708            7 :     PG_END_TRY();
    3709              : 
    3710              :     /************************************************************
    3711              :      * Return the query's hash key to the caller.
    3712              :      ************************************************************/
    3713            7 :     return cstr2sv(qdesc->qname);
    3714              : }
    3715              : 
    3716              : HV *
    3717            6 : plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
    3718              : {
    3719              :     HV         *ret_hv;
    3720              :     SV        **sv;
    3721              :     int         i,
    3722              :                 limit,
    3723              :                 spi_rv;
    3724              :     char       *nulls;
    3725              :     Datum      *argvalues;
    3726              :     plperl_query_desc *qdesc;
    3727              :     plperl_query_entry *hash_entry;
    3728              : 
    3729              :     /*
    3730              :      * Execute the query inside a sub-transaction, so we can cope with errors
    3731              :      * sanely
    3732              :      */
    3733            6 :     MemoryContext oldcontext = CurrentMemoryContext;
    3734            6 :     ResourceOwner oldowner = CurrentResourceOwner;
    3735              : 
    3736            6 :     check_spi_usage_allowed();
    3737              : 
    3738            6 :     BeginInternalSubTransaction(NULL);
    3739              :     /* Want to run inside function's memory context */
    3740            6 :     MemoryContextSwitchTo(oldcontext);
    3741              : 
    3742            6 :     PG_TRY();
    3743              :     {
    3744            6 :         dTHX;
    3745              : 
    3746              :         /************************************************************
    3747              :          * Fetch the saved plan descriptor, see if it's o.k.
    3748              :          ************************************************************/
    3749            6 :         hash_entry = hash_search(plperl_active_interp->query_hash, query,
    3750              :                                  HASH_FIND, NULL);
    3751            6 :         if (hash_entry == NULL)
    3752            0 :             elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
    3753              : 
    3754            6 :         qdesc = hash_entry->query_data;
    3755            6 :         if (qdesc == NULL)
    3756            0 :             elog(ERROR, "spi_exec_prepared: plperl query_hash value vanished");
    3757              : 
    3758            6 :         if (qdesc->nargs != argc)
    3759            0 :             elog(ERROR, "spi_exec_prepared: expected %d argument(s), %d passed",
    3760              :                  qdesc->nargs, argc);
    3761              : 
    3762              :         /************************************************************
    3763              :          * Parse eventual attributes
    3764              :          ************************************************************/
    3765            6 :         limit = 0;
    3766            6 :         if (attr != NULL)
    3767              :         {
    3768            2 :             sv = hv_fetch_string(attr, "limit");
    3769            2 :             if (sv && *sv && SvIOK(*sv))
    3770            0 :                 limit = SvIV(*sv);
    3771              :         }
    3772              :         /************************************************************
    3773              :          * Set up arguments
    3774              :          ************************************************************/
    3775            6 :         if (argc > 0)
    3776              :         {
    3777            4 :             nulls = (char *) palloc(argc);
    3778            4 :             argvalues = (Datum *) palloc(argc * sizeof(Datum));
    3779              :         }
    3780              :         else
    3781              :         {
    3782            2 :             nulls = NULL;
    3783            2 :             argvalues = NULL;
    3784              :         }
    3785              : 
    3786           10 :         for (i = 0; i < argc; i++)
    3787              :         {
    3788              :             bool        isnull;
    3789              : 
    3790            8 :             argvalues[i] = plperl_sv_to_datum(argv[i],
    3791            4 :                                               qdesc->argtypes[i],
    3792              :                                               -1,
    3793              :                                               NULL,
    3794            4 :                                               &qdesc->arginfuncs[i],
    3795            4 :                                               qdesc->argtypioparams[i],
    3796              :                                               &isnull);
    3797            4 :             nulls[i] = isnull ? 'n' : ' ';
    3798              :         }
    3799              : 
    3800              :         /************************************************************
    3801              :          * go
    3802              :          ************************************************************/
    3803           12 :         spi_rv = SPI_execute_plan(qdesc->plan, argvalues, nulls,
    3804            6 :                                   current_call_data->prodesc->fn_readonly, limit);
    3805            6 :         ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
    3806              :                                                  spi_rv);
    3807            6 :         if (argc > 0)
    3808              :         {
    3809            4 :             pfree(argvalues);
    3810            4 :             pfree(nulls);
    3811              :         }
    3812              : 
    3813              :         /* Commit the inner transaction, return to outer xact context */
    3814            6 :         ReleaseCurrentSubTransaction();
    3815            6 :         MemoryContextSwitchTo(oldcontext);
    3816            6 :         CurrentResourceOwner = oldowner;
    3817              :     }
    3818            0 :     PG_CATCH();
    3819              :     {
    3820              :         ErrorData  *edata;
    3821              : 
    3822              :         /* Save error info */
    3823            0 :         MemoryContextSwitchTo(oldcontext);
    3824            0 :         edata = CopyErrorData();
    3825            0 :         FlushErrorState();
    3826              : 
    3827              :         /* Abort the inner transaction */
    3828            0 :         RollbackAndReleaseCurrentSubTransaction();
    3829            0 :         MemoryContextSwitchTo(oldcontext);
    3830            0 :         CurrentResourceOwner = oldowner;
    3831              : 
    3832              :         /* Punt the error to Perl */
    3833            0 :         croak_cstr(edata->message);
    3834              : 
    3835              :         /* Can't get here, but keep compiler quiet */
    3836            0 :         return NULL;
    3837              :     }
    3838            6 :     PG_END_TRY();
    3839              : 
    3840            6 :     return ret_hv;
    3841              : }
    3842              : 
    3843              : SV *
    3844            2 : plperl_spi_query_prepared(char *query, int argc, SV **argv)
    3845              : {
    3846              :     int         i;
    3847              :     char       *nulls;
    3848              :     Datum      *argvalues;
    3849              :     plperl_query_desc *qdesc;
    3850              :     plperl_query_entry *hash_entry;
    3851              :     SV         *cursor;
    3852            2 :     Portal      portal = NULL;
    3853              : 
    3854              :     /*
    3855              :      * Execute the query inside a sub-transaction, so we can cope with errors
    3856              :      * sanely
    3857              :      */
    3858            2 :     MemoryContext oldcontext = CurrentMemoryContext;
    3859            2 :     ResourceOwner oldowner = CurrentResourceOwner;
    3860              : 
    3861            2 :     check_spi_usage_allowed();
    3862              : 
    3863            2 :     BeginInternalSubTransaction(NULL);
    3864              :     /* Want to run inside function's memory context */
    3865            2 :     MemoryContextSwitchTo(oldcontext);
    3866              : 
    3867            2 :     PG_TRY();
    3868              :     {
    3869              :         /************************************************************
    3870              :          * Fetch the saved plan descriptor, see if it's o.k.
    3871              :          ************************************************************/
    3872            2 :         hash_entry = hash_search(plperl_active_interp->query_hash, query,
    3873              :                                  HASH_FIND, NULL);
    3874            2 :         if (hash_entry == NULL)
    3875            0 :             elog(ERROR, "spi_query_prepared: Invalid prepared query passed");
    3876              : 
    3877            2 :         qdesc = hash_entry->query_data;
    3878            2 :         if (qdesc == NULL)
    3879            0 :             elog(ERROR, "spi_query_prepared: plperl query_hash value vanished");
    3880              : 
    3881            2 :         if (qdesc->nargs != argc)
    3882            0 :             elog(ERROR, "spi_query_prepared: expected %d argument(s), %d passed",
    3883              :                  qdesc->nargs, argc);
    3884              : 
    3885              :         /************************************************************
    3886              :          * Set up arguments
    3887              :          ************************************************************/
    3888            2 :         if (argc > 0)
    3889              :         {
    3890            2 :             nulls = (char *) palloc(argc);
    3891            2 :             argvalues = (Datum *) palloc(argc * sizeof(Datum));
    3892              :         }
    3893              :         else
    3894              :         {
    3895            0 :             nulls = NULL;
    3896            0 :             argvalues = NULL;
    3897              :         }
    3898              : 
    3899            5 :         for (i = 0; i < argc; i++)
    3900              :         {
    3901              :             bool        isnull;
    3902              : 
    3903            6 :             argvalues[i] = plperl_sv_to_datum(argv[i],
    3904            3 :                                               qdesc->argtypes[i],
    3905              :                                               -1,
    3906              :                                               NULL,
    3907            3 :                                               &qdesc->arginfuncs[i],
    3908            3 :                                               qdesc->argtypioparams[i],
    3909              :                                               &isnull);
    3910            3 :             nulls[i] = isnull ? 'n' : ' ';
    3911              :         }
    3912              : 
    3913              :         /************************************************************
    3914              :          * go
    3915              :          ************************************************************/
    3916            4 :         portal = SPI_cursor_open(NULL, qdesc->plan, argvalues, nulls,
    3917            2 :                                  current_call_data->prodesc->fn_readonly);
    3918            2 :         if (argc > 0)
    3919              :         {
    3920            2 :             pfree(argvalues);
    3921            2 :             pfree(nulls);
    3922              :         }
    3923            2 :         if (portal == NULL)
    3924            0 :             elog(ERROR, "SPI_cursor_open() failed:%s",
    3925              :                  SPI_result_code_string(SPI_result));
    3926              : 
    3927            2 :         cursor = cstr2sv(portal->name);
    3928              : 
    3929            2 :         PinPortal(portal);
    3930              : 
    3931              :         /* Commit the inner transaction, return to outer xact context */
    3932            2 :         ReleaseCurrentSubTransaction();
    3933            2 :         MemoryContextSwitchTo(oldcontext);
    3934            2 :         CurrentResourceOwner = oldowner;
    3935              :     }
    3936            0 :     PG_CATCH();
    3937              :     {
    3938              :         ErrorData  *edata;
    3939              : 
    3940              :         /* Save error info */
    3941            0 :         MemoryContextSwitchTo(oldcontext);
    3942            0 :         edata = CopyErrorData();
    3943            0 :         FlushErrorState();
    3944              : 
    3945              :         /* Abort the inner transaction */
    3946            0 :         RollbackAndReleaseCurrentSubTransaction();
    3947            0 :         MemoryContextSwitchTo(oldcontext);
    3948            0 :         CurrentResourceOwner = oldowner;
    3949              : 
    3950              :         /* Punt the error to Perl */
    3951            0 :         croak_cstr(edata->message);
    3952              : 
    3953              :         /* Can't get here, but keep compiler quiet */
    3954            0 :         return NULL;
    3955              :     }
    3956            2 :     PG_END_TRY();
    3957              : 
    3958            2 :     return cursor;
    3959              : }
    3960              : 
    3961              : void
    3962            5 : plperl_spi_freeplan(char *query)
    3963              : {
    3964              :     SPIPlanPtr  plan;
    3965              :     plperl_query_desc *qdesc;
    3966              :     plperl_query_entry *hash_entry;
    3967              : 
    3968            5 :     check_spi_usage_allowed();
    3969              : 
    3970            5 :     hash_entry = hash_search(plperl_active_interp->query_hash, query,
    3971              :                              HASH_FIND, NULL);
    3972            5 :     if (hash_entry == NULL)
    3973            0 :         elog(ERROR, "spi_freeplan: Invalid prepared query passed");
    3974              : 
    3975            5 :     qdesc = hash_entry->query_data;
    3976            5 :     if (qdesc == NULL)
    3977            0 :         elog(ERROR, "spi_freeplan: plperl query_hash value vanished");
    3978            5 :     plan = qdesc->plan;
    3979              : 
    3980              :     /*
    3981              :      * free all memory before SPI_freeplan, so if it dies, nothing will be
    3982              :      * left over
    3983              :      */
    3984            5 :     hash_search(plperl_active_interp->query_hash, query,
    3985              :                 HASH_REMOVE, NULL);
    3986              : 
    3987            5 :     MemoryContextDelete(qdesc->plan_cxt);
    3988              : 
    3989            5 :     SPI_freeplan(plan);
    3990            5 : }
    3991              : 
    3992              : void
    3993           25 : plperl_spi_commit(void)
    3994              : {
    3995           25 :     MemoryContext oldcontext = CurrentMemoryContext;
    3996              : 
    3997           25 :     check_spi_usage_allowed();
    3998              : 
    3999           25 :     PG_TRY();
    4000              :     {
    4001           25 :         SPI_commit();
    4002              :     }
    4003            5 :     PG_CATCH();
    4004              :     {
    4005              :         ErrorData  *edata;
    4006              : 
    4007              :         /* Save error info */
    4008            5 :         MemoryContextSwitchTo(oldcontext);
    4009            5 :         edata = CopyErrorData();
    4010            5 :         FlushErrorState();
    4011              : 
    4012              :         /* Punt the error to Perl */
    4013            5 :         croak_cstr(edata->message);
    4014              :     }
    4015           20 :     PG_END_TRY();
    4016           20 : }
    4017              : 
    4018              : void
    4019           17 : plperl_spi_rollback(void)
    4020              : {
    4021           17 :     MemoryContext oldcontext = CurrentMemoryContext;
    4022              : 
    4023           17 :     check_spi_usage_allowed();
    4024              : 
    4025           17 :     PG_TRY();
    4026              :     {
    4027           17 :         SPI_rollback();
    4028              :     }
    4029            0 :     PG_CATCH();
    4030              :     {
    4031              :         ErrorData  *edata;
    4032              : 
    4033              :         /* Save error info */
    4034            0 :         MemoryContextSwitchTo(oldcontext);
    4035            0 :         edata = CopyErrorData();
    4036            0 :         FlushErrorState();
    4037              : 
    4038              :         /* Punt the error to Perl */
    4039            0 :         croak_cstr(edata->message);
    4040              :     }
    4041           17 :     PG_END_TRY();
    4042           17 : }
    4043              : 
    4044              : /*
    4045              :  * Implementation of plperl's elog() function
    4046              :  *
    4047              :  * If the error level is less than ERROR, we'll just emit the message and
    4048              :  * return.  When it is ERROR, elog() will longjmp, which we catch and
    4049              :  * turn into a Perl croak().  Note we are assuming that elog() can't have
    4050              :  * any internal failures that are so bad as to require a transaction abort.
    4051              :  *
    4052              :  * The main reason this is out-of-line is to avoid conflicts between XSUB.h
    4053              :  * and the PG_TRY macros.
    4054              :  */
    4055              : void
    4056          186 : plperl_util_elog(int level, SV *msg)
    4057              : {
    4058          186 :     MemoryContext oldcontext = CurrentMemoryContext;
    4059          186 :     char       *volatile cmsg = NULL;
    4060              : 
    4061              :     /*
    4062              :      * We intentionally omit check_spi_usage_allowed() here, as this seems
    4063              :      * safe to allow even in the contexts that that function rejects.
    4064              :      */
    4065              : 
    4066          186 :     PG_TRY();
    4067              :     {
    4068          186 :         cmsg = sv2cstr(msg);
    4069          186 :         elog(level, "%s", cmsg);
    4070          185 :         pfree(cmsg);
    4071              :     }
    4072            1 :     PG_CATCH();
    4073              :     {
    4074              :         ErrorData  *edata;
    4075              : 
    4076              :         /* Must reset elog.c's state */
    4077            1 :         MemoryContextSwitchTo(oldcontext);
    4078            1 :         edata = CopyErrorData();
    4079            1 :         FlushErrorState();
    4080              : 
    4081            1 :         if (cmsg)
    4082            1 :             pfree(cmsg);
    4083              : 
    4084              :         /* Punt the error to Perl */
    4085            1 :         croak_cstr(edata->message);
    4086              :     }
    4087          185 :     PG_END_TRY();
    4088          185 : }
    4089              : 
    4090              : /*
    4091              :  * Store an SV into a hash table under a key that is a string assumed to be
    4092              :  * in the current database's encoding.
    4093              :  */
    4094              : static SV **
    4095          736 : hv_store_string(HV *hv, const char *key, SV *val)
    4096              : {
    4097          736 :     dTHX;
    4098              :     int32       hlen;
    4099              :     char       *hkey;
    4100              :     SV        **ret;
    4101              : 
    4102          736 :     hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
    4103              : 
    4104              :     /*
    4105              :      * hv_store() recognizes a negative klen parameter as meaning a UTF-8
    4106              :      * encoded key.
    4107              :      */
    4108          736 :     hlen = -(int) strlen(hkey);
    4109          736 :     ret = hv_store(hv, hkey, hlen, val, 0);
    4110              : 
    4111          736 :     if (hkey != key)
    4112            0 :         pfree(hkey);
    4113              : 
    4114          736 :     return ret;
    4115              : }
    4116              : 
    4117              : /*
    4118              :  * Fetch an SV from a hash table under a key that is a string assumed to be
    4119              :  * in the current database's encoding.
    4120              :  */
    4121              : static SV **
    4122            9 : hv_fetch_string(HV *hv, const char *key)
    4123              : {
    4124            9 :     dTHX;
    4125              :     int32       hlen;
    4126              :     char       *hkey;
    4127              :     SV        **ret;
    4128              : 
    4129            9 :     hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
    4130              : 
    4131              :     /* See notes in hv_store_string */
    4132            9 :     hlen = -(int) strlen(hkey);
    4133            9 :     ret = hv_fetch(hv, hkey, hlen, 0);
    4134              : 
    4135            9 :     if (hkey != key)
    4136            0 :         pfree(hkey);
    4137              : 
    4138            9 :     return ret;
    4139              : }
    4140              : 
    4141              : /*
    4142              :  * Provide function name for PL/Perl execution errors
    4143              :  */
    4144              : static void
    4145          234 : plperl_exec_callback(void *arg)
    4146              : {
    4147          234 :     char       *procname = (char *) arg;
    4148              : 
    4149          234 :     if (procname)
    4150          234 :         errcontext("PL/Perl function \"%s\"", procname);
    4151          234 : }
    4152              : 
    4153              : /*
    4154              :  * Provide function name for PL/Perl compilation errors
    4155              :  */
    4156              : static void
    4157            4 : plperl_compile_callback(void *arg)
    4158              : {
    4159            4 :     char       *procname = (char *) arg;
    4160              : 
    4161            4 :     if (procname)
    4162            4 :         errcontext("compilation of PL/Perl function \"%s\"", procname);
    4163            4 : }
    4164              : 
    4165              : /*
    4166              :  * Provide error context for the inline handler
    4167              :  */
    4168              : static void
    4169           23 : plperl_inline_callback(void *arg)
    4170              : {
    4171           23 :     errcontext("PL/Perl anonymous code block");
    4172           23 : }
    4173              : 
    4174              : 
    4175              : /*
    4176              :  * Perl's own setlocale(), copied from POSIX.xs
    4177              :  * (needed because of the calls to new_*())
    4178              :  *
    4179              :  * Starting in 5.28, perl exposes Perl_setlocale to do so.
    4180              :  */
    4181              : #if defined(WIN32) && PERL_VERSION_LT(5, 28, 0)
    4182              : static char *
    4183              : setlocale_perl(int category, char *locale)
    4184              : {
    4185              :     dTHX;
    4186              :     char       *RETVAL = setlocale(category, locale);
    4187              : 
    4188              :     if (RETVAL)
    4189              :     {
    4190              : #ifdef USE_LOCALE_CTYPE
    4191              :         if (category == LC_CTYPE
    4192              : #ifdef LC_ALL
    4193              :             || category == LC_ALL
    4194              : #endif
    4195              :             )
    4196              :         {
    4197              :             char       *newctype;
    4198              : 
    4199              : #ifdef LC_ALL
    4200              :             if (category == LC_ALL)
    4201              :                 newctype = setlocale(LC_CTYPE, NULL);
    4202              :             else
    4203              : #endif
    4204              :                 newctype = RETVAL;
    4205              :             new_ctype(newctype);
    4206              :         }
    4207              : #endif                          /* USE_LOCALE_CTYPE */
    4208              : #ifdef USE_LOCALE_COLLATE
    4209              :         if (category == LC_COLLATE
    4210              : #ifdef LC_ALL
    4211              :             || category == LC_ALL
    4212              : #endif
    4213              :             )
    4214              :         {
    4215              :             char       *newcoll;
    4216              : 
    4217              : #ifdef LC_ALL
    4218              :             if (category == LC_ALL)
    4219              :                 newcoll = setlocale(LC_COLLATE, NULL);
    4220              :             else
    4221              : #endif
    4222              :                 newcoll = RETVAL;
    4223              :             new_collate(newcoll);
    4224              :         }
    4225              : #endif                          /* USE_LOCALE_COLLATE */
    4226              : 
    4227              : #ifdef USE_LOCALE_NUMERIC
    4228              :         if (category == LC_NUMERIC
    4229              : #ifdef LC_ALL
    4230              :             || category == LC_ALL
    4231              : #endif
    4232              :             )
    4233              :         {
    4234              :             char       *newnum;
    4235              : 
    4236              : #ifdef LC_ALL
    4237              :             if (category == LC_ALL)
    4238              :                 newnum = setlocale(LC_NUMERIC, NULL);
    4239              :             else
    4240              : #endif
    4241              :                 newnum = RETVAL;
    4242              :             new_numeric(newnum);
    4243              :         }
    4244              : #endif                          /* USE_LOCALE_NUMERIC */
    4245              :     }
    4246              : 
    4247              :     return RETVAL;
    4248              : }
    4249              : #endif                          /* defined(WIN32) && PERL_VERSION_LT(5, 28, 0) */
        

Generated by: LCOV version 2.0-1