LCOV - differential code coverage report
Current view: top level - src/pl/plperl - plperl.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DUB DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 88.5 % 1444 1278 166 23 1255 1 24
Current Date: 2026-08-27 14:31:44 +0300 Functions: 100.0 % 73 73 8 65 1
Baseline: lcov-20260827-baseline Branches: 58.0 % 993 576 16 401 26 550
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 5 5 5
(7,30] days: 97.8 % 46 45 1 18 27
(30,360] days: 100.0 % 8 8 8
(360..) days: 88.1 % 1385 1220 165 1220
Function coverage date bins:
(7,30] days: 100.0 % 1 1 1
(360..) days: 100.0 % 72 72 8 64
Branch coverage date bins:
(1,7] days: 68.2 % 22 15 7 15
(7,30] days: 56.7 % 30 17 9 4 11 6
(360..) days: 57.8 % 941 544 397 544

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

Generated by: LCOV version 2.0-1