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