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