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