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