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