1 /**********************************************************************
2 * plperl.c - perl as a procedural language for PostgreSQL
4 * src/pl/plperl/plperl.c
6 **********************************************************************/
16 /* postgreSQL stuff */
17 #include "access/htup_details.h"
18 #include "access/xact.h"
19 #include "catalog/pg_language.h"
20 #include "catalog/pg_proc.h"
21 #include "catalog/pg_type.h"
22 #include "commands/event_trigger.h"
23 #include "commands/trigger.h"
24 #include "executor/spi.h"
26 #include "mb/pg_wchar.h"
27 #include "miscadmin.h"
28 #include "nodes/makefuncs.h"
29 #include "parser/parse_type.h"
30 #include "storage/ipc.h"
31 #include "tcop/tcopprot.h"
32 #include "utils/builtins.h"
33 #include "utils/fmgroids.h"
34 #include "utils/guc.h"
35 #include "utils/hsearch.h"
36 #include "utils/lsyscache.h"
37 #include "utils/memutils.h"
38 #include "utils/rel.h"
39 #include "utils/syscache.h"
40 #include "utils/typcache.h"
42 /* define our text domain for translations */
44 #define TEXTDOMAIN PG_TEXTDOMAIN("plperl")
48 #include "plperl_helpers.h"
50 /* string literal macros defining chunks of perl code */
51 #include "perlchunks.h"
52 /* defines PLPERL_SET_OPMASK */
53 #include "plperl_opmask.h"
55 EXTERN_C void boot_DynaLoader(pTHX_ CV *cv);
56 EXTERN_C void boot_PostgreSQL__InServer__Util(pTHX_ CV *cv);
57 EXTERN_C void boot_PostgreSQL__InServer__SPI(pTHX_ CV *cv);
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.)
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.
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.
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 **********************************************************************/
86 typedef struct plperl_interp_desc
88 Oid user_id; /* Hash key (must be first!) */
89 PerlInterpreter *interp; /* The interpreter */
90 HTAB *query_hash; /* plperl_query_entry structs */
94 /**********************************************************************
95 * The information we cache about loaded procedures
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 **********************************************************************/
103 typedef struct plperl_proc_desc
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 */
109 ItemPointerData fn_tid;
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 */
122 Oid result_typioparam;
123 /* Per-argument info for function's argument types: */
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 */
130 #define increment_prodesc_refcount(prodesc) \
131 ((prodesc)->fn_refcount++)
132 #define decrement_prodesc_refcount(prodesc) \
134 Assert((prodesc)->fn_refcount > 0); \
135 if (--((prodesc)->fn_refcount) == 0) \
136 free_plperl_function(prodesc); \
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.
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 **********************************************************************/
152 typedef struct plperl_proc_key
154 Oid proc_id; /* Function OID */
157 * is_trigger is really a bool, but declare as Oid to ensure this struct
158 * contains no padding
160 Oid is_trigger; /* is it a trigger function? */
161 Oid user_id; /* User calling the function, or 0 */
164 typedef struct plperl_proc_ptr
166 plperl_proc_key proc_key; /* Hash key (must be first!) */
167 plperl_proc_desc *proc_ptr;
171 * The information we cache for the duration of a single call to a
174 typedef struct plperl_call_data
176 plperl_proc_desc *prodesc;
177 FunctionCallInfo fcinfo;
178 /* remaining fields are used only in a function returning set: */
179 Tuplestorestate *tuple_store;
181 Oid cdomain_oid; /* 0 unless returning domain-over-composite */
183 MemoryContext tmp_cxt;
186 /**********************************************************************
187 * The information we cache about prepared and saved plans
188 **********************************************************************/
189 typedef struct plperl_query_desc
192 MemoryContext plan_cxt; /* context holding this struct */
196 FmgrInfo *arginfuncs;
200 /* hash table entry for query desc */
202 typedef struct plperl_query_entry
204 char query_name[NAMEDATALEN];
205 plperl_query_desc *query_data;
206 } plperl_query_entry;
208 /**********************************************************************
209 * Information for PostgreSQL - Perl array conversion.
210 **********************************************************************/
211 typedef struct plperl_array_info
214 bool elem_is_rowtype; /* 't' if element type is a rowtype */
219 FmgrInfo transform_proc;
222 /**********************************************************************
224 **********************************************************************/
226 static HTAB *plperl_interp_hash = NULL;
227 static HTAB *plperl_proc_hash = NULL;
228 static plperl_interp_desc *plperl_active_interp = NULL;
230 /* If we have an unassigned "held" interpreter, it's stored here */
231 static PerlInterpreter *plperl_held_interp = NULL;
234 static bool plperl_use_strict = false;
235 static char *plperl_on_init = NULL;
236 static char *plperl_on_plperl_init = NULL;
237 static char *plperl_on_plperlu_init = NULL;
239 static bool plperl_ending = false;
240 static OP *(*pp_require_orig) (pTHX) = NULL;
241 static char plperl_opmask[MAXO];
243 /* this is saved and restored by plperl_call_handler */
244 static plperl_call_data *current_call_data = NULL;
246 /**********************************************************************
247 * Forward declarations
248 **********************************************************************/
251 static PerlInterpreter *plperl_init_interp(void);
252 static void plperl_destroy_interp(PerlInterpreter **);
253 static void plperl_fini(int code, Datum arg);
254 static void set_interp_require(bool trusted);
256 static Datum plperl_func_handler(PG_FUNCTION_ARGS);
257 static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
258 static void plperl_event_trigger_handler(PG_FUNCTION_ARGS);
260 static void free_plperl_function(plperl_proc_desc *prodesc);
262 static plperl_proc_desc *compile_plperl_function(Oid fn_oid,
264 bool is_event_trigger);
266 static SV *plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc, bool include_generated);
267 static SV *plperl_hash_from_datum(Datum attr);
268 static SV *plperl_ref_from_pg_array(Datum arg, Oid typid);
269 static SV *split_array(plperl_array_info *info, int first, int last, int nest);
270 static SV *make_array_ref(plperl_array_info *info, int first, int last);
271 static SV *get_perl_array_ref(SV *sv);
272 static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
273 FunctionCallInfo fcinfo,
274 FmgrInfo *finfo, Oid typioparam,
276 static void _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam);
277 static Datum plperl_array_to_datum(SV *src, Oid typid, int32 typmod);
278 static void array_to_datum_internal(AV *av, ArrayBuildState *astate,
279 int *ndims, int *dims, int cur_depth,
280 Oid arraytypid, Oid elemtypid, int32 typmod,
281 FmgrInfo *finfo, Oid typioparam);
282 static Datum plperl_hash_to_datum(SV *src, TupleDesc td);
284 static void plperl_init_shared_libs(pTHX);
285 static void plperl_trusted_init(void);
286 static void plperl_untrusted_init(void);
287 static HV *plperl_spi_execute_fetch_result(SPITupleTable *, uint64, int);
288 static void plperl_return_next_internal(SV *sv);
289 static char *hek2cstr(HE *he);
290 static SV **hv_store_string(HV *hv, const char *key, SV *val);
291 static SV **hv_fetch_string(HV *hv, const char *key);
292 static void plperl_create_sub(plperl_proc_desc *desc, const char *s, Oid fn_oid);
293 static SV *plperl_call_perl_func(plperl_proc_desc *desc,
294 FunctionCallInfo fcinfo);
295 static void plperl_compile_callback(void *arg);
296 static void plperl_exec_callback(void *arg);
297 static void plperl_inline_callback(void *arg);
298 static char *strip_trailing_ws(const char *msg);
299 static OP *pp_require_safe(pTHX);
300 static void activate_interpreter(plperl_interp_desc *interp_desc);
303 static char *setlocale_perl(int category, char *locale);
307 * Decrement the refcount of the given SV within the active Perl interpreter
309 * This is handy because it reloads the active-interpreter pointer, saving
310 * some notation in callers that switch the active interpreter.
313 SvREFCNT_dec_current(SV *sv)
321 * convert a HE (hash entry) key to a cstr in the current database encoding
331 * HeSVKEY_force will return a temporary mortal SV*, so we need to make
332 * sure to free it with ENTER/SAVE/FREE/LEAVE
337 /*-------------------------
338 * Unfortunately, while HeUTF8 is true for most things > 256, for values
339 * 128..255 it's not, but perl will treat them as unicode code points if
340 * the utf8 flag is not set ( see The "Unicode Bug" in perldoc perlunicode
343 * So if we did the expected:
346 * else // must be ascii
348 * we won't match columns with codepoints from 128..255
350 * For a more concrete example given a column with the name of the unicode
351 * codepoint U+00ae (registered sign) and a UTF8 database and the perl
352 * return_next { "\N{U+00ae}=>'text } would always fail as heUTF8 returns
353 * 0 and HePV() would give us a char * with 1 byte contains the decimal
356 * Perl has the brains to know when it should utf8 encode 174 properly, so
357 * here we force it into an SV so that perl will figure it out and do the
359 *-------------------------
362 sv = HeSVKEY_force(he);
376 * _PG_init() - library load-time initialization
378 * DO NOT make this static nor change its name!
384 * Be sure we do initialization only once.
386 * If initialization fails due to, e.g., plperl_init_interp() throwing an
387 * exception, then we'll return here on the next usage and the user will
388 * get a rather cryptic: ERROR: attempt to redefine parameter
389 * "plperl.use_strict"
391 static bool inited = false;
398 * Support localized messages.
400 pg_bindtextdomain(TEXTDOMAIN);
403 * Initialize plperl's GUCs.
405 DefineCustomBoolVariable("plperl.use_strict",
406 gettext_noop("If true, trusted and untrusted Perl code will be compiled in strict mode."),
414 * plperl.on_init is marked PGC_SIGHUP to support the idea that it might
415 * be executed in the postmaster (if plperl is loaded into the postmaster
416 * via shared_preload_libraries). This isn't really right either way,
419 DefineCustomStringVariable("plperl.on_init",
420 gettext_noop("Perl initialization code to execute when a Perl interpreter is initialized."),
428 * plperl.on_plperl_init is marked PGC_SUSET to avoid issues whereby a
429 * user who might not even have USAGE privilege on the plperl language
430 * could nonetheless use SET plperl.on_plperl_init='...' to influence the
431 * behaviour of any existing plperl function that they can execute (which
432 * might be SECURITY DEFINER, leading to a privilege escalation). See
433 * http://archives.postgresql.org/pgsql-hackers/2010-02/msg00281.php and
434 * the overall thread.
436 * Note that because plperl.use_strict is USERSET, a nefarious user could
437 * set it to be applied against other people's functions. This is judged
438 * OK since the worst result would be an error. Your code oughta pass
439 * use_strict anyway ;-)
441 DefineCustomStringVariable("plperl.on_plperl_init",
442 gettext_noop("Perl initialization code to execute once when plperl is first used."),
444 &plperl_on_plperl_init,
449 DefineCustomStringVariable("plperl.on_plperlu_init",
450 gettext_noop("Perl initialization code to execute once when plperlu is first used."),
452 &plperl_on_plperlu_init,
457 EmitWarningsOnPlaceholders("plperl");
460 * Create hash tables.
462 memset(&hash_ctl, 0, sizeof(hash_ctl));
463 hash_ctl.keysize = sizeof(Oid);
464 hash_ctl.entrysize = sizeof(plperl_interp_desc);
465 plperl_interp_hash = hash_create("PL/Perl interpreters",
468 HASH_ELEM | HASH_BLOBS);
470 memset(&hash_ctl, 0, sizeof(hash_ctl));
471 hash_ctl.keysize = sizeof(plperl_proc_key);
472 hash_ctl.entrysize = sizeof(plperl_proc_ptr);
473 plperl_proc_hash = hash_create("PL/Perl procedures",
476 HASH_ELEM | HASH_BLOBS);
479 * Save the default opmask.
481 PLPERL_SET_OPMASK(plperl_opmask);
484 * Create the first Perl interpreter, but only partially initialize it.
486 plperl_held_interp = plperl_init_interp();
493 set_interp_require(bool trusted)
497 PL_ppaddr[OP_REQUIRE] = pp_require_safe;
498 PL_ppaddr[OP_DOFILE] = pp_require_safe;
502 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
503 PL_ppaddr[OP_DOFILE] = pp_require_orig;
508 * Cleanup perl interpreters, including running END blocks.
509 * Does not fully undo the actions of _PG_init() nor make it callable again.
512 plperl_fini(int code, Datum arg)
514 HASH_SEQ_STATUS hash_seq;
515 plperl_interp_desc *interp_desc;
517 elog(DEBUG3, "plperl_fini");
520 * Indicate that perl is terminating. Disables use of spi_* functions when
521 * running END/DESTROY code. See check_spi_usage_allowed(). Could be
522 * enabled in future, with care, using a transaction
523 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02743.php
525 plperl_ending = true;
527 /* Only perform perl cleanup if we're exiting cleanly */
530 elog(DEBUG3, "plperl_fini: skipped");
534 /* Zap the "held" interpreter, if we still have it */
535 plperl_destroy_interp(&plperl_held_interp);
537 /* Zap any fully-initialized interpreters */
538 hash_seq_init(&hash_seq, plperl_interp_hash);
539 while ((interp_desc = hash_seq_search(&hash_seq)) != NULL)
541 if (interp_desc->interp)
543 activate_interpreter(interp_desc);
544 plperl_destroy_interp(&interp_desc->interp);
548 elog(DEBUG3, "plperl_fini: done");
553 * Select and activate an appropriate Perl interpreter.
556 select_perl_context(bool trusted)
559 plperl_interp_desc *interp_desc;
561 PerlInterpreter *interp = NULL;
563 /* Find or create the interpreter hashtable entry for this userid */
565 user_id = GetUserId();
567 user_id = InvalidOid;
569 interp_desc = hash_search(plperl_interp_hash, &user_id,
574 /* Initialize newly-created hashtable entry */
575 interp_desc->interp = NULL;
576 interp_desc->query_hash = NULL;
579 /* Make sure we have a query_hash for this interpreter */
580 if (interp_desc->query_hash == NULL)
584 memset(&hash_ctl, 0, sizeof(hash_ctl));
585 hash_ctl.keysize = NAMEDATALEN;
586 hash_ctl.entrysize = sizeof(plperl_query_entry);
587 interp_desc->query_hash = hash_create("PL/Perl queries",
594 * Quick exit if already have an interpreter
596 if (interp_desc->interp)
598 activate_interpreter(interp_desc);
603 * adopt held interp if free, else create new one if possible
605 if (plperl_held_interp != NULL)
607 /* first actual use of a perl interpreter */
608 interp = plperl_held_interp;
611 * Reset the plperl_held_interp pointer first; if we fail during init
612 * we don't want to try again with the partially-initialized interp.
614 plperl_held_interp = NULL;
617 plperl_trusted_init();
619 plperl_untrusted_init();
621 /* successfully initialized, so arrange for cleanup */
622 on_proc_exit(plperl_fini, 0);
629 * plperl_init_interp will change Perl's idea of the active
630 * interpreter. Reset plperl_active_interp temporarily, so that if we
631 * hit an error partway through here, we'll make sure to switch back
632 * to a non-broken interpreter before running any other Perl
635 plperl_active_interp = NULL;
637 /* Now build the new interpreter */
638 interp = plperl_init_interp();
641 plperl_trusted_init();
643 plperl_untrusted_init();
646 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
647 errmsg("cannot allocate multiple Perl interpreters on this platform")));
651 set_interp_require(trusted);
654 * Since the timing of first use of PL/Perl can't be predicted, any
655 * database interaction during initialization is problematic. Including,
656 * but not limited to, security definer issues. So we only enable access
657 * to the database AFTER on_*_init code has run. See
658 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02669.php
663 newXS("PostgreSQL::InServer::SPI::bootstrap",
664 boot_PostgreSQL__InServer__SPI, __FILE__);
666 eval_pv("PostgreSQL::InServer::SPI::bootstrap()", FALSE);
669 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
670 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
671 errcontext("while executing PostgreSQL::InServer::SPI::bootstrap")));
674 /* Fully initialized, so mark the hashtable entry valid */
675 interp_desc->interp = interp;
677 /* And mark this as the active interpreter */
678 plperl_active_interp = interp_desc;
682 * Make the specified interpreter the active one
684 * A call with NULL does nothing. This is so that "restoring" to a previously
685 * null state of plperl_active_interp doesn't result in useless thrashing.
688 activate_interpreter(plperl_interp_desc *interp_desc)
690 if (interp_desc && plperl_active_interp != interp_desc)
692 Assert(interp_desc->interp);
693 PERL_SET_CONTEXT(interp_desc->interp);
694 /* trusted iff user_id isn't InvalidOid */
695 set_interp_require(OidIsValid(interp_desc->user_id));
696 plperl_active_interp = interp_desc;
701 * Create a new Perl interpreter.
703 * We initialize the interpreter as far as we can without knowing whether
704 * it will become a trusted or untrusted interpreter; in particular, the
705 * plperl.on_init code will get executed. Later, either plperl_trusted_init
706 * or plperl_untrusted_init must be called to complete the initialization.
708 static PerlInterpreter *
709 plperl_init_interp(void)
711 PerlInterpreter *plperl;
713 static char *embedding[3 + 2] = {
714 "", "-e", PLC_PERLBOOT
721 * The perl library on startup does horrible things like call
722 * setlocale(LC_ALL,""). We have protected against that on most platforms
723 * by setting the environment appropriately. However, on Windows,
724 * setlocale() does not consult the environment, so we need to save the
725 * existing locale settings before perl has a chance to mangle them and
726 * restore them after its dirty deeds are done.
729 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_locale.asp
731 * It appears that we only need to do this on interpreter startup, and
732 * subsequent calls to the interpreter don't mess with the locale
735 * We restore them using setlocale_perl(), defined below, so that Perl
736 * doesn't have a different idea of the locale from Postgres.
747 loc = setlocale(LC_COLLATE, NULL);
748 save_collate = loc ? pstrdup(loc) : NULL;
749 loc = setlocale(LC_CTYPE, NULL);
750 save_ctype = loc ? pstrdup(loc) : NULL;
751 loc = setlocale(LC_MONETARY, NULL);
752 save_monetary = loc ? pstrdup(loc) : NULL;
753 loc = setlocale(LC_NUMERIC, NULL);
754 save_numeric = loc ? pstrdup(loc) : NULL;
755 loc = setlocale(LC_TIME, NULL);
756 save_time = loc ? pstrdup(loc) : NULL;
758 #define PLPERL_RESTORE_LOCALE(name, saved) \
760 if (saved != NULL) { setlocale_perl(name, saved); pfree(saved); } \
764 if (plperl_on_init && *plperl_on_init)
766 embedding[nargs++] = "-e";
767 embedding[nargs++] = plperl_on_init;
771 * The perl API docs state that PERL_SYS_INIT3 should be called before
772 * allocating interpreters. Unfortunately, on some platforms this fails in
773 * the Perl_do_taint() routine, which is called when the platform is using
774 * the system's malloc() instead of perl's own. Other platforms, notably
775 * Windows, fail if PERL_SYS_INIT3 is not called. So we call it if it's
776 * available, unless perl is using the system malloc(), which is true when
779 #if defined(PERL_SYS_INIT3) && !defined(MYMALLOC)
781 static int perl_sys_init_done;
783 /* only call this the first time through, as per perlembed man page */
784 if (!perl_sys_init_done)
786 char *dummy_env[1] = {NULL};
788 PERL_SYS_INIT3(&nargs, (char ***) &embedding, (char ***) &dummy_env);
791 * For unclear reasons, PERL_SYS_INIT3 sets the SIGFPE handler to
792 * SIG_IGN. Aside from being extremely unfriendly behavior for a
793 * library, this is dumb on the grounds that the results of a
794 * SIGFPE in this state are undefined according to POSIX, and in
795 * fact you get a forced process kill at least on Linux. Hence,
796 * restore the SIGFPE handler to the backend's standard setting.
797 * (See Perl bug 114574 for more information.)
799 pqsignal(SIGFPE, FloatExceptionHandler);
801 perl_sys_init_done = 1;
802 /* quiet warning if PERL_SYS_INIT3 doesn't use the third argument */
808 plperl = perl_alloc();
810 elog(ERROR, "could not allocate Perl interpreter");
812 PERL_SET_CONTEXT(plperl);
813 perl_construct(plperl);
816 * Run END blocks in perl_destruct instead of perl_run. Note that dTHX
817 * loads up a pointer to the current interpreter, so we have to postpone
818 * it to here rather than put it at the function head.
823 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
826 * Record the original function for the 'require' and 'dofile'
827 * opcodes. (They share the same implementation.) Ensure it's used
828 * for new interpreters.
830 if (!pp_require_orig)
831 pp_require_orig = PL_ppaddr[OP_REQUIRE];
834 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
835 PL_ppaddr[OP_DOFILE] = pp_require_orig;
838 #ifdef PLPERL_ENABLE_OPMASK_EARLY
841 * For regression testing to prove that the PLC_PERLBOOT and
842 * PLC_TRUSTED code doesn't even compile any unsafe ops. In future
843 * there may be a valid need for them to do so, in which case this
844 * could be softened (perhaps moved to plperl_trusted_init()) or
847 PL_op_mask = plperl_opmask;
850 if (perl_parse(plperl, plperl_init_shared_libs,
851 nargs, embedding, NULL) != 0)
853 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
854 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
855 errcontext("while parsing Perl initialization")));
857 if (perl_run(plperl) != 0)
859 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
860 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
861 errcontext("while running Perl initialization")));
863 #ifdef PLPERL_RESTORE_LOCALE
864 PLPERL_RESTORE_LOCALE(LC_COLLATE, save_collate);
865 PLPERL_RESTORE_LOCALE(LC_CTYPE, save_ctype);
866 PLPERL_RESTORE_LOCALE(LC_MONETARY, save_monetary);
867 PLPERL_RESTORE_LOCALE(LC_NUMERIC, save_numeric);
868 PLPERL_RESTORE_LOCALE(LC_TIME, save_time);
877 * Our safe implementation of the require opcode.
878 * This is safe because it's completely unable to load any code.
879 * If the requested file/module has already been loaded it'll return true.
881 * So now "use Foo;" will work iff Foo has already been loaded.
884 pp_require_safe(pTHX)
894 name = SvPV(sv, len);
895 if (!(name && len > 0 && *name))
898 svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
899 if (svp && *svp != &PL_sv_undef)
902 DIE(aTHX_ "Unable to load %s into plperl", name);
905 * In most Perl versions, DIE() expands to a return statement, so the next
906 * line is not necessary. But in versions between but not including
907 * 5.11.1 and 5.13.3 it does not, so the next line is necessary to avoid a
908 * "control reaches end of non-void function" warning from gcc. Other
909 * compilers such as Solaris Studio will, however, issue a "statement not
910 * reached" warning instead.
917 * Destroy one Perl interpreter ... actually we just run END blocks.
919 * Caller must have ensured this interpreter is the active one.
922 plperl_destroy_interp(PerlInterpreter **interp)
924 if (interp && *interp)
927 * Only a very minimal destruction is performed: - just call END
930 * We could call perl_destruct() but we'd need to audit its actions
931 * very carefully and work-around any that impact us. (Calling
932 * sv_clean_objs() isn't an option because it's not part of perl's
933 * public API so isn't portably available.) Meanwhile END blocks can
934 * be used to perform manual cleanup.
938 /* Run END blocks - based on perl's perl_destruct() */
939 if (PL_exit_flags & PERL_EXIT_DESTRUCT_END)
946 if (PL_endav && !PL_minus_c)
947 call_list(PL_scopestack_ix, PL_endav);
958 * Initialize the current Perl interpreter as a trusted interp
961 plperl_trusted_init(void)
969 /* use original require while we set up */
970 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
971 PL_ppaddr[OP_DOFILE] = pp_require_orig;
973 eval_pv(PLC_TRUSTED, FALSE);
976 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
977 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
978 errcontext("while executing PLC_TRUSTED")));
981 * Force loading of utf8 module now to prevent errors that can arise from
982 * the regex code later trying to load utf8 modules. See
983 * http://rt.perl.org/rt3/Ticket/Display.html?id=47576
985 eval_pv("my $a=chr(0x100); return $a =~ /\\xa9/i", FALSE);
988 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
989 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
990 errcontext("while executing utf8fix")));
993 * Lock down the interpreter
996 /* switch to the safe require/dofile opcode for future code */
997 PL_ppaddr[OP_REQUIRE] = pp_require_safe;
998 PL_ppaddr[OP_DOFILE] = pp_require_safe;
1001 * prevent (any more) unsafe opcodes being compiled PL_op_mask is per
1002 * interpreter, so this only needs to be set once
1004 PL_op_mask = plperl_opmask;
1006 /* delete the DynaLoader:: namespace so extensions can't be loaded */
1007 stash = gv_stashpv("DynaLoader", GV_ADDWARN);
1009 while ((sv = hv_iternextsv(stash, &key, &klen)))
1011 if (!isGV_with_GP(sv) || !GvCV(sv))
1013 SvREFCNT_dec(GvCV(sv)); /* free the CV */
1014 GvCV_set(sv, NULL); /* prevent call via GV */
1018 /* invalidate assorted caches */
1019 ++PL_sub_generation;
1020 hv_clear(PL_stashcache);
1023 * Execute plperl.on_plperl_init in the locked-down interpreter
1025 if (plperl_on_plperl_init && *plperl_on_plperl_init)
1027 eval_pv(plperl_on_plperl_init, FALSE);
1028 /* XXX need to find a way to determine a better errcode here */
1031 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1032 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
1033 errcontext("while executing plperl.on_plperl_init")));
1039 * Initialize the current Perl interpreter as an untrusted interp
1042 plperl_untrusted_init(void)
1047 * Nothing to do except execute plperl.on_plperlu_init
1049 if (plperl_on_plperlu_init && *plperl_on_plperlu_init)
1051 eval_pv(plperl_on_plperlu_init, FALSE);
1054 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1055 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
1056 errcontext("while executing plperl.on_plperlu_init")));
1062 * Perl likes to put a newline after its error messages; clean up such
1065 strip_trailing_ws(const char *msg)
1067 char *res = pstrdup(msg);
1068 int len = strlen(res);
1070 while (len > 0 && isspace((unsigned char) res[len - 1]))
1076 /* Build a tuple from a hash. */
1079 plperl_build_tuple_result(HV *perlhash, TupleDesc td)
1087 values = palloc0(sizeof(Datum) * td->natts);
1088 nulls = palloc(sizeof(bool) * td->natts);
1089 memset(nulls, true, sizeof(bool) * td->natts);
1091 hv_iterinit(perlhash);
1092 while ((he = hv_iternext(perlhash)))
1094 SV *val = HeVAL(he);
1095 char *key = hek2cstr(he);
1096 int attn = SPI_fnumber(td, key);
1097 Form_pg_attribute attr = TupleDescAttr(td, attn - 1);
1099 if (attn == SPI_ERROR_NOATTRIBUTE)
1101 (errcode(ERRCODE_UNDEFINED_COLUMN),
1102 errmsg("Perl hash contains nonexistent column \"%s\"",
1106 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1107 errmsg("cannot set system attribute \"%s\"",
1110 values[attn - 1] = plperl_sv_to_datum(val,
1120 hv_iterinit(perlhash);
1122 tup = heap_form_tuple(td, values, nulls);
1128 /* convert a hash reference to a datum */
1130 plperl_hash_to_datum(SV *src, TupleDesc td)
1132 HeapTuple tup = plperl_build_tuple_result((HV *) SvRV(src), td);
1134 return HeapTupleGetDatum(tup);
1138 * if we are an array ref return the reference. this is special in that if we
1139 * are a PostgreSQL::InServer::ARRAY object we will return the 'magic' array.
1142 get_perl_array_ref(SV *sv)
1146 if (SvOK(sv) && SvROK(sv))
1148 if (SvTYPE(SvRV(sv)) == SVt_PVAV)
1150 else if (sv_isa(sv, "PostgreSQL::InServer::ARRAY"))
1152 HV *hv = (HV *) SvRV(sv);
1153 SV **sav = hv_fetch_string(hv, "array");
1155 if (*sav && SvOK(*sav) && SvROK(*sav) &&
1156 SvTYPE(SvRV(*sav)) == SVt_PVAV)
1159 elog(ERROR, "could not get array reference from PostgreSQL::InServer::ARRAY object");
1166 * helper function for plperl_array_to_datum, recurses for multi-D arrays
1169 array_to_datum_internal(AV *av, ArrayBuildState *astate,
1170 int *ndims, int *dims, int cur_depth,
1171 Oid arraytypid, Oid elemtypid, int32 typmod,
1172 FmgrInfo *finfo, Oid typioparam)
1176 int len = av_len(av) + 1;
1178 for (i = 0; i < len; i++)
1180 /* fetch the array element */
1181 SV **svp = av_fetch(av, i, FALSE);
1183 /* see if this element is an array, if so get that */
1184 SV *sav = svp ? get_perl_array_ref(*svp) : NULL;
1186 /* multi-dimensional array? */
1189 AV *nav = (AV *) SvRV(sav);
1191 /* dimensionality checks */
1192 if (cur_depth + 1 > MAXDIM)
1194 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1195 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
1196 cur_depth + 1, MAXDIM)));
1198 /* set size when at first element in this level, else compare */
1199 if (i == 0 && *ndims == cur_depth)
1201 dims[*ndims] = av_len(nav) + 1;
1204 else if (av_len(nav) + 1 != dims[cur_depth])
1206 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1207 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1209 /* recurse to fetch elements of this sub-array */
1210 array_to_datum_internal(nav, astate,
1211 ndims, dims, cur_depth + 1,
1212 arraytypid, elemtypid, typmod,
1220 /* scalar after some sub-arrays at same level? */
1221 if (*ndims != cur_depth)
1223 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1224 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1226 dat = plperl_sv_to_datum(svp ? *svp : NULL,
1234 (void) accumArrayResult(astate, dat, isnull,
1235 elemtypid, CurrentMemoryContext);
1241 * convert perl array ref to a datum
1244 plperl_array_to_datum(SV *src, Oid typid, int32 typmod)
1247 ArrayBuildState *astate;
1256 elemtypid = get_element_type(typid);
1259 (errcode(ERRCODE_DATATYPE_MISMATCH),
1260 errmsg("cannot convert Perl array to non-array type %s",
1261 format_type_be(typid))));
1263 astate = initArrayResult(elemtypid, CurrentMemoryContext, true);
1265 _sv_to_datum_finfo(elemtypid, &finfo, &typioparam);
1267 memset(dims, 0, sizeof(dims));
1268 dims[0] = av_len((AV *) SvRV(src)) + 1;
1270 array_to_datum_internal((AV *) SvRV(src), astate,
1272 typid, elemtypid, typmod,
1273 &finfo, typioparam);
1275 /* ensure we get zero-D array for no inputs, as per PG convention */
1279 for (i = 0; i < ndims; i++)
1282 return makeMdArrayResult(astate, ndims, dims, lbs,
1283 CurrentMemoryContext, true);
1286 /* Get the information needed to convert data to the specified PG type */
1288 _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam)
1292 /* XXX would be better to cache these lookups */
1293 getTypeInputInfo(typid,
1294 &typinput, typioparam);
1295 fmgr_info(typinput, finfo);
1299 * convert Perl SV to PG datum of type typid, typmod typmod
1301 * Pass the PL/Perl function's fcinfo when attempting to convert to the
1302 * function's result type; otherwise pass NULL. This is used when we need to
1303 * resolve the actual result type of a function returning RECORD.
1305 * finfo and typioparam should be the results of _sv_to_datum_finfo for the
1306 * given typid, or NULL/InvalidOid to let this function do the lookups.
1308 * *isnull is an output parameter.
1311 plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
1312 FunctionCallInfo fcinfo,
1313 FmgrInfo *finfo, Oid typioparam,
1319 /* we might recurse */
1320 check_stack_depth();
1325 * Return NULL if result is undef, or if we're in a function returning
1326 * VOID. In the latter case, we should pay no attention to the last Perl
1327 * statement's result, and this is a convenient means to ensure that.
1329 if (!sv || !SvOK(sv) || typid == VOIDOID)
1331 /* look up type info if they did not pass it */
1334 _sv_to_datum_finfo(typid, &tmp, &typioparam);
1338 /* must call typinput in case it wants to reject NULL */
1339 return InputFunctionCall(finfo, NULL, typioparam, typmod);
1341 else if ((funcid = get_transform_tosql(typid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
1342 return OidFunctionCall1(funcid, PointerGetDatum(sv));
1345 /* handle references */
1346 SV *sav = get_perl_array_ref(sv);
1350 /* handle an arrayref */
1351 return plperl_array_to_datum(sav, typid, typmod);
1353 else if (SvTYPE(SvRV(sv)) == SVt_PVHV)
1355 /* handle a hashref */
1360 if (!type_is_rowtype(typid))
1362 (errcode(ERRCODE_DATATYPE_MISMATCH),
1363 errmsg("cannot convert Perl hash to non-composite type %s",
1364 format_type_be(typid))));
1366 td = lookup_rowtype_tupdesc_domain(typid, typmod, true);
1369 /* Did we look through a domain? */
1370 isdomain = (typid != td->tdtypeid);
1374 /* Must be RECORD, try to resolve based on call info */
1375 TypeFuncClass funcclass;
1378 funcclass = get_call_result_type(fcinfo, &typid, &td);
1380 funcclass = TYPEFUNC_OTHER;
1381 if (funcclass != TYPEFUNC_COMPOSITE &&
1382 funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
1384 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1385 errmsg("function returning record called in context "
1386 "that cannot accept type record")));
1388 isdomain = (funcclass == TYPEFUNC_COMPOSITE_DOMAIN);
1391 ret = plperl_hash_to_datum(sv, td);
1394 domain_check(ret, false, typid, NULL, NULL);
1396 /* Release on the result of get_call_result_type is harmless */
1397 ReleaseTupleDesc(td);
1403 * If it's a reference to something else, such as a scalar, just
1404 * recursively look through the reference.
1406 return plperl_sv_to_datum(SvRV(sv), typid, typmod,
1407 fcinfo, finfo, typioparam,
1412 /* handle a string/number */
1414 char *str = sv2cstr(sv);
1416 /* did not pass in any typeinfo? look it up */
1419 _sv_to_datum_finfo(typid, &tmp, &typioparam);
1423 ret = InputFunctionCall(finfo, str, typioparam, typmod);
1430 /* Convert the perl SV to a string returned by the type output function */
1432 plperl_sv_to_literal(SV *sv, char *fqtypename)
1434 Datum str = CStringGetDatum(fqtypename);
1435 Oid typid = DirectFunctionCall1(regtypein, str);
1441 if (!OidIsValid(typid))
1443 (errcode(ERRCODE_UNDEFINED_OBJECT),
1444 errmsg("lookup failed for type %s", fqtypename)));
1446 datum = plperl_sv_to_datum(sv,
1448 NULL, NULL, InvalidOid,
1454 getTypeOutputInfo(typid,
1455 &typoutput, &typisvarlena);
1457 return OidOutputFunctionCall(typoutput, datum);
1461 * Convert PostgreSQL array datum to a perl array reference.
1463 * typid is arg's OID, which must be an array type.
1466 plperl_ref_from_pg_array(Datum arg, Oid typid)
1469 ArrayType *ar = DatumGetArrayTypeP(arg);
1470 Oid elementtype = ARR_ELEMTYPE(ar);
1477 Oid transform_funcid;
1481 plperl_array_info *info;
1486 * Currently we make no effort to cache any of the stuff we look up here,
1489 info = palloc0(sizeof(plperl_array_info));
1491 /* get element type information, including output conversion function */
1492 get_type_io_data(elementtype, IOFunc_output,
1493 &typlen, &typbyval, &typalign,
1494 &typdelim, &typioparam, &typoutputfunc);
1496 /* Check for a transform function */
1497 transform_funcid = get_transform_fromsql(elementtype,
1498 current_call_data->prodesc->lang_oid,
1499 current_call_data->prodesc->trftypes);
1501 /* Look up transform or output function as appropriate */
1502 if (OidIsValid(transform_funcid))
1503 fmgr_info(transform_funcid, &info->transform_proc);
1505 fmgr_info(typoutputfunc, &info->proc);
1507 info->elem_is_rowtype = type_is_rowtype(elementtype);
1509 /* Get the number and bounds of array dimensions */
1510 info->ndims = ARR_NDIM(ar);
1511 dims = ARR_DIMS(ar);
1513 /* No dimensions? Return an empty array */
1514 if (info->ndims == 0)
1516 av = newRV_noinc((SV *) newAV());
1520 deconstruct_array(ar, elementtype, typlen, typbyval,
1521 typalign, &info->elements, &info->nulls,
1524 /* Get total number of elements in each dimension */
1525 info->nelems = palloc(sizeof(int) * info->ndims);
1526 info->nelems[0] = nitems;
1527 for (i = 1; i < info->ndims; i++)
1528 info->nelems[i] = info->nelems[i - 1] / dims[i - 1];
1530 av = split_array(info, 0, nitems, 0);
1534 (void) hv_store(hv, "array", 5, av, 0);
1535 (void) hv_store(hv, "typeoid", 7, newSVuv(typid), 0);
1537 return sv_bless(newRV_noinc((SV *) hv),
1538 gv_stashpv("PostgreSQL::InServer::ARRAY", 0));
1542 * Recursively form array references from splices of the initial array
1545 split_array(plperl_array_info *info, int first, int last, int nest)
1551 /* we should only be called when we have something to split */
1552 Assert(info->ndims > 0);
1554 /* since this function recurses, it could be driven to stack overflow */
1555 check_stack_depth();
1558 * Base case, return a reference to a single-dimensional array
1560 if (nest >= info->ndims - 1)
1561 return make_array_ref(info, first, last);
1564 for (i = first; i < last; i += info->nelems[nest + 1])
1566 /* Recursively form references to arrays of lower dimensions */
1567 SV *ref = split_array(info, i, i + info->nelems[nest + 1], nest + 1);
1569 av_push(result, ref);
1571 return newRV_noinc((SV *) result);
1575 * Create a Perl reference from a one-dimensional C array, converting
1576 * composite type elements to hash references.
1579 make_array_ref(plperl_array_info *info, int first, int last)
1583 AV *result = newAV();
1585 for (i = first; i < last; i++)
1590 * We can't use &PL_sv_undef here. See "AVs, HVs and undefined
1591 * values" in perlguts.
1593 av_push(result, newSV(0));
1597 Datum itemvalue = info->elements[i];
1599 if (info->transform_proc.fn_oid)
1600 av_push(result, (SV *) DatumGetPointer(FunctionCall1(&info->transform_proc, itemvalue)));
1601 else if (info->elem_is_rowtype)
1602 /* Handle composite type elements */
1603 av_push(result, plperl_hash_from_datum(itemvalue));
1606 char *val = OutputFunctionCall(&info->proc, itemvalue);
1608 av_push(result, cstr2sv(val));
1612 return newRV_noinc((SV *) result);
1615 /* Set up the arguments for a trigger call. */
1617 plperl_trigger_build_args(FunctionCallInfo fcinfo)
1630 hv_ksplit(hv, 12); /* pre-grow the hash */
1632 tdata = (TriggerData *) fcinfo->context;
1633 tupdesc = tdata->tg_relation->rd_att;
1635 relid = DatumGetCString(
1636 DirectFunctionCall1(oidout,
1637 ObjectIdGetDatum(tdata->tg_relation->rd_id)
1641 hv_store_string(hv, "name", cstr2sv(tdata->tg_trigger->tgname));
1642 hv_store_string(hv, "relid", cstr2sv(relid));
1645 * Note: In BEFORE trigger, stored generated columns are not computed yet,
1646 * so don't make them accessible in NEW row.
1649 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
1652 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1653 hv_store_string(hv, "new",
1654 plperl_hash_from_tuple(tdata->tg_trigtuple,
1656 !TRIGGER_FIRED_BEFORE(tdata->tg_event)));
1658 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
1661 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1662 hv_store_string(hv, "old",
1663 plperl_hash_from_tuple(tdata->tg_trigtuple,
1667 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
1670 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1672 hv_store_string(hv, "old",
1673 plperl_hash_from_tuple(tdata->tg_trigtuple,
1676 hv_store_string(hv, "new",
1677 plperl_hash_from_tuple(tdata->tg_newtuple,
1679 !TRIGGER_FIRED_BEFORE(tdata->tg_event)));
1682 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
1687 hv_store_string(hv, "event", cstr2sv(event));
1688 hv_store_string(hv, "argc", newSViv(tdata->tg_trigger->tgnargs));
1690 if (tdata->tg_trigger->tgnargs > 0)
1694 av_extend(av, tdata->tg_trigger->tgnargs);
1695 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
1696 av_push(av, cstr2sv(tdata->tg_trigger->tgargs[i]));
1697 hv_store_string(hv, "args", newRV_noinc((SV *) av));
1700 hv_store_string(hv, "relname",
1701 cstr2sv(SPI_getrelname(tdata->tg_relation)));
1703 hv_store_string(hv, "table_name",
1704 cstr2sv(SPI_getrelname(tdata->tg_relation)));
1706 hv_store_string(hv, "table_schema",
1707 cstr2sv(SPI_getnspname(tdata->tg_relation)));
1709 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
1711 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
1713 else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
1714 when = "INSTEAD OF";
1717 hv_store_string(hv, "when", cstr2sv(when));
1719 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1721 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
1722 level = "STATEMENT";
1725 hv_store_string(hv, "level", cstr2sv(level));
1727 return newRV_noinc((SV *) hv);
1731 /* Set up the arguments for an event trigger call. */
1733 plperl_event_trigger_build_args(FunctionCallInfo fcinfo)
1736 EventTriggerData *tdata;
1741 tdata = (EventTriggerData *) fcinfo->context;
1743 hv_store_string(hv, "event", cstr2sv(tdata->event));
1744 hv_store_string(hv, "tag", cstr2sv(tdata->tag));
1746 return newRV_noinc((SV *) hv);
1749 /* Construct the modified new tuple to be returned from a trigger. */
1751 plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup)
1764 svp = hv_fetch_string(hvTD, "new");
1767 (errcode(ERRCODE_UNDEFINED_COLUMN),
1768 errmsg("$_TD->{new} does not exist")));
1769 if (!SvOK(*svp) || !SvROK(*svp) || SvTYPE(SvRV(*svp)) != SVt_PVHV)
1771 (errcode(ERRCODE_DATATYPE_MISMATCH),
1772 errmsg("$_TD->{new} is not a hash reference")));
1773 hvNew = (HV *) SvRV(*svp);
1775 tupdesc = tdata->tg_relation->rd_att;
1776 natts = tupdesc->natts;
1778 modvalues = (Datum *) palloc0(natts * sizeof(Datum));
1779 modnulls = (bool *) palloc0(natts * sizeof(bool));
1780 modrepls = (bool *) palloc0(natts * sizeof(bool));
1783 while ((he = hv_iternext(hvNew)))
1785 char *key = hek2cstr(he);
1786 SV *val = HeVAL(he);
1787 int attn = SPI_fnumber(tupdesc, key);
1788 Form_pg_attribute attr = TupleDescAttr(tupdesc, attn - 1);
1790 if (attn == SPI_ERROR_NOATTRIBUTE)
1792 (errcode(ERRCODE_UNDEFINED_COLUMN),
1793 errmsg("Perl hash contains nonexistent column \"%s\"",
1797 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1798 errmsg("cannot set system attribute \"%s\"",
1800 if (attr->attgenerated)
1802 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1803 errmsg("cannot set generated column \"%s\"",
1806 modvalues[attn - 1] = plperl_sv_to_datum(val,
1812 &modnulls[attn - 1]);
1813 modrepls[attn - 1] = true;
1819 rtup = heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls);
1830 * There are three externally visible pieces to plperl: plperl_call_handler,
1831 * plperl_inline_handler, and plperl_validator.
1835 * The call handler is called to run normal functions (including trigger
1836 * functions) that are defined in pg_proc.
1838 PG_FUNCTION_INFO_V1(plperl_call_handler);
1841 plperl_call_handler(PG_FUNCTION_ARGS)
1844 plperl_call_data *volatile save_call_data = current_call_data;
1845 plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1846 plperl_call_data this_call_data;
1848 /* Initialize current-call status record */
1849 MemSet(&this_call_data, 0, sizeof(this_call_data));
1850 this_call_data.fcinfo = fcinfo;
1854 current_call_data = &this_call_data;
1855 if (CALLED_AS_TRIGGER(fcinfo))
1856 retval = PointerGetDatum(plperl_trigger_handler(fcinfo));
1857 else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
1859 plperl_event_trigger_handler(fcinfo);
1863 retval = plperl_func_handler(fcinfo);
1867 current_call_data = save_call_data;
1868 activate_interpreter(oldinterp);
1869 if (this_call_data.prodesc)
1870 decrement_prodesc_refcount(this_call_data.prodesc);
1875 current_call_data = save_call_data;
1876 activate_interpreter(oldinterp);
1877 if (this_call_data.prodesc)
1878 decrement_prodesc_refcount(this_call_data.prodesc);
1883 * The inline handler runs anonymous code blocks (DO blocks).
1885 PG_FUNCTION_INFO_V1(plperl_inline_handler);
1888 plperl_inline_handler(PG_FUNCTION_ARGS)
1890 LOCAL_FCINFO(fake_fcinfo, 0);
1891 InlineCodeBlock *codeblock = (InlineCodeBlock *) PG_GETARG_POINTER(0);
1893 plperl_proc_desc desc;
1894 plperl_call_data *volatile save_call_data = current_call_data;
1895 plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1896 plperl_call_data this_call_data;
1897 ErrorContextCallback pl_error_context;
1899 /* Initialize current-call status record */
1900 MemSet(&this_call_data, 0, sizeof(this_call_data));
1902 /* Set up a callback for error reporting */
1903 pl_error_context.callback = plperl_inline_callback;
1904 pl_error_context.previous = error_context_stack;
1905 pl_error_context.arg = NULL;
1906 error_context_stack = &pl_error_context;
1909 * Set up a fake fcinfo and descriptor with just enough info to satisfy
1910 * plperl_call_perl_func(). In particular note that this sets things up
1911 * with no arguments passed, and a result type of VOID.
1913 MemSet(fake_fcinfo, 0, SizeForFunctionCallInfo(0));
1914 MemSet(&flinfo, 0, sizeof(flinfo));
1915 MemSet(&desc, 0, sizeof(desc));
1916 fake_fcinfo->flinfo = &flinfo;
1917 flinfo.fn_oid = InvalidOid;
1918 flinfo.fn_mcxt = CurrentMemoryContext;
1920 desc.proname = "inline_code_block";
1921 desc.fn_readonly = false;
1923 desc.lang_oid = codeblock->langOid;
1924 desc.trftypes = NIL;
1925 desc.lanpltrusted = codeblock->langIsTrusted;
1927 desc.fn_retistuple = false;
1928 desc.fn_retisset = false;
1929 desc.fn_retisarray = false;
1930 desc.result_oid = InvalidOid;
1932 desc.reference = NULL;
1934 this_call_data.fcinfo = fake_fcinfo;
1935 this_call_data.prodesc = &desc;
1936 /* we do not bother with refcounting the fake prodesc */
1942 current_call_data = &this_call_data;
1944 if (SPI_connect_ext(codeblock->atomic ? 0 : SPI_OPT_NONATOMIC) != SPI_OK_CONNECT)
1945 elog(ERROR, "could not connect to SPI manager");
1947 select_perl_context(desc.lanpltrusted);
1949 plperl_create_sub(&desc, codeblock->source_text, 0);
1951 if (!desc.reference) /* can this happen? */
1952 elog(ERROR, "could not create internal procedure for anonymous code block");
1954 perlret = plperl_call_perl_func(&desc, fake_fcinfo);
1956 SvREFCNT_dec_current(perlret);
1958 if (SPI_finish() != SPI_OK_FINISH)
1959 elog(ERROR, "SPI_finish() failed");
1964 SvREFCNT_dec_current(desc.reference);
1965 current_call_data = save_call_data;
1966 activate_interpreter(oldinterp);
1972 SvREFCNT_dec_current(desc.reference);
1974 current_call_data = save_call_data;
1975 activate_interpreter(oldinterp);
1977 error_context_stack = pl_error_context.previous;
1983 * The validator is called during CREATE FUNCTION to validate the function
1984 * being created/replaced. The precise behavior of the validator may be
1985 * modified by the check_function_bodies GUC.
1987 PG_FUNCTION_INFO_V1(plperl_validator);
1990 plperl_validator(PG_FUNCTION_ARGS)
1992 Oid funcoid = PG_GETARG_OID(0);
2000 bool is_trigger = false;
2001 bool is_event_trigger = false;
2004 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
2007 /* Get the new function's pg_proc entry */
2008 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
2009 if (!HeapTupleIsValid(tuple))
2010 elog(ERROR, "cache lookup failed for function %u", funcoid);
2011 proc = (Form_pg_proc) GETSTRUCT(tuple);
2013 functyptype = get_typtype(proc->prorettype);
2015 /* Disallow pseudotype result */
2016 /* except for TRIGGER, EVTTRIGGER, RECORD, or VOID */
2017 if (functyptype == TYPTYPE_PSEUDO)
2019 /* we assume OPAQUE with no arguments means a trigger */
2020 if (proc->prorettype == TRIGGEROID ||
2021 (proc->prorettype == OPAQUEOID && proc->pronargs == 0))
2023 else if (proc->prorettype == EVTTRIGGEROID)
2024 is_event_trigger = true;
2025 else if (proc->prorettype != RECORDOID &&
2026 proc->prorettype != VOIDOID)
2028 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2029 errmsg("PL/Perl functions cannot return type %s",
2030 format_type_be(proc->prorettype))));
2033 /* Disallow pseudotypes in arguments (either IN or OUT) */
2034 numargs = get_func_arg_info(tuple,
2035 &argtypes, &argnames, &argmodes);
2036 for (i = 0; i < numargs; i++)
2038 if (get_typtype(argtypes[i]) == TYPTYPE_PSEUDO &&
2039 argtypes[i] != RECORDOID)
2041 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2042 errmsg("PL/Perl functions cannot accept type %s",
2043 format_type_be(argtypes[i]))));
2046 ReleaseSysCache(tuple);
2048 /* Postpone body checks if !check_function_bodies */
2049 if (check_function_bodies)
2051 (void) compile_plperl_function(funcoid, is_trigger, is_event_trigger);
2054 /* the result of a validator is ignored */
2060 * plperlu likewise requires three externally visible functions:
2061 * plperlu_call_handler, plperlu_inline_handler, and plperlu_validator.
2062 * These are currently just aliases that send control to the plperl
2063 * handler functions, and we decide whether a particular function is
2064 * trusted or not by inspecting the actual pg_language tuple.
2067 PG_FUNCTION_INFO_V1(plperlu_call_handler);
2070 plperlu_call_handler(PG_FUNCTION_ARGS)
2072 return plperl_call_handler(fcinfo);
2075 PG_FUNCTION_INFO_V1(plperlu_inline_handler);
2078 plperlu_inline_handler(PG_FUNCTION_ARGS)
2080 return plperl_inline_handler(fcinfo);
2083 PG_FUNCTION_INFO_V1(plperlu_validator);
2086 plperlu_validator(PG_FUNCTION_ARGS)
2088 /* call plperl validator with our fcinfo so it gets our oid */
2089 return plperl_validator(fcinfo);
2094 * Uses mkfunc to create a subroutine whose text is
2095 * supplied in s, and returns a reference to it
2098 plperl_create_sub(plperl_proc_desc *prodesc, const char *s, Oid fn_oid)
2102 char subname[NAMEDATALEN + 40];
2103 HV *pragma_hv = newHV();
2107 sprintf(subname, "%s__%u", prodesc->proname, fn_oid);
2109 if (plperl_use_strict)
2110 hv_store_string(pragma_hv, "strict", (SV *) newAV());
2116 PUSHs(sv_2mortal(cstr2sv(subname)));
2117 PUSHs(sv_2mortal(newRV_noinc((SV *) pragma_hv)));
2120 * Use 'false' for $prolog in mkfunc, which is kept for compatibility in
2121 * case a module such as PostgreSQL::PLPerl::NYTprof replaces the function
2125 PUSHs(sv_2mortal(cstr2sv(s)));
2129 * G_KEEPERR seems to be needed here, else we don't recognize compile
2130 * errors properly. Perhaps it's because there's another level of eval
2131 * inside mksafefunc?
2133 count = perl_call_pv("PostgreSQL::InServer::mkfunc",
2134 G_SCALAR | G_EVAL | G_KEEPERR);
2139 SV *sub_rv = (SV *) POPs;
2141 if (sub_rv && SvROK(sub_rv) && SvTYPE(SvRV(sub_rv)) == SVt_PVCV)
2143 subref = newRV_inc(SvRV(sub_rv));
2153 (errcode(ERRCODE_SYNTAX_ERROR),
2154 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2158 (errcode(ERRCODE_SYNTAX_ERROR),
2159 errmsg("didn't get a CODE reference from compiling function \"%s\"",
2160 prodesc->proname)));
2162 prodesc->reference = subref;
2168 /**********************************************************************
2169 * plperl_init_shared_libs() -
2170 **********************************************************************/
2173 plperl_init_shared_libs(pTHX)
2175 char *file = __FILE__;
2177 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2178 newXS("PostgreSQL::InServer::Util::bootstrap",
2179 boot_PostgreSQL__InServer__Util, file);
2180 /* newXS for...::SPI::bootstrap is in select_perl_context() */
2185 plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
2192 Oid *argtypes = NULL;
2199 EXTEND(sp, desc->nargs);
2201 /* Get signature for true functions; inline blocks have no args. */
2202 if (fcinfo->flinfo->fn_oid)
2203 get_func_signature(fcinfo->flinfo->fn_oid, &argtypes, &nargs);
2204 Assert(nargs == desc->nargs);
2206 for (i = 0; i < desc->nargs; i++)
2208 if (fcinfo->args[i].isnull)
2209 PUSHs(&PL_sv_undef);
2210 else if (desc->arg_is_rowtype[i])
2212 SV *sv = plperl_hash_from_datum(fcinfo->args[i].value);
2214 PUSHs(sv_2mortal(sv));
2221 if (OidIsValid(desc->arg_arraytype[i]))
2222 sv = plperl_ref_from_pg_array(fcinfo->args[i].value, desc->arg_arraytype[i]);
2223 else if ((funcid = get_transform_fromsql(argtypes[i], current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
2224 sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, fcinfo->args[i].value));
2229 tmp = OutputFunctionCall(&(desc->arg_out_func[i]),
2230 fcinfo->args[i].value);
2235 PUSHs(sv_2mortal(sv));
2240 /* Do NOT use G_KEEPERR here */
2241 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2251 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2252 errmsg("didn't get a return item from function")));
2261 /* XXX need to find a way to determine a better errcode here */
2263 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2264 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2267 retval = newSVsv(POPs);
2278 plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo,
2287 Trigger *tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
2292 TDsv = get_sv("main::_TD", 0);
2295 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2296 errmsg("couldn't fetch $_TD")));
2298 save_item(TDsv); /* local $_TD */
2302 EXTEND(sp, tg_trigger->tgnargs);
2304 for (i = 0; i < tg_trigger->tgnargs; i++)
2305 PUSHs(sv_2mortal(cstr2sv(tg_trigger->tgargs[i])));
2308 /* Do NOT use G_KEEPERR here */
2309 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2319 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2320 errmsg("didn't get a return item from trigger function")));
2329 /* XXX need to find a way to determine a better errcode here */
2331 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2332 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2335 retval = newSVsv(POPs);
2346 plperl_call_perl_event_trigger_func(plperl_proc_desc *desc,
2347 FunctionCallInfo fcinfo,
2359 TDsv = get_sv("main::_TD", 0);
2362 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2363 errmsg("couldn't fetch $_TD")));
2365 save_item(TDsv); /* local $_TD */
2371 /* Do NOT use G_KEEPERR here */
2372 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2382 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2383 errmsg("didn't get a return item from trigger function")));
2392 /* XXX need to find a way to determine a better errcode here */
2394 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2395 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2398 retval = newSVsv(POPs);
2399 (void) retval; /* silence compiler warning */
2409 plperl_func_handler(PG_FUNCTION_ARGS)
2412 plperl_proc_desc *prodesc;
2416 ErrorContextCallback pl_error_context;
2418 nonatomic = fcinfo->context &&
2419 IsA(fcinfo->context, CallContext) &&
2420 !castNode(CallContext, fcinfo->context)->atomic;
2422 if (SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0) != SPI_OK_CONNECT)
2423 elog(ERROR, "could not connect to SPI manager");
2425 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, false);
2426 current_call_data->prodesc = prodesc;
2427 increment_prodesc_refcount(prodesc);
2429 /* Set a callback for error reporting */
2430 pl_error_context.callback = plperl_exec_callback;
2431 pl_error_context.previous = error_context_stack;
2432 pl_error_context.arg = prodesc->proname;
2433 error_context_stack = &pl_error_context;
2435 rsi = (ReturnSetInfo *) fcinfo->resultinfo;
2437 if (prodesc->fn_retisset)
2439 /* Check context before allowing the call to go through */
2440 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2441 (rsi->allowedModes & SFRM_Materialize) == 0)
2443 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2444 errmsg("set-valued function called in context that "
2445 "cannot accept a set")));
2448 activate_interpreter(prodesc->interp);
2450 perlret = plperl_call_perl_func(prodesc, fcinfo);
2452 /************************************************************
2453 * Disconnect from SPI manager and then create the return
2454 * values datum (if the input function does a palloc for it
2455 * this must not be allocated in the SPI memory context
2456 * because SPI_finish would free it).
2457 ************************************************************/
2458 if (SPI_finish() != SPI_OK_FINISH)
2459 elog(ERROR, "SPI_finish() failed");
2461 if (prodesc->fn_retisset)
2466 * If the Perl function returned an arrayref, we pretend that it
2467 * called return_next() for each element of the array, to handle old
2468 * SRFs that didn't know about return_next(). Any other sort of return
2469 * value is an error, except undef which means return an empty set.
2471 sav = get_perl_array_ref(perlret);
2477 AV *rav = (AV *) SvRV(sav);
2479 while ((svp = av_fetch(rav, i, FALSE)) != NULL)
2481 plperl_return_next_internal(*svp);
2485 else if (SvOK(perlret))
2488 (errcode(ERRCODE_DATATYPE_MISMATCH),
2489 errmsg("set-returning PL/Perl function must return "
2490 "reference to array or use return_next")));
2493 rsi->returnMode = SFRM_Materialize;
2494 if (current_call_data->tuple_store)
2496 rsi->setResult = current_call_data->tuple_store;
2497 rsi->setDesc = current_call_data->ret_tdesc;
2501 else if (prodesc->result_oid)
2503 retval = plperl_sv_to_datum(perlret,
2504 prodesc->result_oid,
2507 &prodesc->result_in_func,
2508 prodesc->result_typioparam,
2511 if (fcinfo->isnull && rsi && IsA(rsi, ReturnSetInfo))
2512 rsi->isDone = ExprEndResult;
2515 /* Restore the previous error callback */
2516 error_context_stack = pl_error_context.previous;
2518 SvREFCNT_dec_current(perlret);
2525 plperl_trigger_handler(PG_FUNCTION_ARGS)
2527 plperl_proc_desc *prodesc;
2532 ErrorContextCallback pl_error_context;
2534 int rc PG_USED_FOR_ASSERTS_ONLY;
2536 /* Connect to SPI manager */
2537 if (SPI_connect() != SPI_OK_CONNECT)
2538 elog(ERROR, "could not connect to SPI manager");
2540 /* Make transition tables visible to this SPI connection */
2541 tdata = (TriggerData *) fcinfo->context;
2542 rc = SPI_register_trigger_data(tdata);
2545 /* Find or compile the function */
2546 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true, false);
2547 current_call_data->prodesc = prodesc;
2548 increment_prodesc_refcount(prodesc);
2550 /* Set a callback for error reporting */
2551 pl_error_context.callback = plperl_exec_callback;
2552 pl_error_context.previous = error_context_stack;
2553 pl_error_context.arg = prodesc->proname;
2554 error_context_stack = &pl_error_context;
2556 activate_interpreter(prodesc->interp);
2558 svTD = plperl_trigger_build_args(fcinfo);
2559 perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
2560 hvTD = (HV *) SvRV(svTD);
2562 /************************************************************
2563 * Disconnect from SPI manager and then create the return
2564 * values datum (if the input function does a palloc for it
2565 * this must not be allocated in the SPI memory context
2566 * because SPI_finish would free it).
2567 ************************************************************/
2568 if (SPI_finish() != SPI_OK_FINISH)
2569 elog(ERROR, "SPI_finish() failed");
2571 if (perlret == NULL || !SvOK(perlret))
2573 /* undef result means go ahead with original tuple */
2574 TriggerData *trigdata = ((TriggerData *) fcinfo->context);
2576 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2577 retval = (Datum) trigdata->tg_trigtuple;
2578 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2579 retval = (Datum) trigdata->tg_newtuple;
2580 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2581 retval = (Datum) trigdata->tg_trigtuple;
2582 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
2583 retval = (Datum) trigdata->tg_trigtuple;
2585 retval = (Datum) 0; /* can this happen? */
2592 tmp = sv2cstr(perlret);
2594 if (pg_strcasecmp(tmp, "SKIP") == 0)
2596 else if (pg_strcasecmp(tmp, "MODIFY") == 0)
2598 TriggerData *trigdata = (TriggerData *) fcinfo->context;
2600 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2601 trv = plperl_modify_tuple(hvTD, trigdata,
2602 trigdata->tg_trigtuple);
2603 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2604 trv = plperl_modify_tuple(hvTD, trigdata,
2605 trigdata->tg_newtuple);
2609 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2610 errmsg("ignoring modified row in DELETE trigger")));
2617 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2618 errmsg("result of PL/Perl trigger function must be undef, "
2619 "\"SKIP\", or \"MODIFY\"")));
2622 retval = PointerGetDatum(trv);
2626 /* Restore the previous error callback */
2627 error_context_stack = pl_error_context.previous;
2629 SvREFCNT_dec_current(svTD);
2631 SvREFCNT_dec_current(perlret);
2638 plperl_event_trigger_handler(PG_FUNCTION_ARGS)
2640 plperl_proc_desc *prodesc;
2642 ErrorContextCallback pl_error_context;
2644 /* Connect to SPI manager */
2645 if (SPI_connect() != SPI_OK_CONNECT)
2646 elog(ERROR, "could not connect to SPI manager");
2648 /* Find or compile the function */
2649 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, true);
2650 current_call_data->prodesc = prodesc;
2651 increment_prodesc_refcount(prodesc);
2653 /* Set a callback for error reporting */
2654 pl_error_context.callback = plperl_exec_callback;
2655 pl_error_context.previous = error_context_stack;
2656 pl_error_context.arg = prodesc->proname;
2657 error_context_stack = &pl_error_context;
2659 activate_interpreter(prodesc->interp);
2661 svTD = plperl_event_trigger_build_args(fcinfo);
2662 plperl_call_perl_event_trigger_func(prodesc, fcinfo, svTD);
2664 if (SPI_finish() != SPI_OK_FINISH)
2665 elog(ERROR, "SPI_finish() failed");
2667 /* Restore the previous error callback */
2668 error_context_stack = pl_error_context.previous;
2670 SvREFCNT_dec_current(svTD);
2675 validate_plperl_function(plperl_proc_ptr *proc_ptr, HeapTuple procTup)
2677 if (proc_ptr && proc_ptr->proc_ptr)
2679 plperl_proc_desc *prodesc = proc_ptr->proc_ptr;
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));
2693 /* Otherwise, unlink the obsoleted entry from the hashtable ... */
2694 proc_ptr->proc_ptr = NULL;
2695 /* ... and release the corresponding refcount, probably deleting it */
2696 decrement_prodesc_refcount(prodesc);
2704 free_plperl_function(plperl_proc_desc *prodesc)
2706 Assert(prodesc->fn_refcount == 0);
2707 /* Release CODE reference, if we have one, from the appropriate interp */
2708 if (prodesc->reference)
2710 plperl_interp_desc *oldinterp = plperl_active_interp;
2712 activate_interpreter(prodesc->interp);
2713 SvREFCNT_dec_current(prodesc->reference);
2714 activate_interpreter(oldinterp);
2716 /* Release all PG-owned data for this proc */
2717 MemoryContextDelete(prodesc->fn_cxt);
2721 static plperl_proc_desc *
2722 compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
2725 Form_pg_proc procStruct;
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;
2730 plperl_interp_desc *oldinterp = plperl_active_interp;
2731 ErrorContextCallback plperl_error_context;
2733 /* We'll need the pg_proc tuple in any case... */
2734 procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
2735 if (!HeapTupleIsValid(procTup))
2736 elog(ERROR, "cache lookup failed for function %u", fn_oid);
2737 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
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
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,
2750 if (validate_plperl_function(proc_ptr, procTup))
2752 /* Found valid plperl entry */
2753 ReleaseSysCache(procTup);
2754 return proc_ptr->proc_ptr;
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,
2761 if (validate_plperl_function(proc_ptr, procTup))
2763 /* Found valid plperlu entry */
2764 ReleaseSysCache(procTup);
2765 return proc_ptr->proc_ptr;
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 ************************************************************/
2776 /* Set a callback for reporting compilation errors */
2777 plperl_error_context.callback = plperl_compile_callback;
2778 plperl_error_context.previous = error_context_stack;
2779 plperl_error_context.arg = NameStr(procStruct->proname);
2780 error_context_stack = &plperl_error_context;
2786 Form_pg_language langStruct;
2787 Form_pg_type typeStruct;
2788 Datum protrftypes_datum;
2792 MemoryContext oldcontext;
2794 /************************************************************
2795 * Allocate a context that will hold all PG data for the procedure.
2796 ************************************************************/
2797 proc_cxt = AllocSetContextCreate(TopMemoryContext,
2799 ALLOCSET_SMALL_SIZES);
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);
2806 prodesc = (plperl_proc_desc *) palloc0(sizeof(plperl_proc_desc));
2807 prodesc->proname = pstrdup(NameStr(procStruct->proname));
2808 MemoryContextSetIdentifier(proc_cxt, prodesc->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);
2819 /* Remember if function is STABLE/IMMUTABLE */
2820 prodesc->fn_readonly =
2821 (procStruct->provolatile != PROVOLATILE_VOLATILE);
2823 /* Fetch protrftypes */
2824 protrftypes_datum = SysCacheGetAttr(PROCOID, procTup,
2825 Anum_pg_proc_protrftypes, &isnull);
2826 MemoryContextSwitchTo(proc_cxt);
2827 prodesc->trftypes = isnull ? NIL : oid_array_to_list(protrftypes_datum);
2828 MemoryContextSwitchTo(oldcontext);
2830 /************************************************************
2831 * Lookup the pg_language tuple by Oid
2832 ************************************************************/
2833 langTup = SearchSysCache1(LANGOID,
2834 ObjectIdGetDatum(procStruct->prolang));
2835 if (!HeapTupleIsValid(langTup))
2836 elog(ERROR, "cache lookup failed for language %u",
2837 procStruct->prolang);
2838 langStruct = (Form_pg_language) GETSTRUCT(langTup);
2839 prodesc->lang_oid = langStruct->oid;
2840 prodesc->lanpltrusted = langStruct->lanpltrusted;
2841 ReleaseSysCache(langTup);
2843 /************************************************************
2844 * Get the required information for input conversion of the
2846 ************************************************************/
2847 if (!is_trigger && !is_event_trigger)
2849 Oid rettype = procStruct->prorettype;
2851 typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettype));
2852 if (!HeapTupleIsValid(typeTup))
2853 elog(ERROR, "cache lookup failed for type %u", rettype);
2854 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2856 /* Disallow pseudotype result, except VOID or RECORD */
2857 if (typeStruct->typtype == TYPTYPE_PSEUDO)
2859 if (rettype == VOIDOID ||
2860 rettype == RECORDOID)
2862 else if (rettype == TRIGGEROID ||
2863 rettype == EVTTRIGGEROID)
2865 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2866 errmsg("trigger functions can only be called "
2870 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2871 errmsg("PL/Perl functions cannot return type %s",
2872 format_type_be(rettype))));
2875 prodesc->result_oid = rettype;
2876 prodesc->fn_retisset = procStruct->proretset;
2877 prodesc->fn_retistuple = type_is_rowtype(rettype);
2879 prodesc->fn_retisarray =
2880 (typeStruct->typlen == -1 && typeStruct->typelem);
2882 fmgr_info_cxt(typeStruct->typinput,
2883 &(prodesc->result_in_func),
2885 prodesc->result_typioparam = getTypeIOParam(typeTup);
2887 ReleaseSysCache(typeTup);
2890 /************************************************************
2891 * Get the required information for output conversion
2892 * of all procedure arguments
2893 ************************************************************/
2894 if (!is_trigger && !is_event_trigger)
2898 for (i = 0; i < prodesc->nargs; i++)
2900 Oid argtype = procStruct->proargtypes.values[i];
2902 typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype));
2903 if (!HeapTupleIsValid(typeTup))
2904 elog(ERROR, "cache lookup failed for type %u", argtype);
2905 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2907 /* Disallow pseudotype argument, except RECORD */
2908 if (typeStruct->typtype == TYPTYPE_PSEUDO &&
2909 argtype != RECORDOID)
2911 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2912 errmsg("PL/Perl functions cannot accept type %s",
2913 format_type_be(argtype))));
2915 if (type_is_rowtype(argtype))
2916 prodesc->arg_is_rowtype[i] = true;
2919 prodesc->arg_is_rowtype[i] = false;
2920 fmgr_info_cxt(typeStruct->typoutput,
2921 &(prodesc->arg_out_func[i]),
2925 /* Identify array-type arguments */
2926 if (typeStruct->typelem != 0 && typeStruct->typlen == -1)
2927 prodesc->arg_arraytype[i] = argtype;
2929 prodesc->arg_arraytype[i] = InvalidOid;
2931 ReleaseSysCache(typeTup);
2935 /************************************************************
2936 * create the text of the anonymous subroutine.
2937 * we do not use a named subroutine so that we can call directly
2938 * through the reference.
2939 ************************************************************/
2940 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
2941 Anum_pg_proc_prosrc, &isnull);
2943 elog(ERROR, "null prosrc");
2944 proc_source = TextDatumGetCString(prosrcdatum);
2946 /************************************************************
2947 * Create the procedure in the appropriate interpreter
2948 ************************************************************/
2950 select_perl_context(prodesc->lanpltrusted);
2952 prodesc->interp = plperl_active_interp;
2954 plperl_create_sub(prodesc, proc_source, fn_oid);
2956 activate_interpreter(oldinterp);
2960 if (!prodesc->reference) /* can this happen? */
2961 elog(ERROR, "could not create PL/Perl internal procedure");
2963 /************************************************************
2964 * OK, link the procedure into the correct hashtable entry.
2965 * Note we assume that the hashtable entry either doesn't exist yet,
2966 * or we already cleared its proc_ptr during the validation attempts
2967 * above. So no need to decrement an old refcount here.
2968 ************************************************************/
2969 proc_key.user_id = prodesc->lanpltrusted ? GetUserId() : InvalidOid;
2971 proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2973 /* We assume these two steps can't throw an error: */
2974 proc_ptr->proc_ptr = prodesc;
2975 increment_prodesc_refcount(prodesc);
2980 * If we got as far as creating a reference, we should be able to use
2981 * free_plperl_function() to clean up. If not, then at most we have
2982 * some PG memory resources in proc_cxt, which we can just delete.
2984 if (prodesc && prodesc->reference)
2985 free_plperl_function(prodesc);
2987 MemoryContextDelete(proc_cxt);
2989 /* Be sure to restore the previous interpreter, too, for luck */
2990 activate_interpreter(oldinterp);
2996 /* restore previous error callback */
2997 error_context_stack = plperl_error_context.previous;
2999 ReleaseSysCache(procTup);
3004 /* Build a hash from a given composite/row datum */
3006 plperl_hash_from_datum(Datum attr)
3012 HeapTupleData tmptup;
3015 td = DatumGetHeapTupleHeader(attr);
3017 /* Extract rowtype info and find a tupdesc */
3018 tupType = HeapTupleHeaderGetTypeId(td);
3019 tupTypmod = HeapTupleHeaderGetTypMod(td);
3020 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3022 /* Build a temporary HeapTuple control structure */
3023 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3026 sv = plperl_hash_from_tuple(&tmptup, tupdesc, true);
3027 ReleaseTupleDesc(tupdesc);
3032 /* Build a hash from all attributes of a given tuple. */
3034 plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
3040 /* since this function recurses, it could be driven to stack overflow */
3041 check_stack_depth();
3044 hv_ksplit(hv, tupdesc->natts); /* pre-grow the hash */
3046 for (i = 0; i < tupdesc->natts; i++)
3053 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3055 if (att->attisdropped)
3058 if (att->attgenerated)
3060 /* don't include unless requested */
3061 if (!include_generated)
3065 attname = NameStr(att->attname);
3066 attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3071 * Store (attname => undef) and move on. Note we can't use
3072 * &PL_sv_undef here; see "AVs, HVs and undefined values" in
3073 * perlguts for an explanation.
3075 hv_store_string(hv, attname, newSV(0));
3079 if (type_is_rowtype(att->atttypid))
3081 SV *sv = plperl_hash_from_datum(attr);
3083 hv_store_string(hv, attname, sv);
3090 if (OidIsValid(get_base_element_type(att->atttypid)))
3091 sv = plperl_ref_from_pg_array(attr, att->atttypid);
3092 else if ((funcid = get_transform_fromsql(att->atttypid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
3093 sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, attr));
3098 /* XXX should have a way to cache these lookups */
3099 getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
3101 outputstr = OidOutputFunctionCall(typoutput, attr);
3102 sv = cstr2sv(outputstr);
3106 hv_store_string(hv, attname, sv);
3109 return newRV_noinc((SV *) hv);
3114 check_spi_usage_allowed(void)
3116 /* see comment in plperl_fini() */
3119 /* simple croak as we don't want to involve PostgreSQL code */
3120 croak("SPI functions can not be used in END blocks");
3126 plperl_spi_exec(char *query, int limit)
3131 * Execute the query inside a sub-transaction, so we can cope with errors
3134 MemoryContext oldcontext = CurrentMemoryContext;
3135 ResourceOwner oldowner = CurrentResourceOwner;
3137 check_spi_usage_allowed();
3139 BeginInternalSubTransaction(NULL);
3140 /* Want to run inside function's memory context */
3141 MemoryContextSwitchTo(oldcontext);
3147 pg_verifymbstr(query, strlen(query), false);
3149 spi_rv = SPI_execute(query, current_call_data->prodesc->fn_readonly,
3151 ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
3154 /* Commit the inner transaction, return to outer xact context */
3155 ReleaseCurrentSubTransaction();
3156 MemoryContextSwitchTo(oldcontext);
3157 CurrentResourceOwner = oldowner;
3163 /* Save error info */
3164 MemoryContextSwitchTo(oldcontext);
3165 edata = CopyErrorData();
3168 /* Abort the inner transaction */
3169 RollbackAndReleaseCurrentSubTransaction();
3170 MemoryContextSwitchTo(oldcontext);
3171 CurrentResourceOwner = oldowner;
3173 /* Punt the error to Perl */
3174 croak_cstr(edata->message);
3176 /* Can't get here, but keep compiler quiet */
3186 plperl_spi_execute_fetch_result(SPITupleTable *tuptable, uint64 processed,
3192 check_spi_usage_allowed();
3196 hv_store_string(result, "status",
3197 cstr2sv(SPI_result_code_string(status)));
3198 hv_store_string(result, "processed",
3199 (processed > (uint64) UV_MAX) ?
3200 newSVnv((NV) processed) :
3201 newSVuv((UV) processed));
3203 if (status > 0 && tuptable)
3209 /* Prevent overflow in call to av_extend() */
3210 if (processed > (uint64) AV_SIZE_MAX)
3212 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3213 errmsg("query result has too many rows to fit in a Perl array")));
3216 av_extend(rows, processed);
3217 for (i = 0; i < processed; i++)
3219 row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc, true);
3222 hv_store_string(result, "rows",
3223 newRV_noinc((SV *) rows));
3226 SPI_freetuptable(tuptable);
3233 * plperl_return_next catches any error and converts it to a Perl error.
3234 * We assume (perhaps without adequate justification) that we need not abort
3235 * the current transaction if the Perl code traps the error.
3238 plperl_return_next(SV *sv)
3240 MemoryContext oldcontext = CurrentMemoryContext;
3244 plperl_return_next_internal(sv);
3250 /* Must reset elog.c's state */
3251 MemoryContextSwitchTo(oldcontext);
3252 edata = CopyErrorData();
3255 /* Punt the error to Perl */
3256 croak_cstr(edata->message);
3262 * plperl_return_next_internal reports any errors in Postgres fashion
3266 plperl_return_next_internal(SV *sv)
3268 plperl_proc_desc *prodesc;
3269 FunctionCallInfo fcinfo;
3271 MemoryContext old_cxt;
3276 prodesc = current_call_data->prodesc;
3277 fcinfo = current_call_data->fcinfo;
3278 rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3280 if (!prodesc->fn_retisset)
3282 (errcode(ERRCODE_SYNTAX_ERROR),
3283 errmsg("cannot use return_next in a non-SETOF function")));
3285 if (!current_call_data->ret_tdesc)
3289 Assert(!current_call_data->tuple_store);
3292 * This is the first call to return_next in the current PL/Perl
3293 * function call, so identify the output tuple type and create a
3294 * tuplestore to hold the result rows.
3296 if (prodesc->fn_retistuple)
3298 TypeFuncClass funcclass;
3301 funcclass = get_call_result_type(fcinfo, &typid, &tupdesc);
3302 if (funcclass != TYPEFUNC_COMPOSITE &&
3303 funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
3305 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3306 errmsg("function returning record called in context "
3307 "that cannot accept type record")));
3308 /* if domain-over-composite, remember the domain's type OID */
3309 if (funcclass == TYPEFUNC_COMPOSITE_DOMAIN)
3310 current_call_data->cdomain_oid = typid;
3314 tupdesc = rsi->expectedDesc;
3315 /* Protect assumption below that we return exactly one column */
3316 if (tupdesc == NULL || tupdesc->natts != 1)
3317 elog(ERROR, "expected single-column result descriptor for non-composite SETOF result");
3321 * Make sure the tuple_store and ret_tdesc are sufficiently
3324 old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
3326 current_call_data->ret_tdesc = CreateTupleDescCopy(tupdesc);
3327 current_call_data->tuple_store =
3328 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
3331 MemoryContextSwitchTo(old_cxt);
3335 * Producing the tuple we want to return requires making plenty of
3336 * palloc() allocations that are not cleaned up. Since this function can
3337 * be called many times before the current memory context is reset, we
3338 * need to do those allocations in a temporary context.
3340 if (!current_call_data->tmp_cxt)
3342 current_call_data->tmp_cxt =
3343 AllocSetContextCreate(CurrentMemoryContext,
3344 "PL/Perl return_next temporary cxt",
3345 ALLOCSET_DEFAULT_SIZES);
3348 old_cxt = MemoryContextSwitchTo(current_call_data->tmp_cxt);
3350 if (prodesc->fn_retistuple)
3354 if (!(SvOK(sv) && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV))
3356 (errcode(ERRCODE_DATATYPE_MISMATCH),
3357 errmsg("SETOF-composite-returning PL/Perl function "
3358 "must call return_next with reference to hash")));
3360 tuple = plperl_build_tuple_result((HV *) SvRV(sv),
3361 current_call_data->ret_tdesc);
3363 if (OidIsValid(current_call_data->cdomain_oid))
3364 domain_check(HeapTupleGetDatum(tuple), false,
3365 current_call_data->cdomain_oid,
3366 ¤t_call_data->cdomain_info,
3367 rsi->econtext->ecxt_per_query_memory);
3369 tuplestore_puttuple(current_call_data->tuple_store, tuple);
3371 else if (prodesc->result_oid)
3376 ret[0] = plperl_sv_to_datum(sv,
3377 prodesc->result_oid,
3380 &prodesc->result_in_func,
3381 prodesc->result_typioparam,
3384 tuplestore_putvalues(current_call_data->tuple_store,
3385 current_call_data->ret_tdesc,
3389 MemoryContextSwitchTo(old_cxt);
3390 MemoryContextReset(current_call_data->tmp_cxt);
3395 plperl_spi_query(char *query)
3400 * Execute the query inside a sub-transaction, so we can cope with errors
3403 MemoryContext oldcontext = CurrentMemoryContext;
3404 ResourceOwner oldowner = CurrentResourceOwner;
3406 check_spi_usage_allowed();
3408 BeginInternalSubTransaction(NULL);
3409 /* Want to run inside function's memory context */
3410 MemoryContextSwitchTo(oldcontext);
3417 /* Make sure the query is validly encoded */
3418 pg_verifymbstr(query, strlen(query), false);
3420 /* Create a cursor for the query */
3421 plan = SPI_prepare(query, 0, NULL);
3423 elog(ERROR, "SPI_prepare() failed:%s",
3424 SPI_result_code_string(SPI_result));
3426 portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
3429 elog(ERROR, "SPI_cursor_open() failed:%s",
3430 SPI_result_code_string(SPI_result));
3431 cursor = cstr2sv(portal->name);
3435 /* Commit the inner transaction, return to outer xact context */
3436 ReleaseCurrentSubTransaction();
3437 MemoryContextSwitchTo(oldcontext);
3438 CurrentResourceOwner = oldowner;
3444 /* Save error info */
3445 MemoryContextSwitchTo(oldcontext);
3446 edata = CopyErrorData();
3449 /* Abort the inner transaction */
3450 RollbackAndReleaseCurrentSubTransaction();
3451 MemoryContextSwitchTo(oldcontext);
3452 CurrentResourceOwner = oldowner;
3454 /* Punt the error to Perl */
3455 croak_cstr(edata->message);
3457 /* Can't get here, but keep compiler quiet */
3467 plperl_spi_fetchrow(char *cursor)
3472 * Execute the FETCH inside a sub-transaction, so we can cope with errors
3475 MemoryContext oldcontext = CurrentMemoryContext;
3476 ResourceOwner oldowner = CurrentResourceOwner;
3478 check_spi_usage_allowed();
3480 BeginInternalSubTransaction(NULL);
3481 /* Want to run inside function's memory context */
3482 MemoryContextSwitchTo(oldcontext);
3487 Portal p = SPI_cursor_find(cursor);
3495 SPI_cursor_fetch(p, true, 1);
3496 if (SPI_processed == 0)
3499 SPI_cursor_close(p);
3504 row = plperl_hash_from_tuple(SPI_tuptable->vals[0],
3505 SPI_tuptable->tupdesc,
3508 SPI_freetuptable(SPI_tuptable);
3511 /* Commit the inner transaction, return to outer xact context */
3512 ReleaseCurrentSubTransaction();
3513 MemoryContextSwitchTo(oldcontext);
3514 CurrentResourceOwner = oldowner;
3520 /* Save error info */
3521 MemoryContextSwitchTo(oldcontext);
3522 edata = CopyErrorData();
3525 /* Abort the inner transaction */
3526 RollbackAndReleaseCurrentSubTransaction();
3527 MemoryContextSwitchTo(oldcontext);
3528 CurrentResourceOwner = oldowner;
3530 /* Punt the error to Perl */
3531 croak_cstr(edata->message);
3533 /* Can't get here, but keep compiler quiet */
3542 plperl_spi_cursor_close(char *cursor)
3546 check_spi_usage_allowed();
3548 p = SPI_cursor_find(cursor);
3553 SPI_cursor_close(p);
3558 plperl_spi_prepare(char *query, int argc, SV **argv)
3560 volatile SPIPlanPtr plan = NULL;
3561 volatile MemoryContext plan_cxt = NULL;
3562 plperl_query_desc *volatile qdesc = NULL;
3563 plperl_query_entry *volatile hash_entry = NULL;
3564 MemoryContext oldcontext = CurrentMemoryContext;
3565 ResourceOwner oldowner = CurrentResourceOwner;
3566 MemoryContext work_cxt;
3570 check_spi_usage_allowed();
3572 BeginInternalSubTransaction(NULL);
3573 MemoryContextSwitchTo(oldcontext);
3577 CHECK_FOR_INTERRUPTS();
3579 /************************************************************
3580 * Allocate the new querydesc structure
3582 * The qdesc struct, as well as all its subsidiary data, lives in its
3583 * plan_cxt. But note that the SPIPlan does not.
3584 ************************************************************/
3585 plan_cxt = AllocSetContextCreate(TopMemoryContext,
3586 "PL/Perl spi_prepare query",
3587 ALLOCSET_SMALL_SIZES);
3588 MemoryContextSwitchTo(plan_cxt);
3589 qdesc = (plperl_query_desc *) palloc0(sizeof(plperl_query_desc));
3590 snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
3591 qdesc->plan_cxt = plan_cxt;
3592 qdesc->nargs = argc;
3593 qdesc->argtypes = (Oid *) palloc(argc * sizeof(Oid));
3594 qdesc->arginfuncs = (FmgrInfo *) palloc(argc * sizeof(FmgrInfo));
3595 qdesc->argtypioparams = (Oid *) palloc(argc * sizeof(Oid));
3596 MemoryContextSwitchTo(oldcontext);
3598 /************************************************************
3599 * Do the following work in a short-lived context so that we don't
3600 * leak a lot of memory in the PL/Perl function's SPI Proc context.
3601 ************************************************************/
3602 work_cxt = AllocSetContextCreate(CurrentMemoryContext,
3603 "PL/Perl spi_prepare workspace",
3604 ALLOCSET_DEFAULT_SIZES);
3605 MemoryContextSwitchTo(work_cxt);
3607 /************************************************************
3608 * Resolve argument type names and then look them up by oid
3609 * in the system cache, and remember the required information
3610 * for input conversion.
3611 ************************************************************/
3612 for (i = 0; i < argc; i++)
3620 typstr = sv2cstr(argv[i]);
3621 parseTypeString(typstr, &typId, &typmod, false);
3624 getTypeInputInfo(typId, &typInput, &typIOParam);
3626 qdesc->argtypes[i] = typId;
3627 fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
3628 qdesc->argtypioparams[i] = typIOParam;
3631 /* Make sure the query is validly encoded */
3632 pg_verifymbstr(query, strlen(query), false);
3634 /************************************************************
3635 * Prepare the plan and check for errors
3636 ************************************************************/
3637 plan = SPI_prepare(query, argc, qdesc->argtypes);
3640 elog(ERROR, "SPI_prepare() failed:%s",
3641 SPI_result_code_string(SPI_result));
3643 /************************************************************
3644 * Save the plan into permanent memory (right now it's in the
3645 * SPI procCxt, which will go away at function end).
3646 ************************************************************/
3647 if (SPI_keepplan(plan))
3648 elog(ERROR, "SPI_keepplan() failed");
3651 /************************************************************
3652 * Insert a hashtable entry for the plan.
3653 ************************************************************/
3654 hash_entry = hash_search(plperl_active_interp->query_hash,
3656 HASH_ENTER, &found);
3657 hash_entry->query_data = qdesc;
3659 /* Get rid of workspace */
3660 MemoryContextDelete(work_cxt);
3662 /* Commit the inner transaction, return to outer xact context */
3663 ReleaseCurrentSubTransaction();
3664 MemoryContextSwitchTo(oldcontext);
3665 CurrentResourceOwner = oldowner;
3671 /* Save error info */
3672 MemoryContextSwitchTo(oldcontext);
3673 edata = CopyErrorData();
3676 /* Drop anything we managed to allocate */
3678 hash_search(plperl_active_interp->query_hash,
3682 MemoryContextDelete(plan_cxt);
3686 /* Abort the inner transaction */
3687 RollbackAndReleaseCurrentSubTransaction();
3688 MemoryContextSwitchTo(oldcontext);
3689 CurrentResourceOwner = oldowner;
3691 /* Punt the error to Perl */
3692 croak_cstr(edata->message);
3694 /* Can't get here, but keep compiler quiet */
3699 /************************************************************
3700 * Return the query's hash key to the caller.
3701 ************************************************************/
3702 return cstr2sv(qdesc->qname);
3706 plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
3715 plperl_query_desc *qdesc;
3716 plperl_query_entry *hash_entry;
3719 * Execute the query inside a sub-transaction, so we can cope with errors
3722 MemoryContext oldcontext = CurrentMemoryContext;
3723 ResourceOwner oldowner = CurrentResourceOwner;
3725 check_spi_usage_allowed();
3727 BeginInternalSubTransaction(NULL);
3728 /* Want to run inside function's memory context */
3729 MemoryContextSwitchTo(oldcontext);
3735 /************************************************************
3736 * Fetch the saved plan descriptor, see if it's o.k.
3737 ************************************************************/
3738 hash_entry = hash_search(plperl_active_interp->query_hash, query,
3740 if (hash_entry == NULL)
3741 elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
3743 qdesc = hash_entry->query_data;
3745 elog(ERROR, "spi_exec_prepared: plperl query_hash value vanished");
3747 if (qdesc->nargs != argc)
3748 elog(ERROR, "spi_exec_prepared: expected %d argument(s), %d passed",
3749 qdesc->nargs, argc);
3751 /************************************************************
3752 * Parse eventual attributes
3753 ************************************************************/
3757 sv = hv_fetch_string(attr, "limit");
3758 if (sv && *sv && SvIOK(*sv))
3761 /************************************************************
3763 ************************************************************/
3766 nulls = (char *) palloc(argc);
3767 argvalues = (Datum *) palloc(argc * sizeof(Datum));
3775 for (i = 0; i < argc; i++)
3779 argvalues[i] = plperl_sv_to_datum(argv[i],
3783 &qdesc->arginfuncs[i],
3784 qdesc->argtypioparams[i],
3786 nulls[i] = isnull ? 'n' : ' ';
3789 /************************************************************
3791 ************************************************************/
3792 spi_rv = SPI_execute_plan(qdesc->plan, argvalues, nulls,
3793 current_call_data->prodesc->fn_readonly, limit);
3794 ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
3802 /* Commit the inner transaction, return to outer xact context */
3803 ReleaseCurrentSubTransaction();
3804 MemoryContextSwitchTo(oldcontext);
3805 CurrentResourceOwner = oldowner;
3811 /* Save error info */
3812 MemoryContextSwitchTo(oldcontext);
3813 edata = CopyErrorData();
3816 /* Abort the inner transaction */
3817 RollbackAndReleaseCurrentSubTransaction();
3818 MemoryContextSwitchTo(oldcontext);
3819 CurrentResourceOwner = oldowner;
3821 /* Punt the error to Perl */
3822 croak_cstr(edata->message);
3824 /* Can't get here, but keep compiler quiet */
3833 plperl_spi_query_prepared(char *query, int argc, SV **argv)
3838 plperl_query_desc *qdesc;
3839 plperl_query_entry *hash_entry;
3841 Portal portal = NULL;
3844 * Execute the query inside a sub-transaction, so we can cope with errors
3847 MemoryContext oldcontext = CurrentMemoryContext;
3848 ResourceOwner oldowner = CurrentResourceOwner;
3850 check_spi_usage_allowed();
3852 BeginInternalSubTransaction(NULL);
3853 /* Want to run inside function's memory context */
3854 MemoryContextSwitchTo(oldcontext);
3858 /************************************************************
3859 * Fetch the saved plan descriptor, see if it's o.k.
3860 ************************************************************/
3861 hash_entry = hash_search(plperl_active_interp->query_hash, query,
3863 if (hash_entry == NULL)
3864 elog(ERROR, "spi_query_prepared: Invalid prepared query passed");
3866 qdesc = hash_entry->query_data;
3868 elog(ERROR, "spi_query_prepared: plperl query_hash value vanished");
3870 if (qdesc->nargs != argc)
3871 elog(ERROR, "spi_query_prepared: expected %d argument(s), %d passed",
3872 qdesc->nargs, argc);
3874 /************************************************************
3876 ************************************************************/
3879 nulls = (char *) palloc(argc);
3880 argvalues = (Datum *) palloc(argc * sizeof(Datum));
3888 for (i = 0; i < argc; i++)
3892 argvalues[i] = plperl_sv_to_datum(argv[i],
3896 &qdesc->arginfuncs[i],
3897 qdesc->argtypioparams[i],
3899 nulls[i] = isnull ? 'n' : ' ';
3902 /************************************************************
3904 ************************************************************/
3905 portal = SPI_cursor_open(NULL, qdesc->plan, argvalues, nulls,
3906 current_call_data->prodesc->fn_readonly);
3913 elog(ERROR, "SPI_cursor_open() failed:%s",
3914 SPI_result_code_string(SPI_result));
3916 cursor = cstr2sv(portal->name);
3920 /* Commit the inner transaction, return to outer xact context */
3921 ReleaseCurrentSubTransaction();
3922 MemoryContextSwitchTo(oldcontext);
3923 CurrentResourceOwner = oldowner;
3929 /* Save error info */
3930 MemoryContextSwitchTo(oldcontext);
3931 edata = CopyErrorData();
3934 /* Abort the inner transaction */
3935 RollbackAndReleaseCurrentSubTransaction();
3936 MemoryContextSwitchTo(oldcontext);
3937 CurrentResourceOwner = oldowner;
3939 /* Punt the error to Perl */
3940 croak_cstr(edata->message);
3942 /* Can't get here, but keep compiler quiet */
3951 plperl_spi_freeplan(char *query)
3954 plperl_query_desc *qdesc;
3955 plperl_query_entry *hash_entry;
3957 check_spi_usage_allowed();
3959 hash_entry = hash_search(plperl_active_interp->query_hash, query,
3961 if (hash_entry == NULL)
3962 elog(ERROR, "spi_freeplan: Invalid prepared query passed");
3964 qdesc = hash_entry->query_data;
3966 elog(ERROR, "spi_freeplan: plperl query_hash value vanished");
3970 * free all memory before SPI_freeplan, so if it dies, nothing will be
3973 hash_search(plperl_active_interp->query_hash, query,
3976 MemoryContextDelete(qdesc->plan_cxt);
3982 plperl_spi_commit(void)
3984 MemoryContext oldcontext = CurrentMemoryContext;
3989 SPI_start_transaction();
3995 /* Save error info */
3996 MemoryContextSwitchTo(oldcontext);
3997 edata = CopyErrorData();
4000 /* Punt the error to Perl */
4001 croak_cstr(edata->message);
4007 plperl_spi_rollback(void)
4009 MemoryContext oldcontext = CurrentMemoryContext;
4014 SPI_start_transaction();
4020 /* Save error info */
4021 MemoryContextSwitchTo(oldcontext);
4022 edata = CopyErrorData();
4025 /* Punt the error to Perl */
4026 croak_cstr(edata->message);
4032 * Implementation of plperl's elog() function
4034 * If the error level is less than ERROR, we'll just emit the message and
4035 * return. When it is ERROR, elog() will longjmp, which we catch and
4036 * turn into a Perl croak(). Note we are assuming that elog() can't have
4037 * any internal failures that are so bad as to require a transaction abort.
4039 * The main reason this is out-of-line is to avoid conflicts between XSUB.h
4040 * and the PG_TRY macros.
4043 plperl_util_elog(int level, SV *msg)
4045 MemoryContext oldcontext = CurrentMemoryContext;
4046 char *volatile cmsg = NULL;
4050 cmsg = sv2cstr(msg);
4051 elog(level, "%s", cmsg);
4058 /* Must reset elog.c's state */
4059 MemoryContextSwitchTo(oldcontext);
4060 edata = CopyErrorData();
4066 /* Punt the error to Perl */
4067 croak_cstr(edata->message);
4073 * Store an SV into a hash table under a key that is a string assumed to be
4074 * in the current database's encoding.
4077 hv_store_string(HV *hv, const char *key, SV *val)
4084 hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4087 * hv_store() recognizes a negative klen parameter as meaning a UTF-8
4090 hlen = -(int) strlen(hkey);
4091 ret = hv_store(hv, hkey, hlen, val, 0);
4100 * Fetch an SV from a hash table under a key that is a string assumed to be
4101 * in the current database's encoding.
4104 hv_fetch_string(HV *hv, const char *key)
4111 hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4113 /* See notes in hv_store_string */
4114 hlen = -(int) strlen(hkey);
4115 ret = hv_fetch(hv, hkey, hlen, 0);
4124 * Provide function name for PL/Perl execution errors
4127 plperl_exec_callback(void *arg)
4129 char *procname = (char *) arg;
4132 errcontext("PL/Perl function \"%s\"", procname);
4136 * Provide function name for PL/Perl compilation errors
4139 plperl_compile_callback(void *arg)
4141 char *procname = (char *) arg;
4144 errcontext("compilation of PL/Perl function \"%s\"", procname);
4148 * Provide error context for the inline handler
4151 plperl_inline_callback(void *arg)
4153 errcontext("PL/Perl anonymous code block");
4158 * Perl's own setlocale(), copied from POSIX.xs
4159 * (needed because of the calls to new_*())
4163 setlocale_perl(int category, char *locale)
4166 char *RETVAL = setlocale(category, locale);
4170 #ifdef USE_LOCALE_CTYPE
4171 if (category == LC_CTYPE
4173 || category == LC_ALL
4180 if (category == LC_ALL)
4181 newctype = setlocale(LC_CTYPE, NULL);
4185 new_ctype(newctype);
4187 #endif /* USE_LOCALE_CTYPE */
4188 #ifdef USE_LOCALE_COLLATE
4189 if (category == LC_COLLATE
4191 || category == LC_ALL
4198 if (category == LC_ALL)
4199 newcoll = setlocale(LC_COLLATE, NULL);
4203 new_collate(newcoll);
4205 #endif /* USE_LOCALE_COLLATE */
4207 #ifdef USE_LOCALE_NUMERIC
4208 if (category == LC_NUMERIC
4210 || category == LC_ALL
4217 if (category == LC_ALL)
4218 newnum = setlocale(LC_NUMERIC, NULL);
4222 new_numeric(newnum);
4224 #endif /* USE_LOCALE_NUMERIC */