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