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