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