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