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