1 /**********************************************************************
2 * plperl.c - perl as a procedural language for PostgreSQL
4 * src/pl/plperl/plperl.c
6 **********************************************************************/
19 /* postgreSQL stuff */
20 #include "access/htup_details.h"
21 #include "access/xact.h"
22 #include "catalog/pg_language.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_proc_fn.h"
25 #include "catalog/pg_type.h"
26 #include "commands/event_trigger.h"
27 #include "commands/trigger.h"
28 #include "executor/spi.h"
30 #include "mb/pg_wchar.h"
31 #include "miscadmin.h"
32 #include "nodes/makefuncs.h"
33 #include "parser/parse_type.h"
34 #include "storage/ipc.h"
35 #include "tcop/tcopprot.h"
36 #include "utils/builtins.h"
37 #include "utils/fmgroids.h"
38 #include "utils/guc.h"
39 #include "utils/hsearch.h"
40 #include "utils/lsyscache.h"
41 #include "utils/memutils.h"
42 #include "utils/rel.h"
43 #include "utils/syscache.h"
44 #include "utils/typcache.h"
46 /* define our text domain for translations */
48 #define TEXTDOMAIN PG_TEXTDOMAIN("plperl")
52 #include "plperl_helpers.h"
54 /* string literal macros defining chunks of perl code */
55 #include "perlchunks.h"
56 /* defines PLPERL_SET_OPMASK */
57 #include "plperl_opmask.h"
59 EXTERN_C void boot_DynaLoader(pTHX_ CV *cv);
60 EXTERN_C void boot_PostgreSQL__InServer__Util(pTHX_ CV *cv);
61 EXTERN_C void boot_PostgreSQL__InServer__SPI(pTHX_ CV *cv);
65 /**********************************************************************
66 * Information associated with a Perl interpreter. We have one interpreter
67 * that is used for all plperlu (untrusted) functions. For plperl (trusted)
68 * functions, there is a separate interpreter for each effective SQL userid.
69 * (This is needed to ensure that an unprivileged user can't inject Perl code
70 * that'll be executed with the privileges of some other SQL user.)
72 * The plperl_interp_desc structs are kept in a Postgres hash table indexed
73 * by userid OID, with OID 0 used for the single untrusted interpreter.
74 * Once created, an interpreter is kept for the life of the process.
76 * We start out by creating a "held" interpreter, which we initialize
77 * only as far as we can do without deciding if it will be trusted or
78 * untrusted. Later, when we first need to run a plperl or plperlu
79 * function, we complete the initialization appropriately and move the
80 * PerlInterpreter pointer into the plperl_interp_hash hashtable. If after
81 * that we need more interpreters, we create them as needed if we can, or
82 * fail if the Perl build doesn't support multiple interpreters.
84 * The reason for all the dancing about with a held interpreter is to make
85 * it possible for people to preload a lot of Perl code at postmaster startup
86 * (using plperl.on_init) and then use that code in backends. Of course this
87 * will only work for the first interpreter created in any backend, but it's
88 * still useful with that restriction.
89 **********************************************************************/
90 typedef struct plperl_interp_desc
92 Oid user_id; /* Hash key (must be first!) */
93 PerlInterpreter *interp; /* The interpreter */
94 HTAB *query_hash; /* plperl_query_entry structs */
98 /**********************************************************************
99 * The information we cache about loaded procedures
101 * The fn_refcount field counts the struct's reference from the hash table
102 * shown below, plus one reference for each function call level that is using
103 * the struct. We can release the struct, and the associated Perl sub, when
104 * the fn_refcount goes to zero. Releasing the struct itself is done by
105 * deleting the fn_cxt, which also gets rid of all subsidiary data.
106 **********************************************************************/
107 typedef struct plperl_proc_desc
109 char *proname; /* user name of procedure */
110 MemoryContext fn_cxt; /* memory context for this procedure */
111 unsigned long fn_refcount; /* number of active references */
112 TransactionId fn_xmin; /* xmin/TID of procedure's pg_proc tuple */
113 ItemPointerData fn_tid;
114 SV *reference; /* CODE reference for Perl sub */
115 plperl_interp_desc *interp; /* interpreter it's created in */
116 bool fn_readonly; /* is function readonly (not volatile)? */
119 bool lanpltrusted; /* is it plperl, rather than plperlu? */
120 bool fn_retistuple; /* true, if function returns tuple */
121 bool fn_retisset; /* true, if function returns set */
122 bool fn_retisarray; /* true if function returns array */
123 /* Conversion info for function's result type: */
124 Oid result_oid; /* Oid of result type */
125 FmgrInfo result_in_func; /* I/O function and arg for result type */
126 Oid result_typioparam;
127 /* Per-argument info for function's argument types: */
129 FmgrInfo *arg_out_func; /* output fns for arg types */
130 bool *arg_is_rowtype; /* is each arg composite? */
131 Oid *arg_arraytype; /* InvalidOid if not an array */
134 #define increment_prodesc_refcount(prodesc) \
135 ((prodesc)->fn_refcount++)
136 #define decrement_prodesc_refcount(prodesc) \
138 Assert((prodesc)->fn_refcount > 0); \
139 if (--((prodesc)->fn_refcount) == 0) \
140 free_plperl_function(prodesc); \
143 /**********************************************************************
144 * For speedy lookup, we maintain a hash table mapping from
145 * function OID + trigger flag + user OID to plperl_proc_desc pointers.
146 * The reason the plperl_proc_desc struct isn't directly part of the hash
147 * entry is to simplify recovery from errors during compile_plperl_function.
149 * Note: if the same function is called by multiple userIDs within a session,
150 * there will be a separate plperl_proc_desc entry for each userID in the case
151 * of plperl functions, but only one entry for plperlu functions, because we
152 * set user_id = 0 for that case. If the user redeclares the same function
153 * from plperl to plperlu or vice versa, there might be multiple
154 * plperl_proc_ptr entries in the hashtable, but only one is valid.
155 **********************************************************************/
156 typedef struct plperl_proc_key
158 Oid proc_id; /* Function OID */
161 * is_trigger is really a bool, but declare as Oid to ensure this struct
162 * contains no padding
164 Oid is_trigger; /* is it a trigger function? */
165 Oid user_id; /* User calling the function, or 0 */
168 typedef struct plperl_proc_ptr
170 plperl_proc_key proc_key; /* Hash key (must be first!) */
171 plperl_proc_desc *proc_ptr;
175 * The information we cache for the duration of a single call to a
178 typedef struct plperl_call_data
180 plperl_proc_desc *prodesc;
181 FunctionCallInfo fcinfo;
182 /* remaining fields are used only in a function returning set: */
183 Tuplestorestate *tuple_store;
185 Oid cdomain_oid; /* 0 unless returning domain-over-composite */
187 MemoryContext tmp_cxt;
190 /**********************************************************************
191 * The information we cache about prepared and saved plans
192 **********************************************************************/
193 typedef struct plperl_query_desc
196 MemoryContext plan_cxt; /* context holding this struct */
200 FmgrInfo *arginfuncs;
204 /* hash table entry for query desc */
206 typedef struct plperl_query_entry
208 char query_name[NAMEDATALEN];
209 plperl_query_desc *query_data;
210 } plperl_query_entry;
212 /**********************************************************************
213 * Information for PostgreSQL - Perl array conversion.
214 **********************************************************************/
215 typedef struct plperl_array_info
218 bool elem_is_rowtype; /* 't' if element type is a rowtype */
223 FmgrInfo transform_proc;
226 /**********************************************************************
228 **********************************************************************/
230 static HTAB *plperl_interp_hash = NULL;
231 static HTAB *plperl_proc_hash = NULL;
232 static plperl_interp_desc *plperl_active_interp = NULL;
234 /* If we have an unassigned "held" interpreter, it's stored here */
235 static PerlInterpreter *plperl_held_interp = NULL;
238 static bool plperl_use_strict = false;
239 static char *plperl_on_init = NULL;
240 static char *plperl_on_plperl_init = NULL;
241 static char *plperl_on_plperlu_init = NULL;
243 static bool plperl_ending = false;
244 static OP *(*pp_require_orig) (pTHX) = NULL;
245 static char plperl_opmask[MAXO];
247 /* this is saved and restored by plperl_call_handler */
248 static plperl_call_data *current_call_data = NULL;
250 /**********************************************************************
251 * Forward declarations
252 **********************************************************************/
255 static PerlInterpreter *plperl_init_interp(void);
256 static void plperl_destroy_interp(PerlInterpreter **);
257 static void plperl_fini(int code, Datum arg);
258 static void set_interp_require(bool trusted);
260 static Datum plperl_func_handler(PG_FUNCTION_ARGS);
261 static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
262 static void plperl_event_trigger_handler(PG_FUNCTION_ARGS);
264 static void free_plperl_function(plperl_proc_desc *prodesc);
266 static plperl_proc_desc *compile_plperl_function(Oid fn_oid,
268 bool is_event_trigger);
270 static SV *plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc);
271 static SV *plperl_hash_from_datum(Datum attr);
272 static SV *plperl_ref_from_pg_array(Datum arg, Oid typid);
273 static SV *split_array(plperl_array_info *info, int first, int last, int nest);
274 static SV *make_array_ref(plperl_array_info *info, int first, int last);
275 static SV *get_perl_array_ref(SV *sv);
276 static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
277 FunctionCallInfo fcinfo,
278 FmgrInfo *finfo, Oid typioparam,
280 static void _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam);
281 static Datum plperl_array_to_datum(SV *src, Oid typid, int32 typmod);
282 static void array_to_datum_internal(AV *av, ArrayBuildState *astate,
283 int *ndims, int *dims, int cur_depth,
284 Oid arraytypid, Oid elemtypid, int32 typmod,
285 FmgrInfo *finfo, Oid typioparam);
286 static Datum plperl_hash_to_datum(SV *src, TupleDesc td);
288 static void plperl_init_shared_libs(pTHX);
289 static void plperl_trusted_init(void);
290 static void plperl_untrusted_init(void);
291 static HV *plperl_spi_execute_fetch_result(SPITupleTable *, uint64, int);
292 static void plperl_return_next_internal(SV *sv);
293 static char *hek2cstr(HE *he);
294 static SV **hv_store_string(HV *hv, const char *key, SV *val);
295 static SV **hv_fetch_string(HV *hv, const char *key);
296 static void plperl_create_sub(plperl_proc_desc *desc, const char *s, Oid fn_oid);
297 static SV *plperl_call_perl_func(plperl_proc_desc *desc,
298 FunctionCallInfo fcinfo);
299 static void plperl_compile_callback(void *arg);
300 static void plperl_exec_callback(void *arg);
301 static void plperl_inline_callback(void *arg);
302 static char *strip_trailing_ws(const char *msg);
303 static OP *pp_require_safe(pTHX);
304 static void activate_interpreter(plperl_interp_desc *interp_desc);
307 static char *setlocale_perl(int category, char *locale);
311 * Decrement the refcount of the given SV within the active Perl interpreter
313 * This is handy because it reloads the active-interpreter pointer, saving
314 * some notation in callers that switch the active interpreter.
317 SvREFCNT_dec_current(SV *sv)
325 * convert a HE (hash entry) key to a cstr in the current database encoding
335 * HeSVKEY_force will return a temporary mortal SV*, so we need to make
336 * sure to free it with ENTER/SAVE/FREE/LEAVE
341 /*-------------------------
342 * Unfortunately, while HeUTF8 is true for most things > 256, for values
343 * 128..255 it's not, but perl will treat them as unicode code points if
344 * the utf8 flag is not set ( see The "Unicode Bug" in perldoc perlunicode
347 * So if we did the expected:
350 * else // must be ascii
352 * we won't match columns with codepoints from 128..255
354 * For a more concrete example given a column with the name of the unicode
355 * codepoint U+00ae (registered sign) and a UTF8 database and the perl
356 * return_next { "\N{U+00ae}=>'text } would always fail as heUTF8 returns
357 * 0 and HePV() would give us a char * with 1 byte contains the decimal
360 * Perl has the brains to know when it should utf8 encode 174 properly, so
361 * here we force it into an SV so that perl will figure it out and do the
363 *-------------------------
366 sv = HeSVKEY_force(he);
380 * _PG_init() - library load-time initialization
382 * DO NOT make this static nor change its name!
388 * Be sure we do initialization only once.
390 * If initialization fails due to, e.g., plperl_init_interp() throwing an
391 * exception, then we'll return here on the next usage and the user will
392 * get a rather cryptic: ERROR: attempt to redefine parameter
393 * "plperl.use_strict"
395 static bool inited = false;
402 * Support localized messages.
404 pg_bindtextdomain(TEXTDOMAIN);
407 * Initialize plperl's GUCs.
409 DefineCustomBoolVariable("plperl.use_strict",
410 gettext_noop("If true, trusted and untrusted Perl code will be compiled in strict mode."),
418 * plperl.on_init is marked PGC_SIGHUP to support the idea that it might
419 * be executed in the postmaster (if plperl is loaded into the postmaster
420 * via shared_preload_libraries). This isn't really right either way,
423 DefineCustomStringVariable("plperl.on_init",
424 gettext_noop("Perl initialization code to execute when a Perl interpreter is initialized."),
432 * plperl.on_plperl_init is marked PGC_SUSET to avoid issues whereby a
433 * user who might not even have USAGE privilege on the plperl language
434 * could nonetheless use SET plperl.on_plperl_init='...' to influence the
435 * behaviour of any existing plperl function that they can execute (which
436 * might be SECURITY DEFINER, leading to a privilege escalation). See
437 * http://archives.postgresql.org/pgsql-hackers/2010-02/msg00281.php and
438 * the overall thread.
440 * Note that because plperl.use_strict is USERSET, a nefarious user could
441 * set it to be applied against other people's functions. This is judged
442 * OK since the worst result would be an error. Your code oughta pass
443 * use_strict anyway ;-)
445 DefineCustomStringVariable("plperl.on_plperl_init",
446 gettext_noop("Perl initialization code to execute once when plperl is first used."),
448 &plperl_on_plperl_init,
453 DefineCustomStringVariable("plperl.on_plperlu_init",
454 gettext_noop("Perl initialization code to execute once when plperlu is first used."),
456 &plperl_on_plperlu_init,
461 EmitWarningsOnPlaceholders("plperl");
464 * Create hash tables.
466 memset(&hash_ctl, 0, sizeof(hash_ctl));
467 hash_ctl.keysize = sizeof(Oid);
468 hash_ctl.entrysize = sizeof(plperl_interp_desc);
469 plperl_interp_hash = hash_create("PL/Perl interpreters",
472 HASH_ELEM | HASH_BLOBS);
474 memset(&hash_ctl, 0, sizeof(hash_ctl));
475 hash_ctl.keysize = sizeof(plperl_proc_key);
476 hash_ctl.entrysize = sizeof(plperl_proc_ptr);
477 plperl_proc_hash = hash_create("PL/Perl procedures",
480 HASH_ELEM | HASH_BLOBS);
483 * Save the default opmask.
485 PLPERL_SET_OPMASK(plperl_opmask);
488 * Create the first Perl interpreter, but only partially initialize it.
490 plperl_held_interp = plperl_init_interp();
497 set_interp_require(bool trusted)
501 PL_ppaddr[OP_REQUIRE] = pp_require_safe;
502 PL_ppaddr[OP_DOFILE] = pp_require_safe;
506 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
507 PL_ppaddr[OP_DOFILE] = pp_require_orig;
512 * Cleanup perl interpreters, including running END blocks.
513 * Does not fully undo the actions of _PG_init() nor make it callable again.
516 plperl_fini(int code, Datum arg)
518 HASH_SEQ_STATUS hash_seq;
519 plperl_interp_desc *interp_desc;
521 elog(DEBUG3, "plperl_fini");
524 * Indicate that perl is terminating. Disables use of spi_* functions when
525 * running END/DESTROY code. See check_spi_usage_allowed(). Could be
526 * enabled in future, with care, using a transaction
527 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02743.php
529 plperl_ending = true;
531 /* Only perform perl cleanup if we're exiting cleanly */
534 elog(DEBUG3, "plperl_fini: skipped");
538 /* Zap the "held" interpreter, if we still have it */
539 plperl_destroy_interp(&plperl_held_interp);
541 /* Zap any fully-initialized interpreters */
542 hash_seq_init(&hash_seq, plperl_interp_hash);
543 while ((interp_desc = hash_seq_search(&hash_seq)) != NULL)
545 if (interp_desc->interp)
547 activate_interpreter(interp_desc);
548 plperl_destroy_interp(&interp_desc->interp);
552 elog(DEBUG3, "plperl_fini: done");
557 * Select and activate an appropriate Perl interpreter.
560 select_perl_context(bool trusted)
563 plperl_interp_desc *interp_desc;
565 PerlInterpreter *interp = NULL;
567 /* Find or create the interpreter hashtable entry for this userid */
569 user_id = GetUserId();
571 user_id = InvalidOid;
573 interp_desc = hash_search(plperl_interp_hash, &user_id,
578 /* Initialize newly-created hashtable entry */
579 interp_desc->interp = NULL;
580 interp_desc->query_hash = NULL;
583 /* Make sure we have a query_hash for this interpreter */
584 if (interp_desc->query_hash == NULL)
588 memset(&hash_ctl, 0, sizeof(hash_ctl));
589 hash_ctl.keysize = NAMEDATALEN;
590 hash_ctl.entrysize = sizeof(plperl_query_entry);
591 interp_desc->query_hash = hash_create("PL/Perl queries",
598 * Quick exit if already have an interpreter
600 if (interp_desc->interp)
602 activate_interpreter(interp_desc);
607 * adopt held interp if free, else create new one if possible
609 if (plperl_held_interp != NULL)
611 /* first actual use of a perl interpreter */
612 interp = plperl_held_interp;
615 * Reset the plperl_held_interp pointer first; if we fail during init
616 * we don't want to try again with the partially-initialized interp.
618 plperl_held_interp = NULL;
621 plperl_trusted_init();
623 plperl_untrusted_init();
625 /* successfully initialized, so arrange for cleanup */
626 on_proc_exit(plperl_fini, 0);
633 * plperl_init_interp will change Perl's idea of the active
634 * interpreter. Reset plperl_active_interp temporarily, so that if we
635 * hit an error partway through here, we'll make sure to switch back
636 * to a non-broken interpreter before running any other Perl
639 plperl_active_interp = NULL;
641 /* Now build the new interpreter */
642 interp = plperl_init_interp();
645 plperl_trusted_init();
647 plperl_untrusted_init();
650 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
651 errmsg("cannot allocate multiple Perl interpreters on this platform")));
655 set_interp_require(trusted);
658 * Since the timing of first use of PL/Perl can't be predicted, any
659 * database interaction during initialization is problematic. Including,
660 * but not limited to, security definer issues. So we only enable access
661 * to the database AFTER on_*_init code has run. See
662 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02669.php
667 newXS("PostgreSQL::InServer::SPI::bootstrap",
668 boot_PostgreSQL__InServer__SPI, __FILE__);
670 eval_pv("PostgreSQL::InServer::SPI::bootstrap()", FALSE);
673 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
674 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
675 errcontext("while executing PostgreSQL::InServer::SPI::bootstrap")));
678 /* Fully initialized, so mark the hashtable entry valid */
679 interp_desc->interp = interp;
681 /* And mark this as the active interpreter */
682 plperl_active_interp = interp_desc;
686 * Make the specified interpreter the active one
688 * A call with NULL does nothing. This is so that "restoring" to a previously
689 * null state of plperl_active_interp doesn't result in useless thrashing.
692 activate_interpreter(plperl_interp_desc *interp_desc)
694 if (interp_desc && plperl_active_interp != interp_desc)
696 Assert(interp_desc->interp);
697 PERL_SET_CONTEXT(interp_desc->interp);
698 /* trusted iff user_id isn't InvalidOid */
699 set_interp_require(OidIsValid(interp_desc->user_id));
700 plperl_active_interp = interp_desc;
705 * Create a new Perl interpreter.
707 * We initialize the interpreter as far as we can without knowing whether
708 * it will become a trusted or untrusted interpreter; in particular, the
709 * plperl.on_init code will get executed. Later, either plperl_trusted_init
710 * or plperl_untrusted_init must be called to complete the initialization.
712 static PerlInterpreter *
713 plperl_init_interp(void)
715 PerlInterpreter *plperl;
717 static char *embedding[3 + 2] = {
718 "", "-e", PLC_PERLBOOT
725 * The perl library on startup does horrible things like call
726 * setlocale(LC_ALL,""). We have protected against that on most platforms
727 * by setting the environment appropriately. However, on Windows,
728 * setlocale() does not consult the environment, so we need to save the
729 * existing locale settings before perl has a chance to mangle them and
730 * restore them after its dirty deeds are done.
733 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_locale.asp
735 * It appears that we only need to do this on interpreter startup, and
736 * subsequent calls to the interpreter don't mess with the locale
739 * We restore them using setlocale_perl(), defined below, so that Perl
740 * doesn't have a different idea of the locale from Postgres.
751 loc = setlocale(LC_COLLATE, NULL);
752 save_collate = loc ? pstrdup(loc) : NULL;
753 loc = setlocale(LC_CTYPE, NULL);
754 save_ctype = loc ? pstrdup(loc) : NULL;
755 loc = setlocale(LC_MONETARY, NULL);
756 save_monetary = loc ? pstrdup(loc) : NULL;
757 loc = setlocale(LC_NUMERIC, NULL);
758 save_numeric = loc ? pstrdup(loc) : NULL;
759 loc = setlocale(LC_TIME, NULL);
760 save_time = loc ? pstrdup(loc) : NULL;
762 #define PLPERL_RESTORE_LOCALE(name, saved) \
764 if (saved != NULL) { setlocale_perl(name, saved); pfree(saved); } \
768 if (plperl_on_init && *plperl_on_init)
770 embedding[nargs++] = "-e";
771 embedding[nargs++] = plperl_on_init;
775 * The perl API docs state that PERL_SYS_INIT3 should be called before
776 * allocating interpreters. Unfortunately, on some platforms this fails in
777 * the Perl_do_taint() routine, which is called when the platform is using
778 * the system's malloc() instead of perl's own. Other platforms, notably
779 * Windows, fail if PERL_SYS_INIT3 is not called. So we call it if it's
780 * available, unless perl is using the system malloc(), which is true when
783 #if defined(PERL_SYS_INIT3) && !defined(MYMALLOC)
785 static int perl_sys_init_done;
787 /* only call this the first time through, as per perlembed man page */
788 if (!perl_sys_init_done)
790 char *dummy_env[1] = {NULL};
792 PERL_SYS_INIT3(&nargs, (char ***) &embedding, (char ***) &dummy_env);
795 * For unclear reasons, PERL_SYS_INIT3 sets the SIGFPE handler to
796 * SIG_IGN. Aside from being extremely unfriendly behavior for a
797 * library, this is dumb on the grounds that the results of a
798 * SIGFPE in this state are undefined according to POSIX, and in
799 * fact you get a forced process kill at least on Linux. Hence,
800 * restore the SIGFPE handler to the backend's standard setting.
801 * (See Perl bug 114574 for more information.)
803 pqsignal(SIGFPE, FloatExceptionHandler);
805 perl_sys_init_done = 1;
806 /* quiet warning if PERL_SYS_INIT3 doesn't use the third argument */
812 plperl = perl_alloc();
814 elog(ERROR, "could not allocate Perl interpreter");
816 PERL_SET_CONTEXT(plperl);
817 perl_construct(plperl);
820 * Run END blocks in perl_destruct instead of perl_run. Note that dTHX
821 * loads up a pointer to the current interpreter, so we have to postpone
822 * it to here rather than put it at the function head.
827 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
830 * Record the original function for the 'require' and 'dofile'
831 * opcodes. (They share the same implementation.) Ensure it's used
832 * for new interpreters.
834 if (!pp_require_orig)
835 pp_require_orig = PL_ppaddr[OP_REQUIRE];
838 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
839 PL_ppaddr[OP_DOFILE] = pp_require_orig;
842 #ifdef PLPERL_ENABLE_OPMASK_EARLY
845 * For regression testing to prove that the PLC_PERLBOOT and
846 * PLC_TRUSTED code doesn't even compile any unsafe ops. In future
847 * there may be a valid need for them to do so, in which case this
848 * could be softened (perhaps moved to plperl_trusted_init()) or
851 PL_op_mask = plperl_opmask;
854 if (perl_parse(plperl, plperl_init_shared_libs,
855 nargs, embedding, NULL) != 0)
857 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
858 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
859 errcontext("while parsing Perl initialization")));
861 if (perl_run(plperl) != 0)
863 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
864 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
865 errcontext("while running Perl initialization")));
867 #ifdef PLPERL_RESTORE_LOCALE
868 PLPERL_RESTORE_LOCALE(LC_COLLATE, save_collate);
869 PLPERL_RESTORE_LOCALE(LC_CTYPE, save_ctype);
870 PLPERL_RESTORE_LOCALE(LC_MONETARY, save_monetary);
871 PLPERL_RESTORE_LOCALE(LC_NUMERIC, save_numeric);
872 PLPERL_RESTORE_LOCALE(LC_TIME, save_time);
881 * Our safe implementation of the require opcode.
882 * This is safe because it's completely unable to load any code.
883 * If the requested file/module has already been loaded it'll return true.
885 * So now "use Foo;" will work iff Foo has already been loaded.
888 pp_require_safe(pTHX)
898 name = SvPV(sv, len);
899 if (!(name && len > 0 && *name))
902 svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
903 if (svp && *svp != &PL_sv_undef)
906 DIE(aTHX_ "Unable to load %s into plperl", name);
909 * In most Perl versions, DIE() expands to a return statement, so the next
910 * line is not necessary. But in versions between but not including
911 * 5.11.1 and 5.13.3 it does not, so the next line is necessary to avoid a
912 * "control reaches end of non-void function" warning from gcc. Other
913 * compilers such as Solaris Studio will, however, issue a "statement not
914 * reached" warning instead.
921 * Destroy one Perl interpreter ... actually we just run END blocks.
923 * Caller must have ensured this interpreter is the active one.
926 plperl_destroy_interp(PerlInterpreter **interp)
928 if (interp && *interp)
931 * Only a very minimal destruction is performed: - just call END
934 * We could call perl_destruct() but we'd need to audit its actions
935 * very carefully and work-around any that impact us. (Calling
936 * sv_clean_objs() isn't an option because it's not part of perl's
937 * public API so isn't portably available.) Meanwhile END blocks can
938 * be used to perform manual cleanup.
942 /* Run END blocks - based on perl's perl_destruct() */
943 if (PL_exit_flags & PERL_EXIT_DESTRUCT_END)
950 if (PL_endav && !PL_minus_c)
951 call_list(PL_scopestack_ix, PL_endav);
962 * Initialize the current Perl interpreter as a trusted interp
965 plperl_trusted_init(void)
973 /* use original require while we set up */
974 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
975 PL_ppaddr[OP_DOFILE] = pp_require_orig;
977 eval_pv(PLC_TRUSTED, FALSE);
980 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
981 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
982 errcontext("while executing PLC_TRUSTED")));
985 * Force loading of utf8 module now to prevent errors that can arise from
986 * the regex code later trying to load utf8 modules. See
987 * http://rt.perl.org/rt3/Ticket/Display.html?id=47576
989 eval_pv("my $a=chr(0x100); return $a =~ /\\xa9/i", FALSE);
992 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
993 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
994 errcontext("while executing utf8fix")));
997 * Lock down the interpreter
1000 /* switch to the safe require/dofile opcode for future code */
1001 PL_ppaddr[OP_REQUIRE] = pp_require_safe;
1002 PL_ppaddr[OP_DOFILE] = pp_require_safe;
1005 * prevent (any more) unsafe opcodes being compiled PL_op_mask is per
1006 * interpreter, so this only needs to be set once
1008 PL_op_mask = plperl_opmask;
1010 /* delete the DynaLoader:: namespace so extensions can't be loaded */
1011 stash = gv_stashpv("DynaLoader", GV_ADDWARN);
1013 while ((sv = hv_iternextsv(stash, &key, &klen)))
1015 if (!isGV_with_GP(sv) || !GvCV(sv))
1017 SvREFCNT_dec(GvCV(sv)); /* free the CV */
1018 GvCV_set(sv, NULL); /* prevent call via GV */
1022 /* invalidate assorted caches */
1023 ++PL_sub_generation;
1024 hv_clear(PL_stashcache);
1027 * Execute plperl.on_plperl_init in the locked-down interpreter
1029 if (plperl_on_plperl_init && *plperl_on_plperl_init)
1031 eval_pv(plperl_on_plperl_init, FALSE);
1032 /* XXX need to find a way to determine a better errcode here */
1035 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1036 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
1037 errcontext("while executing plperl.on_plperl_init")));
1043 * Initialize the current Perl interpreter as an untrusted interp
1046 plperl_untrusted_init(void)
1051 * Nothing to do except execute plperl.on_plperlu_init
1053 if (plperl_on_plperlu_init && *plperl_on_plperlu_init)
1055 eval_pv(plperl_on_plperlu_init, FALSE);
1058 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1059 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
1060 errcontext("while executing plperl.on_plperlu_init")));
1066 * Perl likes to put a newline after its error messages; clean up such
1069 strip_trailing_ws(const char *msg)
1071 char *res = pstrdup(msg);
1072 int len = strlen(res);
1074 while (len > 0 && isspace((unsigned char) res[len - 1]))
1080 /* Build a tuple from a hash. */
1083 plperl_build_tuple_result(HV *perlhash, TupleDesc td)
1091 values = palloc0(sizeof(Datum) * td->natts);
1092 nulls = palloc(sizeof(bool) * td->natts);
1093 memset(nulls, true, sizeof(bool) * td->natts);
1095 hv_iterinit(perlhash);
1096 while ((he = hv_iternext(perlhash)))
1098 SV *val = HeVAL(he);
1099 char *key = hek2cstr(he);
1100 int attn = SPI_fnumber(td, key);
1101 Form_pg_attribute attr = TupleDescAttr(td, attn - 1);
1103 if (attn == SPI_ERROR_NOATTRIBUTE)
1105 (errcode(ERRCODE_UNDEFINED_COLUMN),
1106 errmsg("Perl hash contains nonexistent column \"%s\"",
1110 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1111 errmsg("cannot set system attribute \"%s\"",
1114 values[attn - 1] = plperl_sv_to_datum(val,
1124 hv_iterinit(perlhash);
1126 tup = heap_form_tuple(td, values, nulls);
1132 /* convert a hash reference to a datum */
1134 plperl_hash_to_datum(SV *src, TupleDesc td)
1136 HeapTuple tup = plperl_build_tuple_result((HV *) SvRV(src), td);
1138 return HeapTupleGetDatum(tup);
1142 * if we are an array ref return the reference. this is special in that if we
1143 * are a PostgreSQL::InServer::ARRAY object we will return the 'magic' array.
1146 get_perl_array_ref(SV *sv)
1150 if (SvOK(sv) && SvROK(sv))
1152 if (SvTYPE(SvRV(sv)) == SVt_PVAV)
1154 else if (sv_isa(sv, "PostgreSQL::InServer::ARRAY"))
1156 HV *hv = (HV *) SvRV(sv);
1157 SV **sav = hv_fetch_string(hv, "array");
1159 if (*sav && SvOK(*sav) && SvROK(*sav) &&
1160 SvTYPE(SvRV(*sav)) == SVt_PVAV)
1163 elog(ERROR, "could not get array reference from PostgreSQL::InServer::ARRAY object");
1170 * helper function for plperl_array_to_datum, recurses for multi-D arrays
1173 array_to_datum_internal(AV *av, ArrayBuildState *astate,
1174 int *ndims, int *dims, int cur_depth,
1175 Oid arraytypid, Oid elemtypid, int32 typmod,
1176 FmgrInfo *finfo, Oid typioparam)
1180 int len = av_len(av) + 1;
1182 for (i = 0; i < len; i++)
1184 /* fetch the array element */
1185 SV **svp = av_fetch(av, i, FALSE);
1187 /* see if this element is an array, if so get that */
1188 SV *sav = svp ? get_perl_array_ref(*svp) : NULL;
1190 /* multi-dimensional array? */
1193 AV *nav = (AV *) SvRV(sav);
1195 /* dimensionality checks */
1196 if (cur_depth + 1 > MAXDIM)
1198 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1199 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
1200 cur_depth + 1, MAXDIM)));
1202 /* set size when at first element in this level, else compare */
1203 if (i == 0 && *ndims == cur_depth)
1205 dims[*ndims] = av_len(nav) + 1;
1208 else if (av_len(nav) + 1 != dims[cur_depth])
1210 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1211 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1213 /* recurse to fetch elements of this sub-array */
1214 array_to_datum_internal(nav, astate,
1215 ndims, dims, cur_depth + 1,
1216 arraytypid, elemtypid, typmod,
1224 /* scalar after some sub-arrays at same level? */
1225 if (*ndims != cur_depth)
1227 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1228 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1230 dat = plperl_sv_to_datum(svp ? *svp : NULL,
1238 (void) accumArrayResult(astate, dat, isnull,
1239 elemtypid, CurrentMemoryContext);
1245 * convert perl array ref to a datum
1248 plperl_array_to_datum(SV *src, Oid typid, int32 typmod)
1251 ArrayBuildState *astate;
1260 elemtypid = get_element_type(typid);
1263 (errcode(ERRCODE_DATATYPE_MISMATCH),
1264 errmsg("cannot convert Perl array to non-array type %s",
1265 format_type_be(typid))));
1267 astate = initArrayResult(elemtypid, CurrentMemoryContext, true);
1269 _sv_to_datum_finfo(elemtypid, &finfo, &typioparam);
1271 memset(dims, 0, sizeof(dims));
1272 dims[0] = av_len((AV *) SvRV(src)) + 1;
1274 array_to_datum_internal((AV *) SvRV(src), astate,
1276 typid, elemtypid, typmod,
1277 &finfo, typioparam);
1279 /* ensure we get zero-D array for no inputs, as per PG convention */
1283 for (i = 0; i < ndims; i++)
1286 return makeMdArrayResult(astate, ndims, dims, lbs,
1287 CurrentMemoryContext, true);
1290 /* Get the information needed to convert data to the specified PG type */
1292 _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam)
1296 /* XXX would be better to cache these lookups */
1297 getTypeInputInfo(typid,
1298 &typinput, typioparam);
1299 fmgr_info(typinput, finfo);
1303 * convert Perl SV to PG datum of type typid, typmod typmod
1305 * Pass the PL/Perl function's fcinfo when attempting to convert to the
1306 * function's result type; otherwise pass NULL. This is used when we need to
1307 * resolve the actual result type of a function returning RECORD.
1309 * finfo and typioparam should be the results of _sv_to_datum_finfo for the
1310 * given typid, or NULL/InvalidOid to let this function do the lookups.
1312 * *isnull is an output parameter.
1315 plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
1316 FunctionCallInfo fcinfo,
1317 FmgrInfo *finfo, Oid typioparam,
1323 /* we might recurse */
1324 check_stack_depth();
1329 * Return NULL if result is undef, or if we're in a function returning
1330 * VOID. In the latter case, we should pay no attention to the last Perl
1331 * statement's result, and this is a convenient means to ensure that.
1333 if (!sv || !SvOK(sv) || typid == VOIDOID)
1335 /* look up type info if they did not pass it */
1338 _sv_to_datum_finfo(typid, &tmp, &typioparam);
1342 /* must call typinput in case it wants to reject NULL */
1343 return InputFunctionCall(finfo, NULL, typioparam, typmod);
1345 else if ((funcid = get_transform_tosql(typid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
1346 return OidFunctionCall1(funcid, PointerGetDatum(sv));
1349 /* handle references */
1350 SV *sav = get_perl_array_ref(sv);
1354 /* handle an arrayref */
1355 return plperl_array_to_datum(sav, typid, typmod);
1357 else if (SvTYPE(SvRV(sv)) == SVt_PVHV)
1359 /* handle a hashref */
1364 if (!type_is_rowtype(typid))
1366 (errcode(ERRCODE_DATATYPE_MISMATCH),
1367 errmsg("cannot convert Perl hash to non-composite type %s",
1368 format_type_be(typid))));
1370 td = lookup_rowtype_tupdesc_domain(typid, typmod, true);
1373 /* Did we look through a domain? */
1374 isdomain = (typid != td->tdtypeid);
1378 /* Must be RECORD, try to resolve based on call info */
1379 TypeFuncClass funcclass;
1382 funcclass = get_call_result_type(fcinfo, &typid, &td);
1384 funcclass = TYPEFUNC_OTHER;
1385 if (funcclass != TYPEFUNC_COMPOSITE &&
1386 funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
1388 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1389 errmsg("function returning record called in context "
1390 "that cannot accept type record")));
1392 isdomain = (funcclass == TYPEFUNC_COMPOSITE_DOMAIN);
1395 ret = plperl_hash_to_datum(sv, td);
1398 domain_check(ret, false, typid, NULL, NULL);
1400 /* Release on the result of get_call_result_type is harmless */
1401 ReleaseTupleDesc(td);
1406 /* Reference, but not reference to hash or array ... */
1408 (errcode(ERRCODE_DATATYPE_MISMATCH),
1409 errmsg("PL/Perl function must return reference to hash or array")));
1410 return (Datum) 0; /* shut up compiler */
1414 /* handle a string/number */
1416 char *str = sv2cstr(sv);
1418 /* did not pass in any typeinfo? look it up */
1421 _sv_to_datum_finfo(typid, &tmp, &typioparam);
1425 ret = InputFunctionCall(finfo, str, typioparam, typmod);
1432 /* Convert the perl SV to a string returned by the type output function */
1434 plperl_sv_to_literal(SV *sv, char *fqtypename)
1436 Datum str = CStringGetDatum(fqtypename);
1437 Oid typid = DirectFunctionCall1(regtypein, str);
1443 if (!OidIsValid(typid))
1445 (errcode(ERRCODE_UNDEFINED_OBJECT),
1446 errmsg("lookup failed for type %s", fqtypename)));
1448 datum = plperl_sv_to_datum(sv,
1450 NULL, NULL, InvalidOid,
1456 getTypeOutputInfo(typid,
1457 &typoutput, &typisvarlena);
1459 return OidOutputFunctionCall(typoutput, datum);
1463 * Convert PostgreSQL array datum to a perl array reference.
1465 * typid is arg's OID, which must be an array type.
1468 plperl_ref_from_pg_array(Datum arg, Oid typid)
1471 ArrayType *ar = DatumGetArrayTypeP(arg);
1472 Oid elementtype = ARR_ELEMTYPE(ar);
1479 Oid transform_funcid;
1483 plperl_array_info *info;
1488 * Currently we make no effort to cache any of the stuff we look up here,
1491 info = palloc0(sizeof(plperl_array_info));
1493 /* get element type information, including output conversion function */
1494 get_type_io_data(elementtype, IOFunc_output,
1495 &typlen, &typbyval, &typalign,
1496 &typdelim, &typioparam, &typoutputfunc);
1498 /* Check for a transform function */
1499 transform_funcid = get_transform_fromsql(elementtype,
1500 current_call_data->prodesc->lang_oid,
1501 current_call_data->prodesc->trftypes);
1503 /* Look up transform or output function as appropriate */
1504 if (OidIsValid(transform_funcid))
1505 fmgr_info(transform_funcid, &info->transform_proc);
1507 fmgr_info(typoutputfunc, &info->proc);
1509 info->elem_is_rowtype = type_is_rowtype(elementtype);
1511 /* Get the number and bounds of array dimensions */
1512 info->ndims = ARR_NDIM(ar);
1513 dims = ARR_DIMS(ar);
1515 /* No dimensions? Return an empty array */
1516 if (info->ndims == 0)
1518 av = newRV_noinc((SV *) newAV());
1522 deconstruct_array(ar, elementtype, typlen, typbyval,
1523 typalign, &info->elements, &info->nulls,
1526 /* Get total number of elements in each dimension */
1527 info->nelems = palloc(sizeof(int) * info->ndims);
1528 info->nelems[0] = nitems;
1529 for (i = 1; i < info->ndims; i++)
1530 info->nelems[i] = info->nelems[i - 1] / dims[i - 1];
1532 av = split_array(info, 0, nitems, 0);
1536 (void) hv_store(hv, "array", 5, av, 0);
1537 (void) hv_store(hv, "typeoid", 7, newSVuv(typid), 0);
1539 return sv_bless(newRV_noinc((SV *) hv),
1540 gv_stashpv("PostgreSQL::InServer::ARRAY", 0));
1544 * Recursively form array references from splices of the initial array
1547 split_array(plperl_array_info *info, int first, int last, int nest)
1553 /* we should only be called when we have something to split */
1554 Assert(info->ndims > 0);
1556 /* since this function recurses, it could be driven to stack overflow */
1557 check_stack_depth();
1560 * Base case, return a reference to a single-dimensional array
1562 if (nest >= info->ndims - 1)
1563 return make_array_ref(info, first, last);
1566 for (i = first; i < last; i += info->nelems[nest + 1])
1568 /* Recursively form references to arrays of lower dimensions */
1569 SV *ref = split_array(info, i, i + info->nelems[nest + 1], nest + 1);
1571 av_push(result, ref);
1573 return newRV_noinc((SV *) result);
1577 * Create a Perl reference from a one-dimensional C array, converting
1578 * composite type elements to hash references.
1581 make_array_ref(plperl_array_info *info, int first, int last)
1585 AV *result = newAV();
1587 for (i = first; i < last; i++)
1592 * We can't use &PL_sv_undef here. See "AVs, HVs and undefined
1593 * values" in perlguts.
1595 av_push(result, newSV(0));
1599 Datum itemvalue = info->elements[i];
1601 if (info->transform_proc.fn_oid)
1602 av_push(result, (SV *) DatumGetPointer(FunctionCall1(&info->transform_proc, itemvalue)));
1603 else if (info->elem_is_rowtype)
1604 /* Handle composite type elements */
1605 av_push(result, plperl_hash_from_datum(itemvalue));
1608 char *val = OutputFunctionCall(&info->proc, itemvalue);
1610 av_push(result, cstr2sv(val));
1614 return newRV_noinc((SV *) result);
1617 /* Set up the arguments for a trigger call. */
1619 plperl_trigger_build_args(FunctionCallInfo fcinfo)
1632 hv_ksplit(hv, 12); /* pre-grow the hash */
1634 tdata = (TriggerData *) fcinfo->context;
1635 tupdesc = tdata->tg_relation->rd_att;
1637 relid = DatumGetCString(
1638 DirectFunctionCall1(oidout,
1639 ObjectIdGetDatum(tdata->tg_relation->rd_id)
1643 hv_store_string(hv, "name", cstr2sv(tdata->tg_trigger->tgname));
1644 hv_store_string(hv, "relid", cstr2sv(relid));
1646 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
1649 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1650 hv_store_string(hv, "new",
1651 plperl_hash_from_tuple(tdata->tg_trigtuple,
1654 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
1657 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1658 hv_store_string(hv, "old",
1659 plperl_hash_from_tuple(tdata->tg_trigtuple,
1662 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
1665 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1667 hv_store_string(hv, "old",
1668 plperl_hash_from_tuple(tdata->tg_trigtuple,
1670 hv_store_string(hv, "new",
1671 plperl_hash_from_tuple(tdata->tg_newtuple,
1675 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
1680 hv_store_string(hv, "event", cstr2sv(event));
1681 hv_store_string(hv, "argc", newSViv(tdata->tg_trigger->tgnargs));
1683 if (tdata->tg_trigger->tgnargs > 0)
1687 av_extend(av, tdata->tg_trigger->tgnargs);
1688 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
1689 av_push(av, cstr2sv(tdata->tg_trigger->tgargs[i]));
1690 hv_store_string(hv, "args", newRV_noinc((SV *) av));
1693 hv_store_string(hv, "relname",
1694 cstr2sv(SPI_getrelname(tdata->tg_relation)));
1696 hv_store_string(hv, "table_name",
1697 cstr2sv(SPI_getrelname(tdata->tg_relation)));
1699 hv_store_string(hv, "table_schema",
1700 cstr2sv(SPI_getnspname(tdata->tg_relation)));
1702 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
1704 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
1706 else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
1707 when = "INSTEAD OF";
1710 hv_store_string(hv, "when", cstr2sv(when));
1712 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1714 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
1715 level = "STATEMENT";
1718 hv_store_string(hv, "level", cstr2sv(level));
1720 return newRV_noinc((SV *) hv);
1724 /* Set up the arguments for an event trigger call. */
1726 plperl_event_trigger_build_args(FunctionCallInfo fcinfo)
1729 EventTriggerData *tdata;
1734 tdata = (EventTriggerData *) fcinfo->context;
1736 hv_store_string(hv, "event", cstr2sv(tdata->event));
1737 hv_store_string(hv, "tag", cstr2sv(tdata->tag));
1739 return newRV_noinc((SV *) hv);
1742 /* Construct the modified new tuple to be returned from a trigger. */
1744 plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup)
1757 svp = hv_fetch_string(hvTD, "new");
1760 (errcode(ERRCODE_UNDEFINED_COLUMN),
1761 errmsg("$_TD->{new} does not exist")));
1762 if (!SvOK(*svp) || !SvROK(*svp) || SvTYPE(SvRV(*svp)) != SVt_PVHV)
1764 (errcode(ERRCODE_DATATYPE_MISMATCH),
1765 errmsg("$_TD->{new} is not a hash reference")));
1766 hvNew = (HV *) SvRV(*svp);
1768 tupdesc = tdata->tg_relation->rd_att;
1769 natts = tupdesc->natts;
1771 modvalues = (Datum *) palloc0(natts * sizeof(Datum));
1772 modnulls = (bool *) palloc0(natts * sizeof(bool));
1773 modrepls = (bool *) palloc0(natts * sizeof(bool));
1776 while ((he = hv_iternext(hvNew)))
1778 char *key = hek2cstr(he);
1779 SV *val = HeVAL(he);
1780 int attn = SPI_fnumber(tupdesc, key);
1781 Form_pg_attribute attr = TupleDescAttr(tupdesc, attn - 1);
1783 if (attn == SPI_ERROR_NOATTRIBUTE)
1785 (errcode(ERRCODE_UNDEFINED_COLUMN),
1786 errmsg("Perl hash contains nonexistent column \"%s\"",
1790 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1791 errmsg("cannot set system attribute \"%s\"",
1794 modvalues[attn - 1] = plperl_sv_to_datum(val,
1800 &modnulls[attn - 1]);
1801 modrepls[attn - 1] = true;
1807 rtup = heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls);
1818 * There are three externally visible pieces to plperl: plperl_call_handler,
1819 * plperl_inline_handler, and plperl_validator.
1823 * The call handler is called to run normal functions (including trigger
1824 * functions) that are defined in pg_proc.
1826 PG_FUNCTION_INFO_V1(plperl_call_handler);
1829 plperl_call_handler(PG_FUNCTION_ARGS)
1832 plperl_call_data *volatile save_call_data = current_call_data;
1833 plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1834 plperl_call_data this_call_data;
1836 /* Initialize current-call status record */
1837 MemSet(&this_call_data, 0, sizeof(this_call_data));
1838 this_call_data.fcinfo = fcinfo;
1842 current_call_data = &this_call_data;
1843 if (CALLED_AS_TRIGGER(fcinfo))
1844 retval = PointerGetDatum(plperl_trigger_handler(fcinfo));
1845 else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
1847 plperl_event_trigger_handler(fcinfo);
1851 retval = plperl_func_handler(fcinfo);
1855 current_call_data = save_call_data;
1856 activate_interpreter(oldinterp);
1857 if (this_call_data.prodesc)
1858 decrement_prodesc_refcount(this_call_data.prodesc);
1863 current_call_data = save_call_data;
1864 activate_interpreter(oldinterp);
1865 if (this_call_data.prodesc)
1866 decrement_prodesc_refcount(this_call_data.prodesc);
1871 * The inline handler runs anonymous code blocks (DO blocks).
1873 PG_FUNCTION_INFO_V1(plperl_inline_handler);
1876 plperl_inline_handler(PG_FUNCTION_ARGS)
1878 InlineCodeBlock *codeblock = (InlineCodeBlock *) PG_GETARG_POINTER(0);
1879 FunctionCallInfoData fake_fcinfo;
1881 plperl_proc_desc desc;
1882 plperl_call_data *volatile save_call_data = current_call_data;
1883 plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1884 plperl_call_data this_call_data;
1885 ErrorContextCallback pl_error_context;
1887 /* Initialize current-call status record */
1888 MemSet(&this_call_data, 0, sizeof(this_call_data));
1890 /* Set up a callback for error reporting */
1891 pl_error_context.callback = plperl_inline_callback;
1892 pl_error_context.previous = error_context_stack;
1893 pl_error_context.arg = NULL;
1894 error_context_stack = &pl_error_context;
1897 * Set up a fake fcinfo and descriptor with just enough info to satisfy
1898 * plperl_call_perl_func(). In particular note that this sets things up
1899 * with no arguments passed, and a result type of VOID.
1901 MemSet(&fake_fcinfo, 0, sizeof(fake_fcinfo));
1902 MemSet(&flinfo, 0, sizeof(flinfo));
1903 MemSet(&desc, 0, sizeof(desc));
1904 fake_fcinfo.flinfo = &flinfo;
1905 flinfo.fn_oid = InvalidOid;
1906 flinfo.fn_mcxt = CurrentMemoryContext;
1908 desc.proname = "inline_code_block";
1909 desc.fn_readonly = false;
1911 desc.lang_oid = codeblock->langOid;
1912 desc.trftypes = NIL;
1913 desc.lanpltrusted = codeblock->langIsTrusted;
1915 desc.fn_retistuple = false;
1916 desc.fn_retisset = false;
1917 desc.fn_retisarray = false;
1918 desc.result_oid = InvalidOid;
1920 desc.reference = NULL;
1922 this_call_data.fcinfo = &fake_fcinfo;
1923 this_call_data.prodesc = &desc;
1924 /* we do not bother with refcounting the fake prodesc */
1930 current_call_data = &this_call_data;
1932 if (SPI_connect_ext(codeblock->atomic ? 0 : SPI_OPT_NONATOMIC) != SPI_OK_CONNECT)
1933 elog(ERROR, "could not connect to SPI manager");
1935 select_perl_context(desc.lanpltrusted);
1937 plperl_create_sub(&desc, codeblock->source_text, 0);
1939 if (!desc.reference) /* can this happen? */
1940 elog(ERROR, "could not create internal procedure for anonymous code block");
1942 perlret = plperl_call_perl_func(&desc, &fake_fcinfo);
1944 SvREFCNT_dec_current(perlret);
1946 if (SPI_finish() != SPI_OK_FINISH)
1947 elog(ERROR, "SPI_finish() failed");
1952 SvREFCNT_dec_current(desc.reference);
1953 current_call_data = save_call_data;
1954 activate_interpreter(oldinterp);
1960 SvREFCNT_dec_current(desc.reference);
1962 current_call_data = save_call_data;
1963 activate_interpreter(oldinterp);
1965 error_context_stack = pl_error_context.previous;
1971 * The validator is called during CREATE FUNCTION to validate the function
1972 * being created/replaced. The precise behavior of the validator may be
1973 * modified by the check_function_bodies GUC.
1975 PG_FUNCTION_INFO_V1(plperl_validator);
1978 plperl_validator(PG_FUNCTION_ARGS)
1980 Oid funcoid = PG_GETARG_OID(0);
1988 bool is_trigger = false;
1989 bool is_event_trigger = false;
1992 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
1995 /* Get the new function's pg_proc entry */
1996 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
1997 if (!HeapTupleIsValid(tuple))
1998 elog(ERROR, "cache lookup failed for function %u", funcoid);
1999 proc = (Form_pg_proc) GETSTRUCT(tuple);
2001 functyptype = get_typtype(proc->prorettype);
2003 /* Disallow pseudotype result */
2004 /* except for TRIGGER, EVTTRIGGER, RECORD, or VOID */
2005 if (functyptype == TYPTYPE_PSEUDO)
2007 /* we assume OPAQUE with no arguments means a trigger */
2008 if (proc->prorettype == TRIGGEROID ||
2009 (proc->prorettype == OPAQUEOID && proc->pronargs == 0))
2011 else if (proc->prorettype == EVTTRIGGEROID)
2012 is_event_trigger = true;
2013 else if (proc->prorettype != RECORDOID &&
2014 proc->prorettype != VOIDOID)
2016 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2017 errmsg("PL/Perl functions cannot return type %s",
2018 format_type_be(proc->prorettype))));
2021 /* Disallow pseudotypes in arguments (either IN or OUT) */
2022 numargs = get_func_arg_info(tuple,
2023 &argtypes, &argnames, &argmodes);
2024 for (i = 0; i < numargs; i++)
2026 if (get_typtype(argtypes[i]) == TYPTYPE_PSEUDO &&
2027 argtypes[i] != RECORDOID)
2029 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2030 errmsg("PL/Perl functions cannot accept type %s",
2031 format_type_be(argtypes[i]))));
2034 ReleaseSysCache(tuple);
2036 /* Postpone body checks if !check_function_bodies */
2037 if (check_function_bodies)
2039 (void) compile_plperl_function(funcoid, is_trigger, is_event_trigger);
2042 /* the result of a validator is ignored */
2048 * plperlu likewise requires three externally visible functions:
2049 * plperlu_call_handler, plperlu_inline_handler, and plperlu_validator.
2050 * These are currently just aliases that send control to the plperl
2051 * handler functions, and we decide whether a particular function is
2052 * trusted or not by inspecting the actual pg_language tuple.
2055 PG_FUNCTION_INFO_V1(plperlu_call_handler);
2058 plperlu_call_handler(PG_FUNCTION_ARGS)
2060 return plperl_call_handler(fcinfo);
2063 PG_FUNCTION_INFO_V1(plperlu_inline_handler);
2066 plperlu_inline_handler(PG_FUNCTION_ARGS)
2068 return plperl_inline_handler(fcinfo);
2071 PG_FUNCTION_INFO_V1(plperlu_validator);
2074 plperlu_validator(PG_FUNCTION_ARGS)
2076 /* call plperl validator with our fcinfo so it gets our oid */
2077 return plperl_validator(fcinfo);
2082 * Uses mksafefunc/mkunsafefunc to create a subroutine whose text is
2083 * supplied in s, and returns a reference to it
2086 plperl_create_sub(plperl_proc_desc *prodesc, const char *s, Oid fn_oid)
2090 char subname[NAMEDATALEN + 40];
2091 HV *pragma_hv = newHV();
2095 sprintf(subname, "%s__%u", prodesc->proname, fn_oid);
2097 if (plperl_use_strict)
2098 hv_store_string(pragma_hv, "strict", (SV *) newAV());
2104 PUSHs(sv_2mortal(cstr2sv(subname)));
2105 PUSHs(sv_2mortal(newRV_noinc((SV *) pragma_hv)));
2108 * Use 'false' for $prolog in mkfunc, which is kept for compatibility in
2109 * case a module such as PostgreSQL::PLPerl::NYTprof replaces the function
2113 PUSHs(sv_2mortal(cstr2sv(s)));
2117 * G_KEEPERR seems to be needed here, else we don't recognize compile
2118 * errors properly. Perhaps it's because there's another level of eval
2119 * inside mksafefunc?
2121 count = perl_call_pv("PostgreSQL::InServer::mkfunc",
2122 G_SCALAR | G_EVAL | G_KEEPERR);
2127 SV *sub_rv = (SV *) POPs;
2129 if (sub_rv && SvROK(sub_rv) && SvTYPE(SvRV(sub_rv)) == SVt_PVCV)
2131 subref = newRV_inc(SvRV(sub_rv));
2141 (errcode(ERRCODE_SYNTAX_ERROR),
2142 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2146 (errcode(ERRCODE_SYNTAX_ERROR),
2147 errmsg("didn't get a CODE reference from compiling function \"%s\"",
2148 prodesc->proname)));
2150 prodesc->reference = subref;
2156 /**********************************************************************
2157 * plperl_init_shared_libs() -
2158 **********************************************************************/
2161 plperl_init_shared_libs(pTHX)
2163 char *file = __FILE__;
2165 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2166 newXS("PostgreSQL::InServer::Util::bootstrap",
2167 boot_PostgreSQL__InServer__Util, file);
2168 /* newXS for...::SPI::bootstrap is in select_perl_context() */
2173 plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
2180 Oid *argtypes = NULL;
2187 EXTEND(sp, desc->nargs);
2189 /* Get signature for true functions; inline blocks have no args. */
2190 if (fcinfo->flinfo->fn_oid)
2191 get_func_signature(fcinfo->flinfo->fn_oid, &argtypes, &nargs);
2192 Assert(nargs == desc->nargs);
2194 for (i = 0; i < desc->nargs; i++)
2196 if (fcinfo->argnull[i])
2197 PUSHs(&PL_sv_undef);
2198 else if (desc->arg_is_rowtype[i])
2200 SV *sv = plperl_hash_from_datum(fcinfo->arg[i]);
2202 PUSHs(sv_2mortal(sv));
2209 if (OidIsValid(desc->arg_arraytype[i]))
2210 sv = plperl_ref_from_pg_array(fcinfo->arg[i], desc->arg_arraytype[i]);
2211 else if ((funcid = get_transform_fromsql(argtypes[i], current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
2212 sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, fcinfo->arg[i]));
2217 tmp = OutputFunctionCall(&(desc->arg_out_func[i]),
2223 PUSHs(sv_2mortal(sv));
2228 /* Do NOT use G_KEEPERR here */
2229 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2239 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2240 errmsg("didn't get a return item from function")));
2249 /* XXX need to find a way to determine a better errcode here */
2251 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2252 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2255 retval = newSVsv(POPs);
2266 plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo,
2275 Trigger *tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
2280 TDsv = get_sv("main::_TD", 0);
2283 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2284 errmsg("couldn't fetch $_TD")));
2286 save_item(TDsv); /* local $_TD */
2290 EXTEND(sp, tg_trigger->tgnargs);
2292 for (i = 0; i < tg_trigger->tgnargs; i++)
2293 PUSHs(sv_2mortal(cstr2sv(tg_trigger->tgargs[i])));
2296 /* Do NOT use G_KEEPERR here */
2297 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2307 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2308 errmsg("didn't get a return item from trigger function")));
2317 /* XXX need to find a way to determine a better errcode here */
2319 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2320 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2323 retval = newSVsv(POPs);
2334 plperl_call_perl_event_trigger_func(plperl_proc_desc *desc,
2335 FunctionCallInfo fcinfo,
2347 TDsv = get_sv("main::_TD", 0);
2350 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2351 errmsg("couldn't fetch $_TD")));
2353 save_item(TDsv); /* local $_TD */
2359 /* Do NOT use G_KEEPERR here */
2360 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2370 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2371 errmsg("didn't get a return item from trigger function")));
2380 /* XXX need to find a way to determine a better errcode here */
2382 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2383 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2386 retval = newSVsv(POPs);
2387 (void) retval; /* silence compiler warning */
2397 plperl_func_handler(PG_FUNCTION_ARGS)
2400 plperl_proc_desc *prodesc;
2404 ErrorContextCallback pl_error_context;
2406 nonatomic = fcinfo->context &&
2407 IsA(fcinfo->context, CallContext) &&
2408 !castNode(CallContext, fcinfo->context)->atomic;
2410 if (SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0) != SPI_OK_CONNECT)
2411 elog(ERROR, "could not connect to SPI manager");
2413 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, false);
2414 current_call_data->prodesc = prodesc;
2415 increment_prodesc_refcount(prodesc);
2417 /* Set a callback for error reporting */
2418 pl_error_context.callback = plperl_exec_callback;
2419 pl_error_context.previous = error_context_stack;
2420 pl_error_context.arg = prodesc->proname;
2421 error_context_stack = &pl_error_context;
2423 rsi = (ReturnSetInfo *) fcinfo->resultinfo;
2425 if (prodesc->fn_retisset)
2427 /* Check context before allowing the call to go through */
2428 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2429 (rsi->allowedModes & SFRM_Materialize) == 0)
2431 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2432 errmsg("set-valued function called in context that "
2433 "cannot accept a set")));
2436 activate_interpreter(prodesc->interp);
2438 perlret = plperl_call_perl_func(prodesc, fcinfo);
2440 /************************************************************
2441 * Disconnect from SPI manager and then create the return
2442 * values datum (if the input function does a palloc for it
2443 * this must not be allocated in the SPI memory context
2444 * because SPI_finish would free it).
2445 ************************************************************/
2446 if (SPI_finish() != SPI_OK_FINISH)
2447 elog(ERROR, "SPI_finish() failed");
2449 if (prodesc->fn_retisset)
2454 * If the Perl function returned an arrayref, we pretend that it
2455 * called return_next() for each element of the array, to handle old
2456 * SRFs that didn't know about return_next(). Any other sort of return
2457 * value is an error, except undef which means return an empty set.
2459 sav = get_perl_array_ref(perlret);
2465 AV *rav = (AV *) SvRV(sav);
2467 while ((svp = av_fetch(rav, i, FALSE)) != NULL)
2469 plperl_return_next_internal(*svp);
2473 else if (SvOK(perlret))
2476 (errcode(ERRCODE_DATATYPE_MISMATCH),
2477 errmsg("set-returning PL/Perl function must return "
2478 "reference to array or use return_next")));
2481 rsi->returnMode = SFRM_Materialize;
2482 if (current_call_data->tuple_store)
2484 rsi->setResult = current_call_data->tuple_store;
2485 rsi->setDesc = current_call_data->ret_tdesc;
2489 else if (prodesc->result_oid)
2491 retval = plperl_sv_to_datum(perlret,
2492 prodesc->result_oid,
2495 &prodesc->result_in_func,
2496 prodesc->result_typioparam,
2499 if (fcinfo->isnull && rsi && IsA(rsi, ReturnSetInfo))
2500 rsi->isDone = ExprEndResult;
2503 /* Restore the previous error callback */
2504 error_context_stack = pl_error_context.previous;
2506 SvREFCNT_dec_current(perlret);
2513 plperl_trigger_handler(PG_FUNCTION_ARGS)
2515 plperl_proc_desc *prodesc;
2520 ErrorContextCallback pl_error_context;
2522 int rc PG_USED_FOR_ASSERTS_ONLY;
2524 /* Connect to SPI manager */
2525 if (SPI_connect() != SPI_OK_CONNECT)
2526 elog(ERROR, "could not connect to SPI manager");
2528 /* Make transition tables visible to this SPI connection */
2529 tdata = (TriggerData *) fcinfo->context;
2530 rc = SPI_register_trigger_data(tdata);
2533 /* Find or compile the function */
2534 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true, false);
2535 current_call_data->prodesc = prodesc;
2536 increment_prodesc_refcount(prodesc);
2538 /* Set a callback for error reporting */
2539 pl_error_context.callback = plperl_exec_callback;
2540 pl_error_context.previous = error_context_stack;
2541 pl_error_context.arg = prodesc->proname;
2542 error_context_stack = &pl_error_context;
2544 activate_interpreter(prodesc->interp);
2546 svTD = plperl_trigger_build_args(fcinfo);
2547 perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
2548 hvTD = (HV *) SvRV(svTD);
2550 /************************************************************
2551 * Disconnect from SPI manager and then create the return
2552 * values datum (if the input function does a palloc for it
2553 * this must not be allocated in the SPI memory context
2554 * because SPI_finish would free it).
2555 ************************************************************/
2556 if (SPI_finish() != SPI_OK_FINISH)
2557 elog(ERROR, "SPI_finish() failed");
2559 if (perlret == NULL || !SvOK(perlret))
2561 /* undef result means go ahead with original tuple */
2562 TriggerData *trigdata = ((TriggerData *) fcinfo->context);
2564 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2565 retval = (Datum) trigdata->tg_trigtuple;
2566 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2567 retval = (Datum) trigdata->tg_newtuple;
2568 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2569 retval = (Datum) trigdata->tg_trigtuple;
2570 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
2571 retval = (Datum) trigdata->tg_trigtuple;
2573 retval = (Datum) 0; /* can this happen? */
2580 tmp = sv2cstr(perlret);
2582 if (pg_strcasecmp(tmp, "SKIP") == 0)
2584 else if (pg_strcasecmp(tmp, "MODIFY") == 0)
2586 TriggerData *trigdata = (TriggerData *) fcinfo->context;
2588 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2589 trv = plperl_modify_tuple(hvTD, trigdata,
2590 trigdata->tg_trigtuple);
2591 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2592 trv = plperl_modify_tuple(hvTD, trigdata,
2593 trigdata->tg_newtuple);
2597 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2598 errmsg("ignoring modified row in DELETE trigger")));
2605 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2606 errmsg("result of PL/Perl trigger function must be undef, "
2607 "\"SKIP\", or \"MODIFY\"")));
2610 retval = PointerGetDatum(trv);
2614 /* Restore the previous error callback */
2615 error_context_stack = pl_error_context.previous;
2617 SvREFCNT_dec_current(svTD);
2619 SvREFCNT_dec_current(perlret);
2626 plperl_event_trigger_handler(PG_FUNCTION_ARGS)
2628 plperl_proc_desc *prodesc;
2630 ErrorContextCallback pl_error_context;
2632 /* Connect to SPI manager */
2633 if (SPI_connect() != SPI_OK_CONNECT)
2634 elog(ERROR, "could not connect to SPI manager");
2636 /* Find or compile the function */
2637 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, true);
2638 current_call_data->prodesc = prodesc;
2639 increment_prodesc_refcount(prodesc);
2641 /* Set a callback for error reporting */
2642 pl_error_context.callback = plperl_exec_callback;
2643 pl_error_context.previous = error_context_stack;
2644 pl_error_context.arg = prodesc->proname;
2645 error_context_stack = &pl_error_context;
2647 activate_interpreter(prodesc->interp);
2649 svTD = plperl_event_trigger_build_args(fcinfo);
2650 plperl_call_perl_event_trigger_func(prodesc, fcinfo, svTD);
2652 if (SPI_finish() != SPI_OK_FINISH)
2653 elog(ERROR, "SPI_finish() failed");
2655 /* Restore the previous error callback */
2656 error_context_stack = pl_error_context.previous;
2658 SvREFCNT_dec_current(svTD);
2663 validate_plperl_function(plperl_proc_ptr *proc_ptr, HeapTuple procTup)
2665 if (proc_ptr && proc_ptr->proc_ptr)
2667 plperl_proc_desc *prodesc = proc_ptr->proc_ptr;
2670 /************************************************************
2671 * If it's present, must check whether it's still up to date.
2672 * This is needed because CREATE OR REPLACE FUNCTION can modify the
2673 * function's pg_proc entry without changing its OID.
2674 ************************************************************/
2675 uptodate = (prodesc->fn_xmin == HeapTupleHeaderGetRawXmin(procTup->t_data) &&
2676 ItemPointerEquals(&prodesc->fn_tid, &procTup->t_self));
2681 /* Otherwise, unlink the obsoleted entry from the hashtable ... */
2682 proc_ptr->proc_ptr = NULL;
2683 /* ... and release the corresponding refcount, probably deleting it */
2684 decrement_prodesc_refcount(prodesc);
2692 free_plperl_function(plperl_proc_desc *prodesc)
2694 Assert(prodesc->fn_refcount == 0);
2695 /* Release CODE reference, if we have one, from the appropriate interp */
2696 if (prodesc->reference)
2698 plperl_interp_desc *oldinterp = plperl_active_interp;
2700 activate_interpreter(prodesc->interp);
2701 SvREFCNT_dec_current(prodesc->reference);
2702 activate_interpreter(oldinterp);
2704 /* Release all PG-owned data for this proc */
2705 MemoryContextDelete(prodesc->fn_cxt);
2709 static plperl_proc_desc *
2710 compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
2713 Form_pg_proc procStruct;
2714 plperl_proc_key proc_key;
2715 plperl_proc_ptr *proc_ptr;
2716 plperl_proc_desc *volatile prodesc = NULL;
2717 volatile MemoryContext proc_cxt = NULL;
2718 plperl_interp_desc *oldinterp = plperl_active_interp;
2719 ErrorContextCallback plperl_error_context;
2721 /* We'll need the pg_proc tuple in any case... */
2722 procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
2723 if (!HeapTupleIsValid(procTup))
2724 elog(ERROR, "cache lookup failed for function %u", fn_oid);
2725 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
2728 * Try to find function in plperl_proc_hash. The reason for this
2729 * overcomplicated-seeming lookup procedure is that we don't know whether
2730 * it's plperl or plperlu, and don't want to spend a lookup in pg_language
2733 proc_key.proc_id = fn_oid;
2734 proc_key.is_trigger = is_trigger;
2735 proc_key.user_id = GetUserId();
2736 proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2738 if (validate_plperl_function(proc_ptr, procTup))
2740 /* Found valid plperl entry */
2741 ReleaseSysCache(procTup);
2742 return proc_ptr->proc_ptr;
2745 /* If not found or obsolete, maybe it's plperlu */
2746 proc_key.user_id = InvalidOid;
2747 proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2749 if (validate_plperl_function(proc_ptr, procTup))
2751 /* Found valid plperlu entry */
2752 ReleaseSysCache(procTup);
2753 return proc_ptr->proc_ptr;
2756 /************************************************************
2757 * If we haven't found it in the hashtable, we analyze
2758 * the function's arguments and return type and store
2759 * the in-/out-functions in the prodesc block,
2760 * then we load the procedure into the Perl interpreter,
2761 * and last we create a new hashtable entry for it.
2762 ************************************************************/
2764 /* Set a callback for reporting compilation errors */
2765 plperl_error_context.callback = plperl_compile_callback;
2766 plperl_error_context.previous = error_context_stack;
2767 plperl_error_context.arg = NameStr(procStruct->proname);
2768 error_context_stack = &plperl_error_context;
2774 Form_pg_language langStruct;
2775 Form_pg_type typeStruct;
2776 Datum protrftypes_datum;
2780 MemoryContext oldcontext;
2782 /************************************************************
2783 * Allocate a context that will hold all PG data for the procedure.
2784 ************************************************************/
2785 proc_cxt = AllocSetContextCreateExtended(TopMemoryContext,
2786 NameStr(procStruct->proname),
2787 MEMCONTEXT_COPY_NAME,
2788 ALLOCSET_SMALL_SIZES);
2790 /************************************************************
2791 * Allocate and fill a new procedure description block.
2792 * struct prodesc and subsidiary data must all live in proc_cxt.
2793 ************************************************************/
2794 oldcontext = MemoryContextSwitchTo(proc_cxt);
2795 prodesc = (plperl_proc_desc *) palloc0(sizeof(plperl_proc_desc));
2796 prodesc->proname = pstrdup(NameStr(procStruct->proname));
2797 prodesc->fn_cxt = proc_cxt;
2798 prodesc->fn_refcount = 0;
2799 prodesc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
2800 prodesc->fn_tid = procTup->t_self;
2801 prodesc->nargs = procStruct->pronargs;
2802 prodesc->arg_out_func = (FmgrInfo *) palloc0(prodesc->nargs * sizeof(FmgrInfo));
2803 prodesc->arg_is_rowtype = (bool *) palloc0(prodesc->nargs * sizeof(bool));
2804 prodesc->arg_arraytype = (Oid *) palloc0(prodesc->nargs * sizeof(Oid));
2805 MemoryContextSwitchTo(oldcontext);
2807 /* Remember if function is STABLE/IMMUTABLE */
2808 prodesc->fn_readonly =
2809 (procStruct->provolatile != PROVOLATILE_VOLATILE);
2811 /* Fetch protrftypes */
2812 protrftypes_datum = SysCacheGetAttr(PROCOID, procTup,
2813 Anum_pg_proc_protrftypes, &isnull);
2814 MemoryContextSwitchTo(proc_cxt);
2815 prodesc->trftypes = isnull ? NIL : oid_array_to_list(protrftypes_datum);
2816 MemoryContextSwitchTo(oldcontext);
2818 /************************************************************
2819 * Lookup the pg_language tuple by Oid
2820 ************************************************************/
2821 langTup = SearchSysCache1(LANGOID,
2822 ObjectIdGetDatum(procStruct->prolang));
2823 if (!HeapTupleIsValid(langTup))
2824 elog(ERROR, "cache lookup failed for language %u",
2825 procStruct->prolang);
2826 langStruct = (Form_pg_language) GETSTRUCT(langTup);
2827 prodesc->lang_oid = HeapTupleGetOid(langTup);
2828 prodesc->lanpltrusted = langStruct->lanpltrusted;
2829 ReleaseSysCache(langTup);
2831 /************************************************************
2832 * Get the required information for input conversion of the
2834 ************************************************************/
2835 if (!is_trigger && !is_event_trigger)
2837 Oid rettype = procStruct->prorettype;
2839 typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettype));
2840 if (!HeapTupleIsValid(typeTup))
2841 elog(ERROR, "cache lookup failed for type %u", rettype);
2842 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2844 /* Disallow pseudotype result, except VOID or RECORD */
2845 if (typeStruct->typtype == TYPTYPE_PSEUDO)
2847 if (rettype == VOIDOID ||
2848 rettype == RECORDOID)
2850 else if (rettype == TRIGGEROID ||
2851 rettype == EVTTRIGGEROID)
2853 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2854 errmsg("trigger functions can only be called "
2858 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2859 errmsg("PL/Perl functions cannot return type %s",
2860 format_type_be(rettype))));
2863 prodesc->result_oid = rettype;
2864 prodesc->fn_retisset = procStruct->proretset;
2865 prodesc->fn_retistuple = type_is_rowtype(rettype);
2867 prodesc->fn_retisarray =
2868 (typeStruct->typlen == -1 && typeStruct->typelem);
2870 fmgr_info_cxt(typeStruct->typinput,
2871 &(prodesc->result_in_func),
2873 prodesc->result_typioparam = getTypeIOParam(typeTup);
2875 ReleaseSysCache(typeTup);
2878 /************************************************************
2879 * Get the required information for output conversion
2880 * of all procedure arguments
2881 ************************************************************/
2882 if (!is_trigger && !is_event_trigger)
2886 for (i = 0; i < prodesc->nargs; i++)
2888 Oid argtype = procStruct->proargtypes.values[i];
2890 typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype));
2891 if (!HeapTupleIsValid(typeTup))
2892 elog(ERROR, "cache lookup failed for type %u", argtype);
2893 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2895 /* Disallow pseudotype argument, except RECORD */
2896 if (typeStruct->typtype == TYPTYPE_PSEUDO &&
2897 argtype != RECORDOID)
2899 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2900 errmsg("PL/Perl functions cannot accept type %s",
2901 format_type_be(argtype))));
2903 if (type_is_rowtype(argtype))
2904 prodesc->arg_is_rowtype[i] = true;
2907 prodesc->arg_is_rowtype[i] = false;
2908 fmgr_info_cxt(typeStruct->typoutput,
2909 &(prodesc->arg_out_func[i]),
2913 /* Identify array-type arguments */
2914 if (typeStruct->typelem != 0 && typeStruct->typlen == -1)
2915 prodesc->arg_arraytype[i] = argtype;
2917 prodesc->arg_arraytype[i] = InvalidOid;
2919 ReleaseSysCache(typeTup);
2923 /************************************************************
2924 * create the text of the anonymous subroutine.
2925 * we do not use a named subroutine so that we can call directly
2926 * through the reference.
2927 ************************************************************/
2928 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
2929 Anum_pg_proc_prosrc, &isnull);
2931 elog(ERROR, "null prosrc");
2932 proc_source = TextDatumGetCString(prosrcdatum);
2934 /************************************************************
2935 * Create the procedure in the appropriate interpreter
2936 ************************************************************/
2938 select_perl_context(prodesc->lanpltrusted);
2940 prodesc->interp = plperl_active_interp;
2942 plperl_create_sub(prodesc, proc_source, fn_oid);
2944 activate_interpreter(oldinterp);
2948 if (!prodesc->reference) /* can this happen? */
2949 elog(ERROR, "could not create PL/Perl internal procedure");
2951 /************************************************************
2952 * OK, link the procedure into the correct hashtable entry.
2953 * Note we assume that the hashtable entry either doesn't exist yet,
2954 * or we already cleared its proc_ptr during the validation attempts
2955 * above. So no need to decrement an old refcount here.
2956 ************************************************************/
2957 proc_key.user_id = prodesc->lanpltrusted ? GetUserId() : InvalidOid;
2959 proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2961 /* We assume these two steps can't throw an error: */
2962 proc_ptr->proc_ptr = prodesc;
2963 increment_prodesc_refcount(prodesc);
2968 * If we got as far as creating a reference, we should be able to use
2969 * free_plperl_function() to clean up. If not, then at most we have
2970 * some PG memory resources in proc_cxt, which we can just delete.
2972 if (prodesc && prodesc->reference)
2973 free_plperl_function(prodesc);
2975 MemoryContextDelete(proc_cxt);
2977 /* Be sure to restore the previous interpreter, too, for luck */
2978 activate_interpreter(oldinterp);
2984 /* restore previous error callback */
2985 error_context_stack = plperl_error_context.previous;
2987 ReleaseSysCache(procTup);
2992 /* Build a hash from a given composite/row datum */
2994 plperl_hash_from_datum(Datum attr)
3000 HeapTupleData tmptup;
3003 td = DatumGetHeapTupleHeader(attr);
3005 /* Extract rowtype info and find a tupdesc */
3006 tupType = HeapTupleHeaderGetTypeId(td);
3007 tupTypmod = HeapTupleHeaderGetTypMod(td);
3008 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3010 /* Build a temporary HeapTuple control structure */
3011 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3014 sv = plperl_hash_from_tuple(&tmptup, tupdesc);
3015 ReleaseTupleDesc(tupdesc);
3020 /* Build a hash from all attributes of a given tuple. */
3022 plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
3028 /* since this function recurses, it could be driven to stack overflow */
3029 check_stack_depth();
3032 hv_ksplit(hv, tupdesc->natts); /* pre-grow the hash */
3034 for (i = 0; i < tupdesc->natts; i++)
3041 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3043 if (att->attisdropped)
3046 attname = NameStr(att->attname);
3047 attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3052 * Store (attname => undef) and move on. Note we can't use
3053 * &PL_sv_undef here; see "AVs, HVs and undefined values" in
3054 * perlguts for an explanation.
3056 hv_store_string(hv, attname, newSV(0));
3060 if (type_is_rowtype(att->atttypid))
3062 SV *sv = plperl_hash_from_datum(attr);
3064 hv_store_string(hv, attname, sv);
3071 if (OidIsValid(get_base_element_type(att->atttypid)))
3072 sv = plperl_ref_from_pg_array(attr, att->atttypid);
3073 else if ((funcid = get_transform_fromsql(att->atttypid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
3074 sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, attr));
3079 /* XXX should have a way to cache these lookups */
3080 getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
3082 outputstr = OidOutputFunctionCall(typoutput, attr);
3083 sv = cstr2sv(outputstr);
3087 hv_store_string(hv, attname, sv);
3090 return newRV_noinc((SV *) hv);
3095 check_spi_usage_allowed(void)
3097 /* see comment in plperl_fini() */
3100 /* simple croak as we don't want to involve PostgreSQL code */
3101 croak("SPI functions can not be used in END blocks");
3107 plperl_spi_exec(char *query, int limit)
3112 * Execute the query inside a sub-transaction, so we can cope with errors
3115 MemoryContext oldcontext = CurrentMemoryContext;
3116 ResourceOwner oldowner = CurrentResourceOwner;
3118 check_spi_usage_allowed();
3120 BeginInternalSubTransaction(NULL);
3121 /* Want to run inside function's memory context */
3122 MemoryContextSwitchTo(oldcontext);
3128 pg_verifymbstr(query, strlen(query), false);
3130 spi_rv = SPI_execute(query, current_call_data->prodesc->fn_readonly,
3132 ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
3135 /* Commit the inner transaction, return to outer xact context */
3136 ReleaseCurrentSubTransaction();
3137 MemoryContextSwitchTo(oldcontext);
3138 CurrentResourceOwner = oldowner;
3144 /* Save error info */
3145 MemoryContextSwitchTo(oldcontext);
3146 edata = CopyErrorData();
3149 /* Abort the inner transaction */
3150 RollbackAndReleaseCurrentSubTransaction();
3151 MemoryContextSwitchTo(oldcontext);
3152 CurrentResourceOwner = oldowner;
3154 /* Punt the error to Perl */
3155 croak_cstr(edata->message);
3157 /* Can't get here, but keep compiler quiet */
3167 plperl_spi_execute_fetch_result(SPITupleTable *tuptable, uint64 processed,
3173 check_spi_usage_allowed();
3177 hv_store_string(result, "status",
3178 cstr2sv(SPI_result_code_string(status)));
3179 hv_store_string(result, "processed",
3180 (processed > (uint64) UV_MAX) ?
3181 newSVnv((NV) processed) :
3182 newSVuv((UV) processed));
3184 if (status > 0 && tuptable)
3190 /* Prevent overflow in call to av_extend() */
3191 if (processed > (uint64) AV_SIZE_MAX)
3193 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3194 errmsg("query result has too many rows to fit in a Perl array")));
3197 av_extend(rows, processed);
3198 for (i = 0; i < processed; i++)
3200 row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc);
3203 hv_store_string(result, "rows",
3204 newRV_noinc((SV *) rows));
3207 SPI_freetuptable(tuptable);
3214 * plperl_return_next catches any error and converts it to a Perl error.
3215 * We assume (perhaps without adequate justification) that we need not abort
3216 * the current transaction if the Perl code traps the error.
3219 plperl_return_next(SV *sv)
3221 MemoryContext oldcontext = CurrentMemoryContext;
3225 plperl_return_next_internal(sv);
3231 /* Must reset elog.c's state */
3232 MemoryContextSwitchTo(oldcontext);
3233 edata = CopyErrorData();
3236 /* Punt the error to Perl */
3237 croak_cstr(edata->message);
3243 * plperl_return_next_internal reports any errors in Postgres fashion
3247 plperl_return_next_internal(SV *sv)
3249 plperl_proc_desc *prodesc;
3250 FunctionCallInfo fcinfo;
3252 MemoryContext old_cxt;
3257 prodesc = current_call_data->prodesc;
3258 fcinfo = current_call_data->fcinfo;
3259 rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3261 if (!prodesc->fn_retisset)
3263 (errcode(ERRCODE_SYNTAX_ERROR),
3264 errmsg("cannot use return_next in a non-SETOF function")));
3266 if (!current_call_data->ret_tdesc)
3270 Assert(!current_call_data->tuple_store);
3273 * This is the first call to return_next in the current PL/Perl
3274 * function call, so identify the output tuple type and create a
3275 * tuplestore to hold the result rows.
3277 if (prodesc->fn_retistuple)
3279 TypeFuncClass funcclass;
3282 funcclass = get_call_result_type(fcinfo, &typid, &tupdesc);
3283 if (funcclass != TYPEFUNC_COMPOSITE &&
3284 funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
3286 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3287 errmsg("function returning record called in context "
3288 "that cannot accept type record")));
3289 /* if domain-over-composite, remember the domain's type OID */
3290 if (funcclass == TYPEFUNC_COMPOSITE_DOMAIN)
3291 current_call_data->cdomain_oid = typid;
3295 tupdesc = rsi->expectedDesc;
3296 /* Protect assumption below that we return exactly one column */
3297 if (tupdesc == NULL || tupdesc->natts != 1)
3298 elog(ERROR, "expected single-column result descriptor for non-composite SETOF result");
3302 * Make sure the tuple_store and ret_tdesc are sufficiently
3305 old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
3307 current_call_data->ret_tdesc = CreateTupleDescCopy(tupdesc);
3308 current_call_data->tuple_store =
3309 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
3312 MemoryContextSwitchTo(old_cxt);
3316 * Producing the tuple we want to return requires making plenty of
3317 * palloc() allocations that are not cleaned up. Since this function can
3318 * be called many times before the current memory context is reset, we
3319 * need to do those allocations in a temporary context.
3321 if (!current_call_data->tmp_cxt)
3323 current_call_data->tmp_cxt =
3324 AllocSetContextCreate(CurrentMemoryContext,
3325 "PL/Perl return_next temporary cxt",
3326 ALLOCSET_DEFAULT_SIZES);
3329 old_cxt = MemoryContextSwitchTo(current_call_data->tmp_cxt);
3331 if (prodesc->fn_retistuple)
3335 if (!(SvOK(sv) && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV))
3337 (errcode(ERRCODE_DATATYPE_MISMATCH),
3338 errmsg("SETOF-composite-returning PL/Perl function "
3339 "must call return_next with reference to hash")));
3341 tuple = plperl_build_tuple_result((HV *) SvRV(sv),
3342 current_call_data->ret_tdesc);
3344 if (OidIsValid(current_call_data->cdomain_oid))
3345 domain_check(HeapTupleGetDatum(tuple), false,
3346 current_call_data->cdomain_oid,
3347 ¤t_call_data->cdomain_info,
3348 rsi->econtext->ecxt_per_query_memory);
3350 tuplestore_puttuple(current_call_data->tuple_store, tuple);
3352 else if (prodesc->result_oid)
3357 ret[0] = plperl_sv_to_datum(sv,
3358 prodesc->result_oid,
3361 &prodesc->result_in_func,
3362 prodesc->result_typioparam,
3365 tuplestore_putvalues(current_call_data->tuple_store,
3366 current_call_data->ret_tdesc,
3370 MemoryContextSwitchTo(old_cxt);
3371 MemoryContextReset(current_call_data->tmp_cxt);
3376 plperl_spi_query(char *query)
3381 * Execute the query inside a sub-transaction, so we can cope with errors
3384 MemoryContext oldcontext = CurrentMemoryContext;
3385 ResourceOwner oldowner = CurrentResourceOwner;
3387 check_spi_usage_allowed();
3389 BeginInternalSubTransaction(NULL);
3390 /* Want to run inside function's memory context */
3391 MemoryContextSwitchTo(oldcontext);
3398 /* Make sure the query is validly encoded */
3399 pg_verifymbstr(query, strlen(query), false);
3401 /* Create a cursor for the query */
3402 plan = SPI_prepare(query, 0, NULL);
3404 elog(ERROR, "SPI_prepare() failed:%s",
3405 SPI_result_code_string(SPI_result));
3407 portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
3410 elog(ERROR, "SPI_cursor_open() failed:%s",
3411 SPI_result_code_string(SPI_result));
3412 cursor = cstr2sv(portal->name);
3416 /* Commit the inner transaction, return to outer xact context */
3417 ReleaseCurrentSubTransaction();
3418 MemoryContextSwitchTo(oldcontext);
3419 CurrentResourceOwner = oldowner;
3425 /* Save error info */
3426 MemoryContextSwitchTo(oldcontext);
3427 edata = CopyErrorData();
3430 /* Abort the inner transaction */
3431 RollbackAndReleaseCurrentSubTransaction();
3432 MemoryContextSwitchTo(oldcontext);
3433 CurrentResourceOwner = oldowner;
3435 /* Punt the error to Perl */
3436 croak_cstr(edata->message);
3438 /* Can't get here, but keep compiler quiet */
3448 plperl_spi_fetchrow(char *cursor)
3453 * Execute the FETCH inside a sub-transaction, so we can cope with errors
3456 MemoryContext oldcontext = CurrentMemoryContext;
3457 ResourceOwner oldowner = CurrentResourceOwner;
3459 check_spi_usage_allowed();
3461 BeginInternalSubTransaction(NULL);
3462 /* Want to run inside function's memory context */
3463 MemoryContextSwitchTo(oldcontext);
3468 Portal p = SPI_cursor_find(cursor);
3476 SPI_cursor_fetch(p, true, 1);
3477 if (SPI_processed == 0)
3480 SPI_cursor_close(p);
3485 row = plperl_hash_from_tuple(SPI_tuptable->vals[0],
3486 SPI_tuptable->tupdesc);
3488 SPI_freetuptable(SPI_tuptable);
3491 /* Commit the inner transaction, return to outer xact context */
3492 ReleaseCurrentSubTransaction();
3493 MemoryContextSwitchTo(oldcontext);
3494 CurrentResourceOwner = oldowner;
3500 /* Save error info */
3501 MemoryContextSwitchTo(oldcontext);
3502 edata = CopyErrorData();
3505 /* Abort the inner transaction */
3506 RollbackAndReleaseCurrentSubTransaction();
3507 MemoryContextSwitchTo(oldcontext);
3508 CurrentResourceOwner = oldowner;
3510 /* Punt the error to Perl */
3511 croak_cstr(edata->message);
3513 /* Can't get here, but keep compiler quiet */
3522 plperl_spi_cursor_close(char *cursor)
3526 check_spi_usage_allowed();
3528 p = SPI_cursor_find(cursor);
3533 SPI_cursor_close(p);
3538 plperl_spi_prepare(char *query, int argc, SV **argv)
3540 volatile SPIPlanPtr plan = NULL;
3541 volatile MemoryContext plan_cxt = NULL;
3542 plperl_query_desc *volatile qdesc = NULL;
3543 plperl_query_entry *volatile hash_entry = NULL;
3544 MemoryContext oldcontext = CurrentMemoryContext;
3545 ResourceOwner oldowner = CurrentResourceOwner;
3546 MemoryContext work_cxt;
3550 check_spi_usage_allowed();
3552 BeginInternalSubTransaction(NULL);
3553 MemoryContextSwitchTo(oldcontext);
3557 CHECK_FOR_INTERRUPTS();
3559 /************************************************************
3560 * Allocate the new querydesc structure
3562 * The qdesc struct, as well as all its subsidiary data, lives in its
3563 * plan_cxt. But note that the SPIPlan does not.
3564 ************************************************************/
3565 plan_cxt = AllocSetContextCreate(TopMemoryContext,
3566 "PL/Perl spi_prepare query",
3567 ALLOCSET_SMALL_SIZES);
3568 MemoryContextSwitchTo(plan_cxt);
3569 qdesc = (plperl_query_desc *) palloc0(sizeof(plperl_query_desc));
3570 snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
3571 qdesc->plan_cxt = plan_cxt;
3572 qdesc->nargs = argc;
3573 qdesc->argtypes = (Oid *) palloc(argc * sizeof(Oid));
3574 qdesc->arginfuncs = (FmgrInfo *) palloc(argc * sizeof(FmgrInfo));
3575 qdesc->argtypioparams = (Oid *) palloc(argc * sizeof(Oid));
3576 MemoryContextSwitchTo(oldcontext);
3578 /************************************************************
3579 * Do the following work in a short-lived context so that we don't
3580 * leak a lot of memory in the PL/Perl function's SPI Proc context.
3581 ************************************************************/
3582 work_cxt = AllocSetContextCreate(CurrentMemoryContext,
3583 "PL/Perl spi_prepare workspace",
3584 ALLOCSET_DEFAULT_SIZES);
3585 MemoryContextSwitchTo(work_cxt);
3587 /************************************************************
3588 * Resolve argument type names and then look them up by oid
3589 * in the system cache, and remember the required information
3590 * for input conversion.
3591 ************************************************************/
3592 for (i = 0; i < argc; i++)
3600 typstr = sv2cstr(argv[i]);
3601 parseTypeString(typstr, &typId, &typmod, false);
3604 getTypeInputInfo(typId, &typInput, &typIOParam);
3606 qdesc->argtypes[i] = typId;
3607 fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
3608 qdesc->argtypioparams[i] = typIOParam;
3611 /* Make sure the query is validly encoded */
3612 pg_verifymbstr(query, strlen(query), false);
3614 /************************************************************
3615 * Prepare the plan and check for errors
3616 ************************************************************/
3617 plan = SPI_prepare(query, argc, qdesc->argtypes);
3620 elog(ERROR, "SPI_prepare() failed:%s",
3621 SPI_result_code_string(SPI_result));
3623 /************************************************************
3624 * Save the plan into permanent memory (right now it's in the
3625 * SPI procCxt, which will go away at function end).
3626 ************************************************************/
3627 if (SPI_keepplan(plan))
3628 elog(ERROR, "SPI_keepplan() failed");
3631 /************************************************************
3632 * Insert a hashtable entry for the plan.
3633 ************************************************************/
3634 hash_entry = hash_search(plperl_active_interp->query_hash,
3636 HASH_ENTER, &found);
3637 hash_entry->query_data = qdesc;
3639 /* Get rid of workspace */
3640 MemoryContextDelete(work_cxt);
3642 /* Commit the inner transaction, return to outer xact context */
3643 ReleaseCurrentSubTransaction();
3644 MemoryContextSwitchTo(oldcontext);
3645 CurrentResourceOwner = oldowner;
3651 /* Save error info */
3652 MemoryContextSwitchTo(oldcontext);
3653 edata = CopyErrorData();
3656 /* Drop anything we managed to allocate */
3658 hash_search(plperl_active_interp->query_hash,
3662 MemoryContextDelete(plan_cxt);
3666 /* Abort the inner transaction */
3667 RollbackAndReleaseCurrentSubTransaction();
3668 MemoryContextSwitchTo(oldcontext);
3669 CurrentResourceOwner = oldowner;
3671 /* Punt the error to Perl */
3672 croak_cstr(edata->message);
3674 /* Can't get here, but keep compiler quiet */
3679 /************************************************************
3680 * Return the query's hash key to the caller.
3681 ************************************************************/
3682 return cstr2sv(qdesc->qname);
3686 plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
3695 plperl_query_desc *qdesc;
3696 plperl_query_entry *hash_entry;
3699 * Execute the query inside a sub-transaction, so we can cope with errors
3702 MemoryContext oldcontext = CurrentMemoryContext;
3703 ResourceOwner oldowner = CurrentResourceOwner;
3705 check_spi_usage_allowed();
3707 BeginInternalSubTransaction(NULL);
3708 /* Want to run inside function's memory context */
3709 MemoryContextSwitchTo(oldcontext);
3715 /************************************************************
3716 * Fetch the saved plan descriptor, see if it's o.k.
3717 ************************************************************/
3718 hash_entry = hash_search(plperl_active_interp->query_hash, query,
3720 if (hash_entry == NULL)
3721 elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
3723 qdesc = hash_entry->query_data;
3725 elog(ERROR, "spi_exec_prepared: plperl query_hash value vanished");
3727 if (qdesc->nargs != argc)
3728 elog(ERROR, "spi_exec_prepared: expected %d argument(s), %d passed",
3729 qdesc->nargs, argc);
3731 /************************************************************
3732 * Parse eventual attributes
3733 ************************************************************/
3737 sv = hv_fetch_string(attr, "limit");
3738 if (sv && *sv && SvIOK(*sv))
3741 /************************************************************
3743 ************************************************************/
3746 nulls = (char *) palloc(argc);
3747 argvalues = (Datum *) palloc(argc * sizeof(Datum));
3755 for (i = 0; i < argc; i++)
3759 argvalues[i] = plperl_sv_to_datum(argv[i],
3763 &qdesc->arginfuncs[i],
3764 qdesc->argtypioparams[i],
3766 nulls[i] = isnull ? 'n' : ' ';
3769 /************************************************************
3771 ************************************************************/
3772 spi_rv = SPI_execute_plan(qdesc->plan, argvalues, nulls,
3773 current_call_data->prodesc->fn_readonly, limit);
3774 ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
3782 /* Commit the inner transaction, return to outer xact context */
3783 ReleaseCurrentSubTransaction();
3784 MemoryContextSwitchTo(oldcontext);
3785 CurrentResourceOwner = oldowner;
3791 /* Save error info */
3792 MemoryContextSwitchTo(oldcontext);
3793 edata = CopyErrorData();
3796 /* Abort the inner transaction */
3797 RollbackAndReleaseCurrentSubTransaction();
3798 MemoryContextSwitchTo(oldcontext);
3799 CurrentResourceOwner = oldowner;
3801 /* Punt the error to Perl */
3802 croak_cstr(edata->message);
3804 /* Can't get here, but keep compiler quiet */
3813 plperl_spi_query_prepared(char *query, int argc, SV **argv)
3818 plperl_query_desc *qdesc;
3819 plperl_query_entry *hash_entry;
3821 Portal portal = NULL;
3824 * Execute the query inside a sub-transaction, so we can cope with errors
3827 MemoryContext oldcontext = CurrentMemoryContext;
3828 ResourceOwner oldowner = CurrentResourceOwner;
3830 check_spi_usage_allowed();
3832 BeginInternalSubTransaction(NULL);
3833 /* Want to run inside function's memory context */
3834 MemoryContextSwitchTo(oldcontext);
3838 /************************************************************
3839 * Fetch the saved plan descriptor, see if it's o.k.
3840 ************************************************************/
3841 hash_entry = hash_search(plperl_active_interp->query_hash, query,
3843 if (hash_entry == NULL)
3844 elog(ERROR, "spi_query_prepared: Invalid prepared query passed");
3846 qdesc = hash_entry->query_data;
3848 elog(ERROR, "spi_query_prepared: plperl query_hash value vanished");
3850 if (qdesc->nargs != argc)
3851 elog(ERROR, "spi_query_prepared: expected %d argument(s), %d passed",
3852 qdesc->nargs, argc);
3854 /************************************************************
3856 ************************************************************/
3859 nulls = (char *) palloc(argc);
3860 argvalues = (Datum *) palloc(argc * sizeof(Datum));
3868 for (i = 0; i < argc; i++)
3872 argvalues[i] = plperl_sv_to_datum(argv[i],
3876 &qdesc->arginfuncs[i],
3877 qdesc->argtypioparams[i],
3879 nulls[i] = isnull ? 'n' : ' ';
3882 /************************************************************
3884 ************************************************************/
3885 portal = SPI_cursor_open(NULL, qdesc->plan, argvalues, nulls,
3886 current_call_data->prodesc->fn_readonly);
3893 elog(ERROR, "SPI_cursor_open() failed:%s",
3894 SPI_result_code_string(SPI_result));
3896 cursor = cstr2sv(portal->name);
3900 /* Commit the inner transaction, return to outer xact context */
3901 ReleaseCurrentSubTransaction();
3902 MemoryContextSwitchTo(oldcontext);
3903 CurrentResourceOwner = oldowner;
3909 /* Save error info */
3910 MemoryContextSwitchTo(oldcontext);
3911 edata = CopyErrorData();
3914 /* Abort the inner transaction */
3915 RollbackAndReleaseCurrentSubTransaction();
3916 MemoryContextSwitchTo(oldcontext);
3917 CurrentResourceOwner = oldowner;
3919 /* Punt the error to Perl */
3920 croak_cstr(edata->message);
3922 /* Can't get here, but keep compiler quiet */
3931 plperl_spi_freeplan(char *query)
3934 plperl_query_desc *qdesc;
3935 plperl_query_entry *hash_entry;
3937 check_spi_usage_allowed();
3939 hash_entry = hash_search(plperl_active_interp->query_hash, query,
3941 if (hash_entry == NULL)
3942 elog(ERROR, "spi_freeplan: Invalid prepared query passed");
3944 qdesc = hash_entry->query_data;
3946 elog(ERROR, "spi_freeplan: plperl query_hash value vanished");
3950 * free all memory before SPI_freeplan, so if it dies, nothing will be
3953 hash_search(plperl_active_interp->query_hash, query,
3956 MemoryContextDelete(qdesc->plan_cxt);
3962 plperl_spi_commit(void)
3964 MemoryContext oldcontext = CurrentMemoryContext;
3968 if (ThereArePinnedPortals())
3970 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3971 errmsg("cannot commit transaction while a cursor is open")));
3974 SPI_start_transaction();
3980 /* Save error info */
3981 MemoryContextSwitchTo(oldcontext);
3982 edata = CopyErrorData();
3985 /* Punt the error to Perl */
3986 croak_cstr(edata->message);
3992 plperl_spi_rollback(void)
3994 MemoryContext oldcontext = CurrentMemoryContext;
3998 if (ThereArePinnedPortals())
4000 (errcode(ERRCODE_INVALID_TRANSACTION_TERMINATION),
4001 errmsg("cannot abort transaction while a cursor is open")));
4004 SPI_start_transaction();
4010 /* Save error info */
4011 MemoryContextSwitchTo(oldcontext);
4012 edata = CopyErrorData();
4015 /* Punt the error to Perl */
4016 croak_cstr(edata->message);
4022 * Implementation of plperl's elog() function
4024 * If the error level is less than ERROR, we'll just emit the message and
4025 * return. When it is ERROR, elog() will longjmp, which we catch and
4026 * turn into a Perl croak(). Note we are assuming that elog() can't have
4027 * any internal failures that are so bad as to require a transaction abort.
4029 * The main reason this is out-of-line is to avoid conflicts between XSUB.h
4030 * and the PG_TRY macros.
4033 plperl_util_elog(int level, SV *msg)
4035 MemoryContext oldcontext = CurrentMemoryContext;
4036 char *volatile cmsg = NULL;
4040 cmsg = sv2cstr(msg);
4041 elog(level, "%s", cmsg);
4048 /* Must reset elog.c's state */
4049 MemoryContextSwitchTo(oldcontext);
4050 edata = CopyErrorData();
4056 /* Punt the error to Perl */
4057 croak_cstr(edata->message);
4063 * Store an SV into a hash table under a key that is a string assumed to be
4064 * in the current database's encoding.
4067 hv_store_string(HV *hv, const char *key, SV *val)
4074 hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4077 * hv_store() recognizes a negative klen parameter as meaning a UTF-8
4080 hlen = -(int) strlen(hkey);
4081 ret = hv_store(hv, hkey, hlen, val, 0);
4090 * Fetch an SV from a hash table under a key that is a string assumed to be
4091 * in the current database's encoding.
4094 hv_fetch_string(HV *hv, const char *key)
4101 hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4103 /* See notes in hv_store_string */
4104 hlen = -(int) strlen(hkey);
4105 ret = hv_fetch(hv, hkey, hlen, 0);
4114 * Provide function name for PL/Perl execution errors
4117 plperl_exec_callback(void *arg)
4119 char *procname = (char *) arg;
4122 errcontext("PL/Perl function \"%s\"", procname);
4126 * Provide function name for PL/Perl compilation errors
4129 plperl_compile_callback(void *arg)
4131 char *procname = (char *) arg;
4134 errcontext("compilation of PL/Perl function \"%s\"", procname);
4138 * Provide error context for the inline handler
4141 plperl_inline_callback(void *arg)
4143 errcontext("PL/Perl anonymous code block");
4148 * Perl's own setlocale(), copied from POSIX.xs
4149 * (needed because of the calls to new_*())
4153 setlocale_perl(int category, char *locale)
4156 char *RETVAL = setlocale(category, locale);
4160 #ifdef USE_LOCALE_CTYPE
4161 if (category == LC_CTYPE
4163 || category == LC_ALL
4170 if (category == LC_ALL)
4171 newctype = setlocale(LC_CTYPE, NULL);
4175 new_ctype(newctype);
4177 #endif /* USE_LOCALE_CTYPE */
4178 #ifdef USE_LOCALE_COLLATE
4179 if (category == LC_COLLATE
4181 || category == LC_ALL
4188 if (category == LC_ALL)
4189 newcoll = setlocale(LC_COLLATE, NULL);
4193 new_collate(newcoll);
4195 #endif /* USE_LOCALE_COLLATE */
4197 #ifdef USE_LOCALE_NUMERIC
4198 if (category == LC_NUMERIC
4200 || category == LC_ALL
4207 if (category == LC_ALL)
4208 newnum = setlocale(LC_NUMERIC, NULL);
4212 new_numeric(newnum);
4214 #endif /* USE_LOCALE_NUMERIC */