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