Rewrite maybe_reread_subscription() comment
[pgsql.git] / src / pl / plperl / plperl.c
blob1b1677e333b919f6741c78856df067910b8a9dcd
1 /**********************************************************************
2 * plperl.c - perl as a procedural language for PostgreSQL
4 * src/pl/plperl/plperl.c
6 **********************************************************************/
8 #include "postgres.h"
10 /* system stuff */
11 #include <ctype.h>
12 #include <fcntl.h>
13 #include <limits.h>
14 #include <unistd.h>
16 /* postgreSQL stuff */
17 #include "access/htup_details.h"
18 #include "access/xact.h"
19 #include "catalog/pg_language.h"
20 #include "catalog/pg_proc.h"
21 #include "catalog/pg_type.h"
22 #include "commands/event_trigger.h"
23 #include "commands/trigger.h"
24 #include "executor/spi.h"
25 #include "funcapi.h"
26 #include "miscadmin.h"
27 #include "parser/parse_type.h"
28 #include "storage/ipc.h"
29 #include "tcop/tcopprot.h"
30 #include "utils/builtins.h"
31 #include "utils/fmgroids.h"
32 #include "utils/guc.h"
33 #include "utils/hsearch.h"
34 #include "utils/lsyscache.h"
35 #include "utils/memutils.h"
36 #include "utils/rel.h"
37 #include "utils/syscache.h"
38 #include "utils/typcache.h"
40 /* define our text domain for translations */
41 #undef TEXTDOMAIN
42 #define TEXTDOMAIN PG_TEXTDOMAIN("plperl")
44 /* perl stuff */
45 /* string literal macros defining chunks of perl code */
46 #include "perlchunks.h"
47 #include "plperl.h"
48 /* defines PLPERL_SET_OPMASK */
49 #include "plperl_opmask.h"
51 EXTERN_C void boot_DynaLoader(pTHX_ CV *cv);
52 EXTERN_C void boot_PostgreSQL__InServer__Util(pTHX_ CV *cv);
53 EXTERN_C void boot_PostgreSQL__InServer__SPI(pTHX_ CV *cv);
55 PG_MODULE_MAGIC;
57 /**********************************************************************
58 * Information associated with a Perl interpreter. We have one interpreter
59 * that is used for all plperlu (untrusted) functions. For plperl (trusted)
60 * functions, there is a separate interpreter for each effective SQL userid.
61 * (This is needed to ensure that an unprivileged user can't inject Perl code
62 * that'll be executed with the privileges of some other SQL user.)
64 * The plperl_interp_desc structs are kept in a Postgres hash table indexed
65 * by userid OID, with OID 0 used for the single untrusted interpreter.
66 * Once created, an interpreter is kept for the life of the process.
68 * We start out by creating a "held" interpreter, which we initialize
69 * only as far as we can do without deciding if it will be trusted or
70 * untrusted. Later, when we first need to run a plperl or plperlu
71 * function, we complete the initialization appropriately and move the
72 * PerlInterpreter pointer into the plperl_interp_hash hashtable. If after
73 * that we need more interpreters, we create them as needed if we can, or
74 * fail if the Perl build doesn't support multiple interpreters.
76 * The reason for all the dancing about with a held interpreter is to make
77 * it possible for people to preload a lot of Perl code at postmaster startup
78 * (using plperl.on_init) and then use that code in backends. Of course this
79 * will only work for the first interpreter created in any backend, but it's
80 * still useful with that restriction.
81 **********************************************************************/
82 typedef struct plperl_interp_desc
84 Oid user_id; /* Hash key (must be first!) */
85 PerlInterpreter *interp; /* The interpreter */
86 HTAB *query_hash; /* plperl_query_entry structs */
87 } plperl_interp_desc;
90 /**********************************************************************
91 * The information we cache about loaded procedures
93 * The fn_refcount field counts the struct's reference from the hash table
94 * shown below, plus one reference for each function call level that is using
95 * the struct. We can release the struct, and the associated Perl sub, when
96 * the fn_refcount goes to zero. Releasing the struct itself is done by
97 * deleting the fn_cxt, which also gets rid of all subsidiary data.
98 **********************************************************************/
99 typedef struct plperl_proc_desc
101 char *proname; /* user name of procedure */
102 MemoryContext fn_cxt; /* memory context for this procedure */
103 unsigned long fn_refcount; /* number of active references */
104 TransactionId fn_xmin; /* xmin/TID of procedure's pg_proc tuple */
105 ItemPointerData fn_tid;
106 SV *reference; /* CODE reference for Perl sub */
107 plperl_interp_desc *interp; /* interpreter it's created in */
108 bool fn_readonly; /* is function readonly (not volatile)? */
109 Oid lang_oid;
110 List *trftypes;
111 bool lanpltrusted; /* is it plperl, rather than plperlu? */
112 bool fn_retistuple; /* true, if function returns tuple */
113 bool fn_retisset; /* true, if function returns set */
114 bool fn_retisarray; /* true if function returns array */
115 /* Conversion info for function's result type: */
116 Oid result_oid; /* Oid of result type */
117 FmgrInfo result_in_func; /* I/O function and arg for result type */
118 Oid result_typioparam;
119 /* Per-argument info for function's argument types: */
120 int nargs;
121 FmgrInfo *arg_out_func; /* output fns for arg types */
122 bool *arg_is_rowtype; /* is each arg composite? */
123 Oid *arg_arraytype; /* InvalidOid if not an array */
124 } plperl_proc_desc;
126 #define increment_prodesc_refcount(prodesc) \
127 ((prodesc)->fn_refcount++)
128 #define decrement_prodesc_refcount(prodesc) \
129 do { \
130 Assert((prodesc)->fn_refcount > 0); \
131 if (--((prodesc)->fn_refcount) == 0) \
132 free_plperl_function(prodesc); \
133 } while(0)
135 /**********************************************************************
136 * For speedy lookup, we maintain a hash table mapping from
137 * function OID + trigger flag + user OID to plperl_proc_desc pointers.
138 * The reason the plperl_proc_desc struct isn't directly part of the hash
139 * entry is to simplify recovery from errors during compile_plperl_function.
141 * Note: if the same function is called by multiple userIDs within a session,
142 * there will be a separate plperl_proc_desc entry for each userID in the case
143 * of plperl functions, but only one entry for plperlu functions, because we
144 * set user_id = 0 for that case. If the user redeclares the same function
145 * from plperl to plperlu or vice versa, there might be multiple
146 * plperl_proc_ptr entries in the hashtable, but only one is valid.
147 **********************************************************************/
148 typedef struct plperl_proc_key
150 Oid proc_id; /* Function OID */
153 * is_trigger is really a bool, but declare as Oid to ensure this struct
154 * contains no padding
156 Oid is_trigger; /* is it a trigger function? */
157 Oid user_id; /* User calling the function, or 0 */
158 } plperl_proc_key;
160 typedef struct plperl_proc_ptr
162 plperl_proc_key proc_key; /* Hash key (must be first!) */
163 plperl_proc_desc *proc_ptr;
164 } plperl_proc_ptr;
167 * The information we cache for the duration of a single call to a
168 * function.
170 typedef struct plperl_call_data
172 plperl_proc_desc *prodesc;
173 FunctionCallInfo fcinfo;
174 /* remaining fields are used only in a function returning set: */
175 Tuplestorestate *tuple_store;
176 TupleDesc ret_tdesc;
177 Oid cdomain_oid; /* 0 unless returning domain-over-composite */
178 void *cdomain_info;
179 MemoryContext tmp_cxt;
180 } plperl_call_data;
182 /**********************************************************************
183 * The information we cache about prepared and saved plans
184 **********************************************************************/
185 typedef struct plperl_query_desc
187 char qname[24];
188 MemoryContext plan_cxt; /* context holding this struct */
189 SPIPlanPtr plan;
190 int nargs;
191 Oid *argtypes;
192 FmgrInfo *arginfuncs;
193 Oid *argtypioparams;
194 } plperl_query_desc;
196 /* hash table entry for query desc */
198 typedef struct plperl_query_entry
200 char query_name[NAMEDATALEN];
201 plperl_query_desc *query_data;
202 } plperl_query_entry;
204 /**********************************************************************
205 * Information for PostgreSQL - Perl array conversion.
206 **********************************************************************/
207 typedef struct plperl_array_info
209 int ndims;
210 bool elem_is_rowtype; /* 't' if element type is a rowtype */
211 Datum *elements;
212 bool *nulls;
213 int *nelems;
214 FmgrInfo proc;
215 FmgrInfo transform_proc;
216 } plperl_array_info;
218 /**********************************************************************
219 * Global data
220 **********************************************************************/
222 static HTAB *plperl_interp_hash = NULL;
223 static HTAB *plperl_proc_hash = NULL;
224 static plperl_interp_desc *plperl_active_interp = NULL;
226 /* If we have an unassigned "held" interpreter, it's stored here */
227 static PerlInterpreter *plperl_held_interp = NULL;
229 /* GUC variables */
230 static bool plperl_use_strict = false;
231 static char *plperl_on_init = NULL;
232 static char *plperl_on_plperl_init = NULL;
233 static char *plperl_on_plperlu_init = NULL;
235 static bool plperl_ending = false;
236 static OP *(*pp_require_orig) (pTHX) = NULL;
237 static char plperl_opmask[MAXO];
239 /* this is saved and restored by plperl_call_handler */
240 static plperl_call_data *current_call_data = NULL;
242 /**********************************************************************
243 * Forward declarations
244 **********************************************************************/
246 static PerlInterpreter *plperl_init_interp(void);
247 static void plperl_destroy_interp(PerlInterpreter **);
248 static void plperl_fini(int code, Datum arg);
249 static void set_interp_require(bool trusted);
251 static Datum plperl_func_handler(PG_FUNCTION_ARGS);
252 static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
253 static void plperl_event_trigger_handler(PG_FUNCTION_ARGS);
255 static void free_plperl_function(plperl_proc_desc *prodesc);
257 static plperl_proc_desc *compile_plperl_function(Oid fn_oid,
258 bool is_trigger,
259 bool is_event_trigger);
261 static SV *plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc, bool include_generated);
262 static SV *plperl_hash_from_datum(Datum attr);
263 static void check_spi_usage_allowed(void);
264 static SV *plperl_ref_from_pg_array(Datum arg, Oid typid);
265 static SV *split_array(plperl_array_info *info, int first, int last, int nest);
266 static SV *make_array_ref(plperl_array_info *info, int first, int last);
267 static SV *get_perl_array_ref(SV *sv);
268 static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
269 FunctionCallInfo fcinfo,
270 FmgrInfo *finfo, Oid typioparam,
271 bool *isnull);
272 static void _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam);
273 static Datum plperl_array_to_datum(SV *src, Oid typid, int32 typmod);
274 static void array_to_datum_internal(AV *av, ArrayBuildState **astatep,
275 int *ndims, int *dims, int cur_depth,
276 Oid elemtypid, int32 typmod,
277 FmgrInfo *finfo, Oid typioparam);
278 static Datum plperl_hash_to_datum(SV *src, TupleDesc td);
280 static void plperl_init_shared_libs(pTHX);
281 static void plperl_trusted_init(void);
282 static void plperl_untrusted_init(void);
283 static HV *plperl_spi_execute_fetch_result(SPITupleTable *, uint64, int);
284 static void plperl_return_next_internal(SV *sv);
285 static char *hek2cstr(HE *he);
286 static SV **hv_store_string(HV *hv, const char *key, SV *val);
287 static SV **hv_fetch_string(HV *hv, const char *key);
288 static void plperl_create_sub(plperl_proc_desc *desc, const char *s, Oid fn_oid);
289 static SV *plperl_call_perl_func(plperl_proc_desc *desc,
290 FunctionCallInfo fcinfo);
291 static void plperl_compile_callback(void *arg);
292 static void plperl_exec_callback(void *arg);
293 static void plperl_inline_callback(void *arg);
294 static char *strip_trailing_ws(const char *msg);
295 static OP *pp_require_safe(pTHX);
296 static void activate_interpreter(plperl_interp_desc *interp_desc);
298 #if defined(WIN32) && PERL_VERSION_LT(5, 28, 0)
299 static char *setlocale_perl(int category, char *locale);
300 #else
301 #define setlocale_perl(a,b) Perl_setlocale(a,b)
302 #endif /* defined(WIN32) && PERL_VERSION_LT(5, 28, 0) */
305 * Decrement the refcount of the given SV within the active Perl interpreter
307 * This is handy because it reloads the active-interpreter pointer, saving
308 * some notation in callers that switch the active interpreter.
310 static inline void
311 SvREFCNT_dec_current(SV *sv)
313 dTHX;
315 SvREFCNT_dec(sv);
319 * convert a HE (hash entry) key to a cstr in the current database encoding
321 static char *
322 hek2cstr(HE *he)
324 dTHX;
325 char *ret;
326 SV *sv;
329 * HeSVKEY_force will return a temporary mortal SV*, so we need to make
330 * sure to free it with ENTER/SAVE/FREE/LEAVE
332 ENTER;
333 SAVETMPS;
335 /*-------------------------
336 * Unfortunately, while HeUTF8 is true for most things > 256, for values
337 * 128..255 it's not, but perl will treat them as unicode code points if
338 * the utf8 flag is not set ( see The "Unicode Bug" in perldoc perlunicode
339 * for more)
341 * So if we did the expected:
342 * if (HeUTF8(he))
343 * utf_u2e(key...);
344 * else // must be ascii
345 * return HePV(he);
346 * we won't match columns with codepoints from 128..255
348 * For a more concrete example given a column with the name of the unicode
349 * codepoint U+00ae (registered sign) and a UTF8 database and the perl
350 * return_next { "\N{U+00ae}=>'text } would always fail as heUTF8 returns
351 * 0 and HePV() would give us a char * with 1 byte contains the decimal
352 * value 174
354 * Perl has the brains to know when it should utf8 encode 174 properly, so
355 * here we force it into an SV so that perl will figure it out and do the
356 * right thing
357 *-------------------------
360 sv = HeSVKEY_force(he);
361 if (HeUTF8(he))
362 SvUTF8_on(sv);
363 ret = sv2cstr(sv);
365 /* free sv */
366 FREETMPS;
367 LEAVE;
369 return ret;
374 * _PG_init() - library load-time initialization
376 * DO NOT make this static nor change its name!
378 void
379 _PG_init(void)
382 * Be sure we do initialization only once.
384 * If initialization fails due to, e.g., plperl_init_interp() throwing an
385 * exception, then we'll return here on the next usage and the user will
386 * get a rather cryptic: ERROR: attempt to redefine parameter
387 * "plperl.use_strict"
389 static bool inited = false;
390 HASHCTL hash_ctl;
392 if (inited)
393 return;
396 * Support localized messages.
398 pg_bindtextdomain(TEXTDOMAIN);
401 * Initialize plperl's GUCs.
403 DefineCustomBoolVariable("plperl.use_strict",
404 gettext_noop("If true, trusted and untrusted Perl code will be compiled in strict mode."),
405 NULL,
406 &plperl_use_strict,
407 false,
408 PGC_USERSET, 0,
409 NULL, NULL, NULL);
412 * plperl.on_init is marked PGC_SIGHUP to support the idea that it might
413 * be executed in the postmaster (if plperl is loaded into the postmaster
414 * via shared_preload_libraries). This isn't really right either way,
415 * though.
417 DefineCustomStringVariable("plperl.on_init",
418 gettext_noop("Perl initialization code to execute when a Perl interpreter is initialized."),
419 NULL,
420 &plperl_on_init,
421 NULL,
422 PGC_SIGHUP, 0,
423 NULL, NULL, NULL);
426 * plperl.on_plperl_init is marked PGC_SUSET to avoid issues whereby a
427 * user who might not even have USAGE privilege on the plperl language
428 * could nonetheless use SET plperl.on_plperl_init='...' to influence the
429 * behaviour of any existing plperl function that they can execute (which
430 * might be SECURITY DEFINER, leading to a privilege escalation). See
431 * http://archives.postgresql.org/pgsql-hackers/2010-02/msg00281.php and
432 * the overall thread.
434 * Note that because plperl.use_strict is USERSET, a nefarious user could
435 * set it to be applied against other people's functions. This is judged
436 * OK since the worst result would be an error. Your code oughta pass
437 * use_strict anyway ;-)
439 DefineCustomStringVariable("plperl.on_plperl_init",
440 gettext_noop("Perl initialization code to execute once when plperl is first used."),
441 NULL,
442 &plperl_on_plperl_init,
443 NULL,
444 PGC_SUSET, 0,
445 NULL, NULL, NULL);
447 DefineCustomStringVariable("plperl.on_plperlu_init",
448 gettext_noop("Perl initialization code to execute once when plperlu is first used."),
449 NULL,
450 &plperl_on_plperlu_init,
451 NULL,
452 PGC_SUSET, 0,
453 NULL, NULL, NULL);
455 MarkGUCPrefixReserved("plperl");
458 * Create hash tables.
460 hash_ctl.keysize = sizeof(Oid);
461 hash_ctl.entrysize = sizeof(plperl_interp_desc);
462 plperl_interp_hash = hash_create("PL/Perl interpreters",
464 &hash_ctl,
465 HASH_ELEM | HASH_BLOBS);
467 hash_ctl.keysize = sizeof(plperl_proc_key);
468 hash_ctl.entrysize = sizeof(plperl_proc_ptr);
469 plperl_proc_hash = hash_create("PL/Perl procedures",
471 &hash_ctl,
472 HASH_ELEM | HASH_BLOBS);
475 * Save the default opmask.
477 PLPERL_SET_OPMASK(plperl_opmask);
480 * Create the first Perl interpreter, but only partially initialize it.
482 plperl_held_interp = plperl_init_interp();
484 inited = true;
488 static void
489 set_interp_require(bool trusted)
491 if (trusted)
493 PL_ppaddr[OP_REQUIRE] = pp_require_safe;
494 PL_ppaddr[OP_DOFILE] = pp_require_safe;
496 else
498 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
499 PL_ppaddr[OP_DOFILE] = pp_require_orig;
504 * Cleanup perl interpreters, including running END blocks.
505 * Does not fully undo the actions of _PG_init() nor make it callable again.
507 static void
508 plperl_fini(int code, Datum arg)
510 HASH_SEQ_STATUS hash_seq;
511 plperl_interp_desc *interp_desc;
513 elog(DEBUG3, "plperl_fini");
516 * Indicate that perl is terminating. Disables use of spi_* functions when
517 * running END/DESTROY code. See check_spi_usage_allowed(). Could be
518 * enabled in future, with care, using a transaction
519 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02743.php
521 plperl_ending = true;
523 /* Only perform perl cleanup if we're exiting cleanly */
524 if (code)
526 elog(DEBUG3, "plperl_fini: skipped");
527 return;
530 /* Zap the "held" interpreter, if we still have it */
531 plperl_destroy_interp(&plperl_held_interp);
533 /* Zap any fully-initialized interpreters */
534 hash_seq_init(&hash_seq, plperl_interp_hash);
535 while ((interp_desc = hash_seq_search(&hash_seq)) != NULL)
537 if (interp_desc->interp)
539 activate_interpreter(interp_desc);
540 plperl_destroy_interp(&interp_desc->interp);
544 elog(DEBUG3, "plperl_fini: done");
549 * Select and activate an appropriate Perl interpreter.
551 static void
552 select_perl_context(bool trusted)
554 Oid user_id;
555 plperl_interp_desc *interp_desc;
556 bool found;
557 PerlInterpreter *interp = NULL;
559 /* Find or create the interpreter hashtable entry for this userid */
560 if (trusted)
561 user_id = GetUserId();
562 else
563 user_id = InvalidOid;
565 interp_desc = hash_search(plperl_interp_hash, &user_id,
566 HASH_ENTER,
567 &found);
568 if (!found)
570 /* Initialize newly-created hashtable entry */
571 interp_desc->interp = NULL;
572 interp_desc->query_hash = NULL;
575 /* Make sure we have a query_hash for this interpreter */
576 if (interp_desc->query_hash == NULL)
578 HASHCTL hash_ctl;
580 hash_ctl.keysize = NAMEDATALEN;
581 hash_ctl.entrysize = sizeof(plperl_query_entry);
582 interp_desc->query_hash = hash_create("PL/Perl queries",
584 &hash_ctl,
585 HASH_ELEM | HASH_STRINGS);
589 * Quick exit if already have an interpreter
591 if (interp_desc->interp)
593 activate_interpreter(interp_desc);
594 return;
598 * adopt held interp if free, else create new one if possible
600 if (plperl_held_interp != NULL)
602 /* first actual use of a perl interpreter */
603 interp = plperl_held_interp;
606 * Reset the plperl_held_interp pointer first; if we fail during init
607 * we don't want to try again with the partially-initialized interp.
609 plperl_held_interp = NULL;
611 if (trusted)
612 plperl_trusted_init();
613 else
614 plperl_untrusted_init();
616 /* successfully initialized, so arrange for cleanup */
617 on_proc_exit(plperl_fini, 0);
619 else
621 #ifdef MULTIPLICITY
624 * plperl_init_interp will change Perl's idea of the active
625 * interpreter. Reset plperl_active_interp temporarily, so that if we
626 * hit an error partway through here, we'll make sure to switch back
627 * to a non-broken interpreter before running any other Perl
628 * functions.
630 plperl_active_interp = NULL;
632 /* Now build the new interpreter */
633 interp = plperl_init_interp();
635 if (trusted)
636 plperl_trusted_init();
637 else
638 plperl_untrusted_init();
639 #else
640 ereport(ERROR,
641 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
642 errmsg("cannot allocate multiple Perl interpreters on this platform")));
643 #endif
646 set_interp_require(trusted);
649 * Since the timing of first use of PL/Perl can't be predicted, any
650 * database interaction during initialization is problematic. Including,
651 * but not limited to, security definer issues. So we only enable access
652 * to the database AFTER on_*_init code has run. See
653 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02669.php
656 dTHX;
658 newXS("PostgreSQL::InServer::SPI::bootstrap",
659 boot_PostgreSQL__InServer__SPI, __FILE__);
661 eval_pv("PostgreSQL::InServer::SPI::bootstrap()", FALSE);
662 if (SvTRUE(ERRSV))
663 ereport(ERROR,
664 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
665 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
666 errcontext("while executing PostgreSQL::InServer::SPI::bootstrap")));
669 /* Fully initialized, so mark the hashtable entry valid */
670 interp_desc->interp = interp;
672 /* And mark this as the active interpreter */
673 plperl_active_interp = interp_desc;
677 * Make the specified interpreter the active one
679 * A call with NULL does nothing. This is so that "restoring" to a previously
680 * null state of plperl_active_interp doesn't result in useless thrashing.
682 static void
683 activate_interpreter(plperl_interp_desc *interp_desc)
685 if (interp_desc && plperl_active_interp != interp_desc)
687 Assert(interp_desc->interp);
688 PERL_SET_CONTEXT(interp_desc->interp);
689 /* trusted iff user_id isn't InvalidOid */
690 set_interp_require(OidIsValid(interp_desc->user_id));
691 plperl_active_interp = interp_desc;
696 * Create a new Perl interpreter.
698 * We initialize the interpreter as far as we can without knowing whether
699 * it will become a trusted or untrusted interpreter; in particular, the
700 * plperl.on_init code will get executed. Later, either plperl_trusted_init
701 * or plperl_untrusted_init must be called to complete the initialization.
703 static PerlInterpreter *
704 plperl_init_interp(void)
706 PerlInterpreter *plperl;
708 static char *embedding[3 + 2] = {
709 "", "-e", PLC_PERLBOOT
711 int nargs = 3;
713 #ifdef WIN32
716 * The perl library on startup does horrible things like call
717 * setlocale(LC_ALL,""). We have protected against that on most platforms
718 * by setting the environment appropriately. However, on Windows,
719 * setlocale() does not consult the environment, so we need to save the
720 * existing locale settings before perl has a chance to mangle them and
721 * restore them after its dirty deeds are done.
723 * MSDN ref:
724 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_locale.asp
726 * It appears that we only need to do this on interpreter startup, and
727 * subsequent calls to the interpreter don't mess with the locale
728 * settings.
730 * We restore them using setlocale_perl(), defined below, so that Perl
731 * doesn't have a different idea of the locale from Postgres.
735 char *loc;
736 char *save_collate,
737 *save_ctype,
738 *save_monetary,
739 *save_numeric,
740 *save_time;
742 loc = setlocale(LC_COLLATE, NULL);
743 save_collate = loc ? pstrdup(loc) : NULL;
744 loc = setlocale(LC_CTYPE, NULL);
745 save_ctype = loc ? pstrdup(loc) : NULL;
746 loc = setlocale(LC_MONETARY, NULL);
747 save_monetary = loc ? pstrdup(loc) : NULL;
748 loc = setlocale(LC_NUMERIC, NULL);
749 save_numeric = loc ? pstrdup(loc) : NULL;
750 loc = setlocale(LC_TIME, NULL);
751 save_time = loc ? pstrdup(loc) : NULL;
753 #define PLPERL_RESTORE_LOCALE(name, saved) \
754 STMT_START { \
755 if (saved != NULL) { setlocale_perl(name, saved); pfree(saved); } \
756 } STMT_END
757 #endif /* WIN32 */
759 if (plperl_on_init && *plperl_on_init)
761 embedding[nargs++] = "-e";
762 embedding[nargs++] = plperl_on_init;
766 * The perl API docs state that PERL_SYS_INIT3 should be called before
767 * allocating interpreters. Unfortunately, on some platforms this fails in
768 * the Perl_do_taint() routine, which is called when the platform is using
769 * the system's malloc() instead of perl's own. Other platforms, notably
770 * Windows, fail if PERL_SYS_INIT3 is not called. So we call it if it's
771 * available, unless perl is using the system malloc(), which is true when
772 * MYMALLOC is set.
774 #if defined(PERL_SYS_INIT3) && !defined(MYMALLOC)
776 static int perl_sys_init_done;
778 /* only call this the first time through, as per perlembed man page */
779 if (!perl_sys_init_done)
781 char *dummy_env[1] = {NULL};
783 PERL_SYS_INIT3(&nargs, (char ***) &embedding, (char ***) &dummy_env);
786 * For unclear reasons, PERL_SYS_INIT3 sets the SIGFPE handler to
787 * SIG_IGN. Aside from being extremely unfriendly behavior for a
788 * library, this is dumb on the grounds that the results of a
789 * SIGFPE in this state are undefined according to POSIX, and in
790 * fact you get a forced process kill at least on Linux. Hence,
791 * restore the SIGFPE handler to the backend's standard setting.
792 * (See Perl bug 114574 for more information.)
794 pqsignal(SIGFPE, FloatExceptionHandler);
796 perl_sys_init_done = 1;
797 /* quiet warning if PERL_SYS_INIT3 doesn't use the third argument */
798 dummy_env[0] = NULL;
801 #endif
803 plperl = perl_alloc();
804 if (!plperl)
805 elog(ERROR, "could not allocate Perl interpreter");
807 PERL_SET_CONTEXT(plperl);
808 perl_construct(plperl);
811 * Run END blocks in perl_destruct instead of perl_run. Note that dTHX
812 * loads up a pointer to the current interpreter, so we have to postpone
813 * it to here rather than put it at the function head.
816 dTHX;
818 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
821 * Record the original function for the 'require' and 'dofile'
822 * opcodes. (They share the same implementation.) Ensure it's used
823 * for new interpreters.
825 if (!pp_require_orig)
826 pp_require_orig = PL_ppaddr[OP_REQUIRE];
827 else
829 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
830 PL_ppaddr[OP_DOFILE] = pp_require_orig;
833 #ifdef PLPERL_ENABLE_OPMASK_EARLY
836 * For regression testing to prove that the PLC_PERLBOOT and
837 * PLC_TRUSTED code doesn't even compile any unsafe ops. In future
838 * there may be a valid need for them to do so, in which case this
839 * could be softened (perhaps moved to plperl_trusted_init()) or
840 * removed.
842 PL_op_mask = plperl_opmask;
843 #endif
845 if (perl_parse(plperl, plperl_init_shared_libs,
846 nargs, embedding, NULL) != 0)
847 ereport(ERROR,
848 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
849 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
850 errcontext("while parsing Perl initialization")));
852 if (perl_run(plperl) != 0)
853 ereport(ERROR,
854 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
855 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
856 errcontext("while running Perl initialization")));
858 #ifdef PLPERL_RESTORE_LOCALE
859 PLPERL_RESTORE_LOCALE(LC_COLLATE, save_collate);
860 PLPERL_RESTORE_LOCALE(LC_CTYPE, save_ctype);
861 PLPERL_RESTORE_LOCALE(LC_MONETARY, save_monetary);
862 PLPERL_RESTORE_LOCALE(LC_NUMERIC, save_numeric);
863 PLPERL_RESTORE_LOCALE(LC_TIME, save_time);
864 #endif
867 return plperl;
872 * Our safe implementation of the require opcode.
873 * This is safe because it's completely unable to load any code.
874 * If the requested file/module has already been loaded it'll return true.
875 * If not, it'll die.
876 * So now "use Foo;" will work iff Foo has already been loaded.
878 static OP *
879 pp_require_safe(pTHX)
881 dVAR;
882 dSP;
883 SV *sv,
884 **svp;
885 char *name;
886 STRLEN len;
888 sv = POPs;
889 name = SvPV(sv, len);
890 if (!(name && len > 0 && *name))
891 RETPUSHNO;
893 svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
894 if (svp && *svp != &PL_sv_undef)
895 RETPUSHYES;
897 DIE(aTHX_ "Unable to load %s into plperl", name);
900 * In most Perl versions, DIE() expands to a return statement, so the next
901 * line is not necessary. But in versions between but not including
902 * 5.11.1 and 5.13.3 it does not, so the next line is necessary to avoid a
903 * "control reaches end of non-void function" warning from gcc. Other
904 * compilers such as Solaris Studio will, however, issue a "statement not
905 * reached" warning instead.
907 return NULL;
912 * Destroy one Perl interpreter ... actually we just run END blocks.
914 * Caller must have ensured this interpreter is the active one.
916 static void
917 plperl_destroy_interp(PerlInterpreter **interp)
919 if (interp && *interp)
922 * Only a very minimal destruction is performed: - just call END
923 * blocks.
925 * We could call perl_destruct() but we'd need to audit its actions
926 * very carefully and work-around any that impact us. (Calling
927 * sv_clean_objs() isn't an option because it's not part of perl's
928 * public API so isn't portably available.) Meanwhile END blocks can
929 * be used to perform manual cleanup.
931 dTHX;
933 /* Run END blocks - based on perl's perl_destruct() */
934 if (PL_exit_flags & PERL_EXIT_DESTRUCT_END)
936 dJMPENV;
937 int x = 0;
939 JMPENV_PUSH(x);
940 PERL_UNUSED_VAR(x);
941 if (PL_endav && !PL_minus_c)
942 call_list(PL_scopestack_ix, PL_endav);
943 JMPENV_POP;
945 LEAVE;
946 FREETMPS;
948 *interp = NULL;
953 * Initialize the current Perl interpreter as a trusted interp
955 static void
956 plperl_trusted_init(void)
958 dTHX;
959 HV *stash;
960 SV *sv;
961 char *key;
962 I32 klen;
964 /* use original require while we set up */
965 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
966 PL_ppaddr[OP_DOFILE] = pp_require_orig;
968 eval_pv(PLC_TRUSTED, FALSE);
969 if (SvTRUE(ERRSV))
970 ereport(ERROR,
971 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
972 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
973 errcontext("while executing PLC_TRUSTED")));
976 * Force loading of utf8 module now to prevent errors that can arise from
977 * the regex code later trying to load utf8 modules. See
978 * http://rt.perl.org/rt3/Ticket/Display.html?id=47576
980 eval_pv("my $a=chr(0x100); return $a =~ /\\xa9/i", FALSE);
981 if (SvTRUE(ERRSV))
982 ereport(ERROR,
983 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
984 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
985 errcontext("while executing utf8fix")));
988 * Lock down the interpreter
991 /* switch to the safe require/dofile opcode for future code */
992 PL_ppaddr[OP_REQUIRE] = pp_require_safe;
993 PL_ppaddr[OP_DOFILE] = pp_require_safe;
996 * prevent (any more) unsafe opcodes being compiled PL_op_mask is per
997 * interpreter, so this only needs to be set once
999 PL_op_mask = plperl_opmask;
1001 /* delete the DynaLoader:: namespace so extensions can't be loaded */
1002 stash = gv_stashpv("DynaLoader", GV_ADDWARN);
1003 hv_iterinit(stash);
1004 while ((sv = hv_iternextsv(stash, &key, &klen)))
1006 if (!isGV_with_GP(sv) || !GvCV(sv))
1007 continue;
1008 SvREFCNT_dec(GvCV(sv)); /* free the CV */
1009 GvCV_set(sv, NULL); /* prevent call via GV */
1011 hv_clear(stash);
1013 /* invalidate assorted caches */
1014 ++PL_sub_generation;
1015 hv_clear(PL_stashcache);
1018 * Execute plperl.on_plperl_init in the locked-down interpreter
1020 if (plperl_on_plperl_init && *plperl_on_plperl_init)
1022 eval_pv(plperl_on_plperl_init, FALSE);
1023 /* XXX need to find a way to determine a better errcode here */
1024 if (SvTRUE(ERRSV))
1025 ereport(ERROR,
1026 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1027 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
1028 errcontext("while executing plperl.on_plperl_init")));
1034 * Initialize the current Perl interpreter as an untrusted interp
1036 static void
1037 plperl_untrusted_init(void)
1039 dTHX;
1042 * Nothing to do except execute plperl.on_plperlu_init
1044 if (plperl_on_plperlu_init && *plperl_on_plperlu_init)
1046 eval_pv(plperl_on_plperlu_init, FALSE);
1047 if (SvTRUE(ERRSV))
1048 ereport(ERROR,
1049 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1050 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV))),
1051 errcontext("while executing plperl.on_plperlu_init")));
1057 * Perl likes to put a newline after its error messages; clean up such
1059 static char *
1060 strip_trailing_ws(const char *msg)
1062 char *res = pstrdup(msg);
1063 int len = strlen(res);
1065 while (len > 0 && isspace((unsigned char) res[len - 1]))
1066 res[--len] = '\0';
1067 return res;
1071 /* Build a tuple from a hash. */
1073 static HeapTuple
1074 plperl_build_tuple_result(HV *perlhash, TupleDesc td)
1076 dTHX;
1077 Datum *values;
1078 bool *nulls;
1079 HE *he;
1080 HeapTuple tup;
1082 values = palloc0(sizeof(Datum) * td->natts);
1083 nulls = palloc(sizeof(bool) * td->natts);
1084 memset(nulls, true, sizeof(bool) * td->natts);
1086 hv_iterinit(perlhash);
1087 while ((he = hv_iternext(perlhash)))
1089 SV *val = HeVAL(he);
1090 char *key = hek2cstr(he);
1091 int attn = SPI_fnumber(td, key);
1092 Form_pg_attribute attr = TupleDescAttr(td, attn - 1);
1094 if (attn == SPI_ERROR_NOATTRIBUTE)
1095 ereport(ERROR,
1096 (errcode(ERRCODE_UNDEFINED_COLUMN),
1097 errmsg("Perl hash contains nonexistent column \"%s\"",
1098 key)));
1099 if (attn <= 0)
1100 ereport(ERROR,
1101 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1102 errmsg("cannot set system attribute \"%s\"",
1103 key)));
1105 values[attn - 1] = plperl_sv_to_datum(val,
1106 attr->atttypid,
1107 attr->atttypmod,
1108 NULL,
1109 NULL,
1110 InvalidOid,
1111 &nulls[attn - 1]);
1113 pfree(key);
1115 hv_iterinit(perlhash);
1117 tup = heap_form_tuple(td, values, nulls);
1118 pfree(values);
1119 pfree(nulls);
1120 return tup;
1123 /* convert a hash reference to a datum */
1124 static Datum
1125 plperl_hash_to_datum(SV *src, TupleDesc td)
1127 HeapTuple tup = plperl_build_tuple_result((HV *) SvRV(src), td);
1129 return HeapTupleGetDatum(tup);
1133 * if we are an array ref return the reference. this is special in that if we
1134 * are a PostgreSQL::InServer::ARRAY object we will return the 'magic' array.
1136 static SV *
1137 get_perl_array_ref(SV *sv)
1139 dTHX;
1141 if (SvOK(sv) && SvROK(sv))
1143 if (SvTYPE(SvRV(sv)) == SVt_PVAV)
1144 return sv;
1145 else if (sv_isa(sv, "PostgreSQL::InServer::ARRAY"))
1147 HV *hv = (HV *) SvRV(sv);
1148 SV **sav = hv_fetch_string(hv, "array");
1150 if (*sav && SvOK(*sav) && SvROK(*sav) &&
1151 SvTYPE(SvRV(*sav)) == SVt_PVAV)
1152 return *sav;
1154 elog(ERROR, "could not get array reference from PostgreSQL::InServer::ARRAY object");
1157 return NULL;
1161 * helper function for plperl_array_to_datum, recurses for multi-D arrays
1163 * The ArrayBuildState is created only when we first find a scalar element;
1164 * if we didn't do it like that, we'd need some other convention for knowing
1165 * whether we'd already found any scalars (and thus the number of dimensions
1166 * is frozen).
1168 static void
1169 array_to_datum_internal(AV *av, ArrayBuildState **astatep,
1170 int *ndims, int *dims, int cur_depth,
1171 Oid elemtypid, int32 typmod,
1172 FmgrInfo *finfo, Oid typioparam)
1174 dTHX;
1175 int i;
1176 int len = av_len(av) + 1;
1178 for (i = 0; i < len; i++)
1180 /* fetch the array element */
1181 SV **svp = av_fetch(av, i, FALSE);
1183 /* see if this element is an array, if so get that */
1184 SV *sav = svp ? get_perl_array_ref(*svp) : NULL;
1186 /* multi-dimensional array? */
1187 if (sav)
1189 AV *nav = (AV *) SvRV(sav);
1191 /* set size when at first element in this level, else compare */
1192 if (i == 0 && *ndims == cur_depth)
1194 /* array after some scalars at same level? */
1195 if (*astatep != NULL)
1196 ereport(ERROR,
1197 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1198 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1199 /* too many dimensions? */
1200 if (cur_depth + 1 > MAXDIM)
1201 ereport(ERROR,
1202 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1203 errmsg("number of array dimensions exceeds the maximum allowed (%d)",
1204 MAXDIM)));
1205 /* OK, add a dimension */
1206 dims[*ndims] = av_len(nav) + 1;
1207 (*ndims)++;
1209 else if (cur_depth >= *ndims ||
1210 av_len(nav) + 1 != dims[cur_depth])
1211 ereport(ERROR,
1212 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1213 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1215 /* recurse to fetch elements of this sub-array */
1216 array_to_datum_internal(nav, astatep,
1217 ndims, dims, cur_depth + 1,
1218 elemtypid, typmod,
1219 finfo, typioparam);
1221 else
1223 Datum dat;
1224 bool isnull;
1226 /* scalar after some sub-arrays at same level? */
1227 if (*ndims != cur_depth)
1228 ereport(ERROR,
1229 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1230 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1232 dat = plperl_sv_to_datum(svp ? *svp : NULL,
1233 elemtypid,
1234 typmod,
1235 NULL,
1236 finfo,
1237 typioparam,
1238 &isnull);
1240 /* Create ArrayBuildState if we didn't already */
1241 if (*astatep == NULL)
1242 *astatep = initArrayResult(elemtypid,
1243 CurrentMemoryContext, true);
1245 /* ... and save the element value in it */
1246 (void) accumArrayResult(*astatep, dat, isnull,
1247 elemtypid, CurrentMemoryContext);
1253 * convert perl array ref to a datum
1255 static Datum
1256 plperl_array_to_datum(SV *src, Oid typid, int32 typmod)
1258 dTHX;
1259 AV *nav = (AV *) SvRV(src);
1260 ArrayBuildState *astate = NULL;
1261 Oid elemtypid;
1262 FmgrInfo finfo;
1263 Oid typioparam;
1264 int dims[MAXDIM];
1265 int lbs[MAXDIM];
1266 int ndims = 1;
1267 int i;
1269 elemtypid = get_element_type(typid);
1270 if (!elemtypid)
1271 ereport(ERROR,
1272 (errcode(ERRCODE_DATATYPE_MISMATCH),
1273 errmsg("cannot convert Perl array to non-array type %s",
1274 format_type_be(typid))));
1276 _sv_to_datum_finfo(elemtypid, &finfo, &typioparam);
1278 memset(dims, 0, sizeof(dims));
1279 dims[0] = av_len(nav) + 1;
1281 array_to_datum_internal(nav, &astate,
1282 &ndims, dims, 1,
1283 elemtypid, typmod,
1284 &finfo, typioparam);
1286 /* ensure we get zero-D array for no inputs, as per PG convention */
1287 if (astate == NULL)
1288 return PointerGetDatum(construct_empty_array(elemtypid));
1290 for (i = 0; i < ndims; i++)
1291 lbs[i] = 1;
1293 return makeMdArrayResult(astate, ndims, dims, lbs,
1294 CurrentMemoryContext, true);
1297 /* Get the information needed to convert data to the specified PG type */
1298 static void
1299 _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam)
1301 Oid typinput;
1303 /* XXX would be better to cache these lookups */
1304 getTypeInputInfo(typid,
1305 &typinput, typioparam);
1306 fmgr_info(typinput, finfo);
1310 * convert Perl SV to PG datum of type typid, typmod typmod
1312 * Pass the PL/Perl function's fcinfo when attempting to convert to the
1313 * function's result type; otherwise pass NULL. This is used when we need to
1314 * resolve the actual result type of a function returning RECORD.
1316 * finfo and typioparam should be the results of _sv_to_datum_finfo for the
1317 * given typid, or NULL/InvalidOid to let this function do the lookups.
1319 * *isnull is an output parameter.
1321 static Datum
1322 plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod,
1323 FunctionCallInfo fcinfo,
1324 FmgrInfo *finfo, Oid typioparam,
1325 bool *isnull)
1327 FmgrInfo tmp;
1328 Oid funcid;
1330 /* we might recurse */
1331 check_stack_depth();
1333 *isnull = false;
1336 * Return NULL if result is undef, or if we're in a function returning
1337 * VOID. In the latter case, we should pay no attention to the last Perl
1338 * statement's result, and this is a convenient means to ensure that.
1340 if (!sv || !SvOK(sv) || typid == VOIDOID)
1342 /* look up type info if they did not pass it */
1343 if (!finfo)
1345 _sv_to_datum_finfo(typid, &tmp, &typioparam);
1346 finfo = &tmp;
1348 *isnull = true;
1349 /* must call typinput in case it wants to reject NULL */
1350 return InputFunctionCall(finfo, NULL, typioparam, typmod);
1352 else if ((funcid = get_transform_tosql(typid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
1353 return OidFunctionCall1(funcid, PointerGetDatum(sv));
1354 else if (SvROK(sv))
1356 /* handle references */
1357 SV *sav = get_perl_array_ref(sv);
1359 if (sav)
1361 /* handle an arrayref */
1362 return plperl_array_to_datum(sav, typid, typmod);
1364 else if (SvTYPE(SvRV(sv)) == SVt_PVHV)
1366 /* handle a hashref */
1367 Datum ret;
1368 TupleDesc td;
1369 bool isdomain;
1371 if (!type_is_rowtype(typid))
1372 ereport(ERROR,
1373 (errcode(ERRCODE_DATATYPE_MISMATCH),
1374 errmsg("cannot convert Perl hash to non-composite type %s",
1375 format_type_be(typid))));
1377 td = lookup_rowtype_tupdesc_domain(typid, typmod, true);
1378 if (td != NULL)
1380 /* Did we look through a domain? */
1381 isdomain = (typid != td->tdtypeid);
1383 else
1385 /* Must be RECORD, try to resolve based on call info */
1386 TypeFuncClass funcclass;
1388 if (fcinfo)
1389 funcclass = get_call_result_type(fcinfo, &typid, &td);
1390 else
1391 funcclass = TYPEFUNC_OTHER;
1392 if (funcclass != TYPEFUNC_COMPOSITE &&
1393 funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
1394 ereport(ERROR,
1395 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1396 errmsg("function returning record called in context "
1397 "that cannot accept type record")));
1398 Assert(td);
1399 isdomain = (funcclass == TYPEFUNC_COMPOSITE_DOMAIN);
1402 ret = plperl_hash_to_datum(sv, td);
1404 if (isdomain)
1405 domain_check(ret, false, typid, NULL, NULL);
1407 /* Release on the result of get_call_result_type is harmless */
1408 ReleaseTupleDesc(td);
1410 return ret;
1414 * If it's a reference to something else, such as a scalar, just
1415 * recursively look through the reference.
1417 return plperl_sv_to_datum(SvRV(sv), typid, typmod,
1418 fcinfo, finfo, typioparam,
1419 isnull);
1421 else
1423 /* handle a string/number */
1424 Datum ret;
1425 char *str = sv2cstr(sv);
1427 /* did not pass in any typeinfo? look it up */
1428 if (!finfo)
1430 _sv_to_datum_finfo(typid, &tmp, &typioparam);
1431 finfo = &tmp;
1434 ret = InputFunctionCall(finfo, str, typioparam, typmod);
1435 pfree(str);
1437 return ret;
1441 /* Convert the perl SV to a string returned by the type output function */
1442 char *
1443 plperl_sv_to_literal(SV *sv, char *fqtypename)
1445 Oid typid;
1446 Oid typoutput;
1447 Datum datum;
1448 bool typisvarlena,
1449 isnull;
1451 check_spi_usage_allowed();
1453 typid = DirectFunctionCall1(regtypein, CStringGetDatum(fqtypename));
1454 if (!OidIsValid(typid))
1455 ereport(ERROR,
1456 (errcode(ERRCODE_UNDEFINED_OBJECT),
1457 errmsg("lookup failed for type %s", fqtypename)));
1459 datum = plperl_sv_to_datum(sv,
1460 typid, -1,
1461 NULL, NULL, InvalidOid,
1462 &isnull);
1464 if (isnull)
1465 return NULL;
1467 getTypeOutputInfo(typid,
1468 &typoutput, &typisvarlena);
1470 return OidOutputFunctionCall(typoutput, datum);
1474 * Convert PostgreSQL array datum to a perl array reference.
1476 * typid is arg's OID, which must be an array type.
1478 static SV *
1479 plperl_ref_from_pg_array(Datum arg, Oid typid)
1481 dTHX;
1482 ArrayType *ar = DatumGetArrayTypeP(arg);
1483 Oid elementtype = ARR_ELEMTYPE(ar);
1484 int16 typlen;
1485 bool typbyval;
1486 char typalign,
1487 typdelim;
1488 Oid typioparam;
1489 Oid typoutputfunc;
1490 Oid transform_funcid;
1491 int i,
1492 nitems,
1493 *dims;
1494 plperl_array_info *info;
1495 SV *av;
1496 HV *hv;
1499 * Currently we make no effort to cache any of the stuff we look up here,
1500 * which is bad.
1502 info = palloc0(sizeof(plperl_array_info));
1504 /* get element type information, including output conversion function */
1505 get_type_io_data(elementtype, IOFunc_output,
1506 &typlen, &typbyval, &typalign,
1507 &typdelim, &typioparam, &typoutputfunc);
1509 /* Check for a transform function */
1510 transform_funcid = get_transform_fromsql(elementtype,
1511 current_call_data->prodesc->lang_oid,
1512 current_call_data->prodesc->trftypes);
1514 /* Look up transform or output function as appropriate */
1515 if (OidIsValid(transform_funcid))
1516 fmgr_info(transform_funcid, &info->transform_proc);
1517 else
1518 fmgr_info(typoutputfunc, &info->proc);
1520 info->elem_is_rowtype = type_is_rowtype(elementtype);
1522 /* Get the number and bounds of array dimensions */
1523 info->ndims = ARR_NDIM(ar);
1524 dims = ARR_DIMS(ar);
1526 /* No dimensions? Return an empty array */
1527 if (info->ndims == 0)
1529 av = newRV_noinc((SV *) newAV());
1531 else
1533 deconstruct_array(ar, elementtype, typlen, typbyval,
1534 typalign, &info->elements, &info->nulls,
1535 &nitems);
1537 /* Get total number of elements in each dimension */
1538 info->nelems = palloc(sizeof(int) * info->ndims);
1539 info->nelems[0] = nitems;
1540 for (i = 1; i < info->ndims; i++)
1541 info->nelems[i] = info->nelems[i - 1] / dims[i - 1];
1543 av = split_array(info, 0, nitems, 0);
1546 hv = newHV();
1547 (void) hv_store(hv, "array", 5, av, 0);
1548 (void) hv_store(hv, "typeoid", 7, newSVuv(typid), 0);
1550 return sv_bless(newRV_noinc((SV *) hv),
1551 gv_stashpv("PostgreSQL::InServer::ARRAY", 0));
1555 * Recursively form array references from splices of the initial array
1557 static SV *
1558 split_array(plperl_array_info *info, int first, int last, int nest)
1560 dTHX;
1561 int i;
1562 AV *result;
1564 /* we should only be called when we have something to split */
1565 Assert(info->ndims > 0);
1567 /* since this function recurses, it could be driven to stack overflow */
1568 check_stack_depth();
1571 * Base case, return a reference to a single-dimensional array
1573 if (nest >= info->ndims - 1)
1574 return make_array_ref(info, first, last);
1576 result = newAV();
1577 for (i = first; i < last; i += info->nelems[nest + 1])
1579 /* Recursively form references to arrays of lower dimensions */
1580 SV *ref = split_array(info, i, i + info->nelems[nest + 1], nest + 1);
1582 av_push(result, ref);
1584 return newRV_noinc((SV *) result);
1588 * Create a Perl reference from a one-dimensional C array, converting
1589 * composite type elements to hash references.
1591 static SV *
1592 make_array_ref(plperl_array_info *info, int first, int last)
1594 dTHX;
1595 int i;
1596 AV *result = newAV();
1598 for (i = first; i < last; i++)
1600 if (info->nulls[i])
1603 * We can't use &PL_sv_undef here. See "AVs, HVs and undefined
1604 * values" in perlguts.
1606 av_push(result, newSV(0));
1608 else
1610 Datum itemvalue = info->elements[i];
1612 if (info->transform_proc.fn_oid)
1613 av_push(result, (SV *) DatumGetPointer(FunctionCall1(&info->transform_proc, itemvalue)));
1614 else if (info->elem_is_rowtype)
1615 /* Handle composite type elements */
1616 av_push(result, plperl_hash_from_datum(itemvalue));
1617 else
1619 char *val = OutputFunctionCall(&info->proc, itemvalue);
1621 av_push(result, cstr2sv(val));
1625 return newRV_noinc((SV *) result);
1628 /* Set up the arguments for a trigger call. */
1629 static SV *
1630 plperl_trigger_build_args(FunctionCallInfo fcinfo)
1632 dTHX;
1633 TriggerData *tdata;
1634 TupleDesc tupdesc;
1635 int i;
1636 char *level;
1637 char *event;
1638 char *relid;
1639 char *when;
1640 HV *hv;
1642 hv = newHV();
1643 hv_ksplit(hv, 12); /* pre-grow the hash */
1645 tdata = (TriggerData *) fcinfo->context;
1646 tupdesc = tdata->tg_relation->rd_att;
1648 relid = DatumGetCString(DirectFunctionCall1(oidout,
1649 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
1651 hv_store_string(hv, "name", cstr2sv(tdata->tg_trigger->tgname));
1652 hv_store_string(hv, "relid", cstr2sv(relid));
1655 * Note: In BEFORE trigger, stored generated columns are not computed yet,
1656 * so don't make them accessible in NEW row.
1659 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
1661 event = "INSERT";
1662 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1663 hv_store_string(hv, "new",
1664 plperl_hash_from_tuple(tdata->tg_trigtuple,
1665 tupdesc,
1666 !TRIGGER_FIRED_BEFORE(tdata->tg_event)));
1668 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
1670 event = "DELETE";
1671 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1672 hv_store_string(hv, "old",
1673 plperl_hash_from_tuple(tdata->tg_trigtuple,
1674 tupdesc,
1675 true));
1677 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
1679 event = "UPDATE";
1680 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1682 hv_store_string(hv, "old",
1683 plperl_hash_from_tuple(tdata->tg_trigtuple,
1684 tupdesc,
1685 true));
1686 hv_store_string(hv, "new",
1687 plperl_hash_from_tuple(tdata->tg_newtuple,
1688 tupdesc,
1689 !TRIGGER_FIRED_BEFORE(tdata->tg_event)));
1692 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
1693 event = "TRUNCATE";
1694 else
1695 event = "UNKNOWN";
1697 hv_store_string(hv, "event", cstr2sv(event));
1698 hv_store_string(hv, "argc", newSViv(tdata->tg_trigger->tgnargs));
1700 if (tdata->tg_trigger->tgnargs > 0)
1702 AV *av = newAV();
1704 av_extend(av, tdata->tg_trigger->tgnargs);
1705 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
1706 av_push(av, cstr2sv(tdata->tg_trigger->tgargs[i]));
1707 hv_store_string(hv, "args", newRV_noinc((SV *) av));
1710 hv_store_string(hv, "relname",
1711 cstr2sv(SPI_getrelname(tdata->tg_relation)));
1713 hv_store_string(hv, "table_name",
1714 cstr2sv(SPI_getrelname(tdata->tg_relation)));
1716 hv_store_string(hv, "table_schema",
1717 cstr2sv(SPI_getnspname(tdata->tg_relation)));
1719 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
1720 when = "BEFORE";
1721 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
1722 when = "AFTER";
1723 else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
1724 when = "INSTEAD OF";
1725 else
1726 when = "UNKNOWN";
1727 hv_store_string(hv, "when", cstr2sv(when));
1729 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1730 level = "ROW";
1731 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
1732 level = "STATEMENT";
1733 else
1734 level = "UNKNOWN";
1735 hv_store_string(hv, "level", cstr2sv(level));
1737 return newRV_noinc((SV *) hv);
1741 /* Set up the arguments for an event trigger call. */
1742 static SV *
1743 plperl_event_trigger_build_args(FunctionCallInfo fcinfo)
1745 dTHX;
1746 EventTriggerData *tdata;
1747 HV *hv;
1749 hv = newHV();
1751 tdata = (EventTriggerData *) fcinfo->context;
1753 hv_store_string(hv, "event", cstr2sv(tdata->event));
1754 hv_store_string(hv, "tag", cstr2sv(GetCommandTagName(tdata->tag)));
1756 return newRV_noinc((SV *) hv);
1759 /* Construct the modified new tuple to be returned from a trigger. */
1760 static HeapTuple
1761 plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup)
1763 dTHX;
1764 SV **svp;
1765 HV *hvNew;
1766 HE *he;
1767 HeapTuple rtup;
1768 TupleDesc tupdesc;
1769 int natts;
1770 Datum *modvalues;
1771 bool *modnulls;
1772 bool *modrepls;
1774 svp = hv_fetch_string(hvTD, "new");
1775 if (!svp)
1776 ereport(ERROR,
1777 (errcode(ERRCODE_UNDEFINED_COLUMN),
1778 errmsg("$_TD->{new} does not exist")));
1779 if (!SvOK(*svp) || !SvROK(*svp) || SvTYPE(SvRV(*svp)) != SVt_PVHV)
1780 ereport(ERROR,
1781 (errcode(ERRCODE_DATATYPE_MISMATCH),
1782 errmsg("$_TD->{new} is not a hash reference")));
1783 hvNew = (HV *) SvRV(*svp);
1785 tupdesc = tdata->tg_relation->rd_att;
1786 natts = tupdesc->natts;
1788 modvalues = (Datum *) palloc0(natts * sizeof(Datum));
1789 modnulls = (bool *) palloc0(natts * sizeof(bool));
1790 modrepls = (bool *) palloc0(natts * sizeof(bool));
1792 hv_iterinit(hvNew);
1793 while ((he = hv_iternext(hvNew)))
1795 char *key = hek2cstr(he);
1796 SV *val = HeVAL(he);
1797 int attn = SPI_fnumber(tupdesc, key);
1798 Form_pg_attribute attr = TupleDescAttr(tupdesc, attn - 1);
1800 if (attn == SPI_ERROR_NOATTRIBUTE)
1801 ereport(ERROR,
1802 (errcode(ERRCODE_UNDEFINED_COLUMN),
1803 errmsg("Perl hash contains nonexistent column \"%s\"",
1804 key)));
1805 if (attn <= 0)
1806 ereport(ERROR,
1807 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1808 errmsg("cannot set system attribute \"%s\"",
1809 key)));
1810 if (attr->attgenerated)
1811 ereport(ERROR,
1812 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1813 errmsg("cannot set generated column \"%s\"",
1814 key)));
1816 modvalues[attn - 1] = plperl_sv_to_datum(val,
1817 attr->atttypid,
1818 attr->atttypmod,
1819 NULL,
1820 NULL,
1821 InvalidOid,
1822 &modnulls[attn - 1]);
1823 modrepls[attn - 1] = true;
1825 pfree(key);
1827 hv_iterinit(hvNew);
1829 rtup = heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls);
1831 pfree(modvalues);
1832 pfree(modnulls);
1833 pfree(modrepls);
1835 return rtup;
1840 * There are three externally visible pieces to plperl: plperl_call_handler,
1841 * plperl_inline_handler, and plperl_validator.
1845 * The call handler is called to run normal functions (including trigger
1846 * functions) that are defined in pg_proc.
1848 PG_FUNCTION_INFO_V1(plperl_call_handler);
1850 Datum
1851 plperl_call_handler(PG_FUNCTION_ARGS)
1853 Datum retval = (Datum) 0;
1854 plperl_call_data *volatile save_call_data = current_call_data;
1855 plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1856 plperl_call_data this_call_data;
1858 /* Initialize current-call status record */
1859 MemSet(&this_call_data, 0, sizeof(this_call_data));
1860 this_call_data.fcinfo = fcinfo;
1862 PG_TRY();
1864 current_call_data = &this_call_data;
1865 if (CALLED_AS_TRIGGER(fcinfo))
1866 retval = plperl_trigger_handler(fcinfo);
1867 else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
1869 plperl_event_trigger_handler(fcinfo);
1870 retval = (Datum) 0;
1872 else
1873 retval = plperl_func_handler(fcinfo);
1875 PG_FINALLY();
1877 current_call_data = save_call_data;
1878 activate_interpreter(oldinterp);
1879 if (this_call_data.prodesc)
1880 decrement_prodesc_refcount(this_call_data.prodesc);
1882 PG_END_TRY();
1884 return retval;
1888 * The inline handler runs anonymous code blocks (DO blocks).
1890 PG_FUNCTION_INFO_V1(plperl_inline_handler);
1892 Datum
1893 plperl_inline_handler(PG_FUNCTION_ARGS)
1895 LOCAL_FCINFO(fake_fcinfo, 0);
1896 InlineCodeBlock *codeblock = (InlineCodeBlock *) PG_GETARG_POINTER(0);
1897 FmgrInfo flinfo;
1898 plperl_proc_desc desc;
1899 plperl_call_data *volatile save_call_data = current_call_data;
1900 plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1901 plperl_call_data this_call_data;
1902 ErrorContextCallback pl_error_context;
1904 /* Initialize current-call status record */
1905 MemSet(&this_call_data, 0, sizeof(this_call_data));
1907 /* Set up a callback for error reporting */
1908 pl_error_context.callback = plperl_inline_callback;
1909 pl_error_context.previous = error_context_stack;
1910 pl_error_context.arg = NULL;
1911 error_context_stack = &pl_error_context;
1914 * Set up a fake fcinfo and descriptor with just enough info to satisfy
1915 * plperl_call_perl_func(). In particular note that this sets things up
1916 * with no arguments passed, and a result type of VOID.
1918 MemSet(fake_fcinfo, 0, SizeForFunctionCallInfo(0));
1919 MemSet(&flinfo, 0, sizeof(flinfo));
1920 MemSet(&desc, 0, sizeof(desc));
1921 fake_fcinfo->flinfo = &flinfo;
1922 flinfo.fn_oid = InvalidOid;
1923 flinfo.fn_mcxt = CurrentMemoryContext;
1925 desc.proname = "inline_code_block";
1926 desc.fn_readonly = false;
1928 desc.lang_oid = codeblock->langOid;
1929 desc.trftypes = NIL;
1930 desc.lanpltrusted = codeblock->langIsTrusted;
1932 desc.fn_retistuple = false;
1933 desc.fn_retisset = false;
1934 desc.fn_retisarray = false;
1935 desc.result_oid = InvalidOid;
1936 desc.nargs = 0;
1937 desc.reference = NULL;
1939 this_call_data.fcinfo = fake_fcinfo;
1940 this_call_data.prodesc = &desc;
1941 /* we do not bother with refcounting the fake prodesc */
1943 PG_TRY();
1945 SV *perlret;
1947 current_call_data = &this_call_data;
1949 SPI_connect_ext(codeblock->atomic ? 0 : SPI_OPT_NONATOMIC);
1951 select_perl_context(desc.lanpltrusted);
1953 plperl_create_sub(&desc, codeblock->source_text, 0);
1955 if (!desc.reference) /* can this happen? */
1956 elog(ERROR, "could not create internal procedure for anonymous code block");
1958 perlret = plperl_call_perl_func(&desc, fake_fcinfo);
1960 SvREFCNT_dec_current(perlret);
1962 if (SPI_finish() != SPI_OK_FINISH)
1963 elog(ERROR, "SPI_finish() failed");
1965 PG_FINALLY();
1967 if (desc.reference)
1968 SvREFCNT_dec_current(desc.reference);
1969 current_call_data = save_call_data;
1970 activate_interpreter(oldinterp);
1972 PG_END_TRY();
1974 error_context_stack = pl_error_context.previous;
1976 PG_RETURN_VOID();
1980 * The validator is called during CREATE FUNCTION to validate the function
1981 * being created/replaced. The precise behavior of the validator may be
1982 * modified by the check_function_bodies GUC.
1984 PG_FUNCTION_INFO_V1(plperl_validator);
1986 Datum
1987 plperl_validator(PG_FUNCTION_ARGS)
1989 Oid funcoid = PG_GETARG_OID(0);
1990 HeapTuple tuple;
1991 Form_pg_proc proc;
1992 char functyptype;
1993 int numargs;
1994 Oid *argtypes;
1995 char **argnames;
1996 char *argmodes;
1997 bool is_trigger = false;
1998 bool is_event_trigger = false;
1999 int i;
2001 if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
2002 PG_RETURN_VOID();
2004 /* Get the new function's pg_proc entry */
2005 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
2006 if (!HeapTupleIsValid(tuple))
2007 elog(ERROR, "cache lookup failed for function %u", funcoid);
2008 proc = (Form_pg_proc) GETSTRUCT(tuple);
2010 functyptype = get_typtype(proc->prorettype);
2012 /* Disallow pseudotype result */
2013 /* except for TRIGGER, EVTTRIGGER, RECORD, or VOID */
2014 if (functyptype == TYPTYPE_PSEUDO)
2016 if (proc->prorettype == TRIGGEROID)
2017 is_trigger = true;
2018 else if (proc->prorettype == EVENT_TRIGGEROID)
2019 is_event_trigger = true;
2020 else if (proc->prorettype != RECORDOID &&
2021 proc->prorettype != VOIDOID)
2022 ereport(ERROR,
2023 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2024 errmsg("PL/Perl functions cannot return type %s",
2025 format_type_be(proc->prorettype))));
2028 /* Disallow pseudotypes in arguments (either IN or OUT) */
2029 numargs = get_func_arg_info(tuple,
2030 &argtypes, &argnames, &argmodes);
2031 for (i = 0; i < numargs; i++)
2033 if (get_typtype(argtypes[i]) == TYPTYPE_PSEUDO &&
2034 argtypes[i] != RECORDOID)
2035 ereport(ERROR,
2036 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2037 errmsg("PL/Perl functions cannot accept type %s",
2038 format_type_be(argtypes[i]))));
2041 ReleaseSysCache(tuple);
2043 /* Postpone body checks if !check_function_bodies */
2044 if (check_function_bodies)
2046 (void) compile_plperl_function(funcoid, is_trigger, is_event_trigger);
2049 /* the result of a validator is ignored */
2050 PG_RETURN_VOID();
2055 * plperlu likewise requires three externally visible functions:
2056 * plperlu_call_handler, plperlu_inline_handler, and plperlu_validator.
2057 * These are currently just aliases that send control to the plperl
2058 * handler functions, and we decide whether a particular function is
2059 * trusted or not by inspecting the actual pg_language tuple.
2062 PG_FUNCTION_INFO_V1(plperlu_call_handler);
2064 Datum
2065 plperlu_call_handler(PG_FUNCTION_ARGS)
2067 return plperl_call_handler(fcinfo);
2070 PG_FUNCTION_INFO_V1(plperlu_inline_handler);
2072 Datum
2073 plperlu_inline_handler(PG_FUNCTION_ARGS)
2075 return plperl_inline_handler(fcinfo);
2078 PG_FUNCTION_INFO_V1(plperlu_validator);
2080 Datum
2081 plperlu_validator(PG_FUNCTION_ARGS)
2083 /* call plperl validator with our fcinfo so it gets our oid */
2084 return plperl_validator(fcinfo);
2089 * Uses mkfunc to create a subroutine whose text is
2090 * supplied in s, and returns a reference to it
2092 static void
2093 plperl_create_sub(plperl_proc_desc *prodesc, const char *s, Oid fn_oid)
2095 dTHX;
2096 dSP;
2097 char subname[NAMEDATALEN + 40];
2098 HV *pragma_hv = newHV();
2099 SV *subref = NULL;
2100 int count;
2102 sprintf(subname, "%s__%u", prodesc->proname, fn_oid);
2104 if (plperl_use_strict)
2105 hv_store_string(pragma_hv, "strict", (SV *) newAV());
2107 ENTER;
2108 SAVETMPS;
2109 PUSHMARK(SP);
2110 EXTEND(SP, 4);
2111 PUSHs(sv_2mortal(cstr2sv(subname)));
2112 PUSHs(sv_2mortal(newRV_noinc((SV *) pragma_hv)));
2115 * Use 'false' for $prolog in mkfunc, which is kept for compatibility in
2116 * case a module such as PostgreSQL::PLPerl::NYTprof replaces the function
2117 * compiler.
2119 PUSHs(&PL_sv_no);
2120 PUSHs(sv_2mortal(cstr2sv(s)));
2121 PUTBACK;
2124 * G_KEEPERR seems to be needed here, else we don't recognize compile
2125 * errors properly. Perhaps it's because there's another level of eval
2126 * inside mkfunc?
2128 count = call_pv("PostgreSQL::InServer::mkfunc",
2129 G_SCALAR | G_EVAL | G_KEEPERR);
2130 SPAGAIN;
2132 if (count == 1)
2134 SV *sub_rv = (SV *) POPs;
2136 if (sub_rv && SvROK(sub_rv) && SvTYPE(SvRV(sub_rv)) == SVt_PVCV)
2138 subref = newRV_inc(SvRV(sub_rv));
2142 PUTBACK;
2143 FREETMPS;
2144 LEAVE;
2146 if (SvTRUE(ERRSV))
2147 ereport(ERROR,
2148 (errcode(ERRCODE_SYNTAX_ERROR),
2149 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2151 if (!subref)
2152 ereport(ERROR,
2153 (errcode(ERRCODE_SYNTAX_ERROR),
2154 errmsg("didn't get a CODE reference from compiling function \"%s\"",
2155 prodesc->proname)));
2157 prodesc->reference = subref;
2161 /**********************************************************************
2162 * plperl_init_shared_libs() -
2163 **********************************************************************/
2165 static void
2166 plperl_init_shared_libs(pTHX)
2168 char *file = __FILE__;
2170 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2171 newXS("PostgreSQL::InServer::Util::bootstrap",
2172 boot_PostgreSQL__InServer__Util, file);
2173 /* newXS for...::SPI::bootstrap is in select_perl_context() */
2177 static SV *
2178 plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
2180 dTHX;
2181 dSP;
2182 SV *retval;
2183 int i;
2184 int count;
2185 Oid *argtypes = NULL;
2186 int nargs = 0;
2188 ENTER;
2189 SAVETMPS;
2191 PUSHMARK(SP);
2192 EXTEND(sp, desc->nargs);
2194 /* Get signature for true functions; inline blocks have no args. */
2195 if (fcinfo->flinfo->fn_oid)
2196 get_func_signature(fcinfo->flinfo->fn_oid, &argtypes, &nargs);
2197 Assert(nargs == desc->nargs);
2199 for (i = 0; i < desc->nargs; i++)
2201 if (fcinfo->args[i].isnull)
2202 PUSHs(&PL_sv_undef);
2203 else if (desc->arg_is_rowtype[i])
2205 SV *sv = plperl_hash_from_datum(fcinfo->args[i].value);
2207 PUSHs(sv_2mortal(sv));
2209 else
2211 SV *sv;
2212 Oid funcid;
2214 if (OidIsValid(desc->arg_arraytype[i]))
2215 sv = plperl_ref_from_pg_array(fcinfo->args[i].value, desc->arg_arraytype[i]);
2216 else if ((funcid = get_transform_fromsql(argtypes[i], current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
2217 sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, fcinfo->args[i].value));
2218 else
2220 char *tmp;
2222 tmp = OutputFunctionCall(&(desc->arg_out_func[i]),
2223 fcinfo->args[i].value);
2224 sv = cstr2sv(tmp);
2225 pfree(tmp);
2228 PUSHs(sv_2mortal(sv));
2231 PUTBACK;
2233 /* Do NOT use G_KEEPERR here */
2234 count = call_sv(desc->reference, G_SCALAR | G_EVAL);
2236 SPAGAIN;
2238 if (count != 1)
2240 PUTBACK;
2241 FREETMPS;
2242 LEAVE;
2243 ereport(ERROR,
2244 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2245 errmsg("didn't get a return item from function")));
2248 if (SvTRUE(ERRSV))
2250 (void) POPs;
2251 PUTBACK;
2252 FREETMPS;
2253 LEAVE;
2254 /* XXX need to find a way to determine a better errcode here */
2255 ereport(ERROR,
2256 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2257 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2260 retval = newSVsv(POPs);
2262 PUTBACK;
2263 FREETMPS;
2264 LEAVE;
2266 return retval;
2270 static SV *
2271 plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo,
2272 SV *td)
2274 dTHX;
2275 dSP;
2276 SV *retval,
2277 *TDsv;
2278 int i,
2279 count;
2280 Trigger *tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
2282 ENTER;
2283 SAVETMPS;
2285 TDsv = get_sv("main::_TD", 0);
2286 if (!TDsv)
2287 ereport(ERROR,
2288 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2289 errmsg("couldn't fetch $_TD")));
2291 save_item(TDsv); /* local $_TD */
2292 sv_setsv(TDsv, td);
2294 PUSHMARK(sp);
2295 EXTEND(sp, tg_trigger->tgnargs);
2297 for (i = 0; i < tg_trigger->tgnargs; i++)
2298 PUSHs(sv_2mortal(cstr2sv(tg_trigger->tgargs[i])));
2299 PUTBACK;
2301 /* Do NOT use G_KEEPERR here */
2302 count = call_sv(desc->reference, G_SCALAR | G_EVAL);
2304 SPAGAIN;
2306 if (count != 1)
2308 PUTBACK;
2309 FREETMPS;
2310 LEAVE;
2311 ereport(ERROR,
2312 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2313 errmsg("didn't get a return item from trigger function")));
2316 if (SvTRUE(ERRSV))
2318 (void) POPs;
2319 PUTBACK;
2320 FREETMPS;
2321 LEAVE;
2322 /* XXX need to find a way to determine a better errcode here */
2323 ereport(ERROR,
2324 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2325 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2328 retval = newSVsv(POPs);
2330 PUTBACK;
2331 FREETMPS;
2332 LEAVE;
2334 return retval;
2338 static void
2339 plperl_call_perl_event_trigger_func(plperl_proc_desc *desc,
2340 FunctionCallInfo fcinfo,
2341 SV *td)
2343 dTHX;
2344 dSP;
2345 SV *retval,
2346 *TDsv;
2347 int count;
2349 ENTER;
2350 SAVETMPS;
2352 TDsv = get_sv("main::_TD", 0);
2353 if (!TDsv)
2354 ereport(ERROR,
2355 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2356 errmsg("couldn't fetch $_TD")));
2358 save_item(TDsv); /* local $_TD */
2359 sv_setsv(TDsv, td);
2361 PUSHMARK(sp);
2362 PUTBACK;
2364 /* Do NOT use G_KEEPERR here */
2365 count = call_sv(desc->reference, G_SCALAR | G_EVAL);
2367 SPAGAIN;
2369 if (count != 1)
2371 PUTBACK;
2372 FREETMPS;
2373 LEAVE;
2374 ereport(ERROR,
2375 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2376 errmsg("didn't get a return item from trigger function")));
2379 if (SvTRUE(ERRSV))
2381 (void) POPs;
2382 PUTBACK;
2383 FREETMPS;
2384 LEAVE;
2385 /* XXX need to find a way to determine a better errcode here */
2386 ereport(ERROR,
2387 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2388 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV)))));
2391 retval = newSVsv(POPs);
2392 (void) retval; /* silence compiler warning */
2394 PUTBACK;
2395 FREETMPS;
2396 LEAVE;
2399 static Datum
2400 plperl_func_handler(PG_FUNCTION_ARGS)
2402 bool nonatomic;
2403 plperl_proc_desc *prodesc;
2404 SV *perlret;
2405 Datum retval = 0;
2406 ReturnSetInfo *rsi;
2407 ErrorContextCallback pl_error_context;
2409 nonatomic = fcinfo->context &&
2410 IsA(fcinfo->context, CallContext) &&
2411 !castNode(CallContext, fcinfo->context)->atomic;
2413 SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0);
2415 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, false);
2416 current_call_data->prodesc = prodesc;
2417 increment_prodesc_refcount(prodesc);
2419 /* Set a callback for error reporting */
2420 pl_error_context.callback = plperl_exec_callback;
2421 pl_error_context.previous = error_context_stack;
2422 pl_error_context.arg = prodesc->proname;
2423 error_context_stack = &pl_error_context;
2425 rsi = (ReturnSetInfo *) fcinfo->resultinfo;
2427 if (prodesc->fn_retisset)
2429 /* Check context before allowing the call to go through */
2430 if (!rsi || !IsA(rsi, ReturnSetInfo))
2431 ereport(ERROR,
2432 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2433 errmsg("set-valued function called in context that cannot accept a set")));
2435 if (!(rsi->allowedModes & SFRM_Materialize))
2436 ereport(ERROR,
2437 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2438 errmsg("materialize mode required, but it is not allowed in this context")));
2441 activate_interpreter(prodesc->interp);
2443 perlret = plperl_call_perl_func(prodesc, fcinfo);
2445 /************************************************************
2446 * Disconnect from SPI manager and then create the return
2447 * values datum (if the input function does a palloc for it
2448 * this must not be allocated in the SPI memory context
2449 * because SPI_finish would free it).
2450 ************************************************************/
2451 if (SPI_finish() != SPI_OK_FINISH)
2452 elog(ERROR, "SPI_finish() failed");
2454 if (prodesc->fn_retisset)
2456 SV *sav;
2459 * If the Perl function returned an arrayref, we pretend that it
2460 * called return_next() for each element of the array, to handle old
2461 * SRFs that didn't know about return_next(). Any other sort of return
2462 * value is an error, except undef which means return an empty set.
2464 sav = get_perl_array_ref(perlret);
2465 if (sav)
2467 dTHX;
2468 int i = 0;
2469 SV **svp = 0;
2470 AV *rav = (AV *) SvRV(sav);
2472 while ((svp = av_fetch(rav, i, FALSE)) != NULL)
2474 plperl_return_next_internal(*svp);
2475 i++;
2478 else if (SvOK(perlret))
2480 ereport(ERROR,
2481 (errcode(ERRCODE_DATATYPE_MISMATCH),
2482 errmsg("set-returning PL/Perl function must return "
2483 "reference to array or use return_next")));
2486 rsi->returnMode = SFRM_Materialize;
2487 if (current_call_data->tuple_store)
2489 rsi->setResult = current_call_data->tuple_store;
2490 rsi->setDesc = current_call_data->ret_tdesc;
2492 retval = (Datum) 0;
2494 else if (prodesc->result_oid)
2496 retval = plperl_sv_to_datum(perlret,
2497 prodesc->result_oid,
2499 fcinfo,
2500 &prodesc->result_in_func,
2501 prodesc->result_typioparam,
2502 &fcinfo->isnull);
2504 if (fcinfo->isnull && rsi && IsA(rsi, ReturnSetInfo))
2505 rsi->isDone = ExprEndResult;
2508 /* Restore the previous error callback */
2509 error_context_stack = pl_error_context.previous;
2511 SvREFCNT_dec_current(perlret);
2513 return retval;
2517 static Datum
2518 plperl_trigger_handler(PG_FUNCTION_ARGS)
2520 plperl_proc_desc *prodesc;
2521 SV *perlret;
2522 Datum retval;
2523 SV *svTD;
2524 HV *hvTD;
2525 ErrorContextCallback pl_error_context;
2526 TriggerData *tdata;
2527 int rc PG_USED_FOR_ASSERTS_ONLY;
2529 /* Connect to SPI manager */
2530 SPI_connect();
2532 /* Make transition tables visible to this SPI connection */
2533 tdata = (TriggerData *) fcinfo->context;
2534 rc = SPI_register_trigger_data(tdata);
2535 Assert(rc >= 0);
2537 /* Find or compile the function */
2538 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true, false);
2539 current_call_data->prodesc = prodesc;
2540 increment_prodesc_refcount(prodesc);
2542 /* Set a callback for error reporting */
2543 pl_error_context.callback = plperl_exec_callback;
2544 pl_error_context.previous = error_context_stack;
2545 pl_error_context.arg = prodesc->proname;
2546 error_context_stack = &pl_error_context;
2548 activate_interpreter(prodesc->interp);
2550 svTD = plperl_trigger_build_args(fcinfo);
2551 perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
2552 hvTD = (HV *) SvRV(svTD);
2554 /************************************************************
2555 * Disconnect from SPI manager and then create the return
2556 * values datum (if the input function does a palloc for it
2557 * this must not be allocated in the SPI memory context
2558 * because SPI_finish would free it).
2559 ************************************************************/
2560 if (SPI_finish() != SPI_OK_FINISH)
2561 elog(ERROR, "SPI_finish() failed");
2563 if (perlret == NULL || !SvOK(perlret))
2565 /* undef result means go ahead with original tuple */
2566 TriggerData *trigdata = ((TriggerData *) fcinfo->context);
2568 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2569 retval = (Datum) trigdata->tg_trigtuple;
2570 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2571 retval = (Datum) trigdata->tg_newtuple;
2572 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2573 retval = (Datum) trigdata->tg_trigtuple;
2574 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
2575 retval = (Datum) trigdata->tg_trigtuple;
2576 else
2577 retval = (Datum) 0; /* can this happen? */
2579 else
2581 HeapTuple trv;
2582 char *tmp;
2584 tmp = sv2cstr(perlret);
2586 if (pg_strcasecmp(tmp, "SKIP") == 0)
2587 trv = NULL;
2588 else if (pg_strcasecmp(tmp, "MODIFY") == 0)
2590 TriggerData *trigdata = (TriggerData *) fcinfo->context;
2592 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2593 trv = plperl_modify_tuple(hvTD, trigdata,
2594 trigdata->tg_trigtuple);
2595 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2596 trv = plperl_modify_tuple(hvTD, trigdata,
2597 trigdata->tg_newtuple);
2598 else
2600 ereport(WARNING,
2601 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2602 errmsg("ignoring modified row in DELETE trigger")));
2603 trv = NULL;
2606 else
2608 ereport(ERROR,
2609 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2610 errmsg("result of PL/Perl trigger function must be undef, "
2611 "\"SKIP\", or \"MODIFY\"")));
2612 trv = NULL;
2614 retval = PointerGetDatum(trv);
2615 pfree(tmp);
2618 /* Restore the previous error callback */
2619 error_context_stack = pl_error_context.previous;
2621 SvREFCNT_dec_current(svTD);
2622 if (perlret)
2623 SvREFCNT_dec_current(perlret);
2625 return retval;
2629 static void
2630 plperl_event_trigger_handler(PG_FUNCTION_ARGS)
2632 plperl_proc_desc *prodesc;
2633 SV *svTD;
2634 ErrorContextCallback pl_error_context;
2636 /* Connect to SPI manager */
2637 SPI_connect();
2639 /* Find or compile the function */
2640 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, true);
2641 current_call_data->prodesc = prodesc;
2642 increment_prodesc_refcount(prodesc);
2644 /* Set a callback for error reporting */
2645 pl_error_context.callback = plperl_exec_callback;
2646 pl_error_context.previous = error_context_stack;
2647 pl_error_context.arg = prodesc->proname;
2648 error_context_stack = &pl_error_context;
2650 activate_interpreter(prodesc->interp);
2652 svTD = plperl_event_trigger_build_args(fcinfo);
2653 plperl_call_perl_event_trigger_func(prodesc, fcinfo, svTD);
2655 if (SPI_finish() != SPI_OK_FINISH)
2656 elog(ERROR, "SPI_finish() failed");
2658 /* Restore the previous error callback */
2659 error_context_stack = pl_error_context.previous;
2661 SvREFCNT_dec_current(svTD);
2665 static bool
2666 validate_plperl_function(plperl_proc_ptr *proc_ptr, HeapTuple procTup)
2668 if (proc_ptr && proc_ptr->proc_ptr)
2670 plperl_proc_desc *prodesc = proc_ptr->proc_ptr;
2671 bool uptodate;
2673 /************************************************************
2674 * If it's present, must check whether it's still up to date.
2675 * This is needed because CREATE OR REPLACE FUNCTION can modify the
2676 * function's pg_proc entry without changing its OID.
2677 ************************************************************/
2678 uptodate = (prodesc->fn_xmin == HeapTupleHeaderGetRawXmin(procTup->t_data) &&
2679 ItemPointerEquals(&prodesc->fn_tid, &procTup->t_self));
2681 if (uptodate)
2682 return true;
2684 /* Otherwise, unlink the obsoleted entry from the hashtable ... */
2685 proc_ptr->proc_ptr = NULL;
2686 /* ... and release the corresponding refcount, probably deleting it */
2687 decrement_prodesc_refcount(prodesc);
2690 return false;
2694 static void
2695 free_plperl_function(plperl_proc_desc *prodesc)
2697 Assert(prodesc->fn_refcount == 0);
2698 /* Release CODE reference, if we have one, from the appropriate interp */
2699 if (prodesc->reference)
2701 plperl_interp_desc *oldinterp = plperl_active_interp;
2703 activate_interpreter(prodesc->interp);
2704 SvREFCNT_dec_current(prodesc->reference);
2705 activate_interpreter(oldinterp);
2707 /* Release all PG-owned data for this proc */
2708 MemoryContextDelete(prodesc->fn_cxt);
2712 static plperl_proc_desc *
2713 compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
2715 HeapTuple procTup;
2716 Form_pg_proc procStruct;
2717 plperl_proc_key proc_key;
2718 plperl_proc_ptr *proc_ptr;
2719 plperl_proc_desc *volatile prodesc = NULL;
2720 volatile MemoryContext proc_cxt = NULL;
2721 plperl_interp_desc *oldinterp = plperl_active_interp;
2722 ErrorContextCallback plperl_error_context;
2724 /* We'll need the pg_proc tuple in any case... */
2725 procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
2726 if (!HeapTupleIsValid(procTup))
2727 elog(ERROR, "cache lookup failed for function %u", fn_oid);
2728 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
2731 * Try to find function in plperl_proc_hash. The reason for this
2732 * overcomplicated-seeming lookup procedure is that we don't know whether
2733 * it's plperl or plperlu, and don't want to spend a lookup in pg_language
2734 * to find out.
2736 proc_key.proc_id = fn_oid;
2737 proc_key.is_trigger = is_trigger;
2738 proc_key.user_id = GetUserId();
2739 proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2740 HASH_FIND, NULL);
2741 if (validate_plperl_function(proc_ptr, procTup))
2743 /* Found valid plperl entry */
2744 ReleaseSysCache(procTup);
2745 return proc_ptr->proc_ptr;
2748 /* If not found or obsolete, maybe it's plperlu */
2749 proc_key.user_id = InvalidOid;
2750 proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2751 HASH_FIND, NULL);
2752 if (validate_plperl_function(proc_ptr, procTup))
2754 /* Found valid plperlu entry */
2755 ReleaseSysCache(procTup);
2756 return proc_ptr->proc_ptr;
2759 /************************************************************
2760 * If we haven't found it in the hashtable, we analyze
2761 * the function's arguments and return type and store
2762 * the in-/out-functions in the prodesc block,
2763 * then we load the procedure into the Perl interpreter,
2764 * and last we create a new hashtable entry for it.
2765 ************************************************************/
2767 /* Set a callback for reporting compilation errors */
2768 plperl_error_context.callback = plperl_compile_callback;
2769 plperl_error_context.previous = error_context_stack;
2770 plperl_error_context.arg = NameStr(procStruct->proname);
2771 error_context_stack = &plperl_error_context;
2773 PG_TRY();
2775 HeapTuple langTup;
2776 HeapTuple typeTup;
2777 Form_pg_language langStruct;
2778 Form_pg_type typeStruct;
2779 Datum protrftypes_datum;
2780 Datum prosrcdatum;
2781 bool isnull;
2782 char *proc_source;
2783 MemoryContext oldcontext;
2785 /************************************************************
2786 * Allocate a context that will hold all PG data for the procedure.
2787 ************************************************************/
2788 proc_cxt = AllocSetContextCreate(TopMemoryContext,
2789 "PL/Perl function",
2790 ALLOCSET_SMALL_SIZES);
2792 /************************************************************
2793 * Allocate and fill a new procedure description block.
2794 * struct prodesc and subsidiary data must all live in proc_cxt.
2795 ************************************************************/
2796 oldcontext = MemoryContextSwitchTo(proc_cxt);
2797 prodesc = (plperl_proc_desc *) palloc0(sizeof(plperl_proc_desc));
2798 prodesc->proname = pstrdup(NameStr(procStruct->proname));
2799 MemoryContextSetIdentifier(proc_cxt, prodesc->proname);
2800 prodesc->fn_cxt = proc_cxt;
2801 prodesc->fn_refcount = 0;
2802 prodesc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
2803 prodesc->fn_tid = procTup->t_self;
2804 prodesc->nargs = procStruct->pronargs;
2805 prodesc->arg_out_func = (FmgrInfo *) palloc0(prodesc->nargs * sizeof(FmgrInfo));
2806 prodesc->arg_is_rowtype = (bool *) palloc0(prodesc->nargs * sizeof(bool));
2807 prodesc->arg_arraytype = (Oid *) palloc0(prodesc->nargs * sizeof(Oid));
2808 MemoryContextSwitchTo(oldcontext);
2810 /* Remember if function is STABLE/IMMUTABLE */
2811 prodesc->fn_readonly =
2812 (procStruct->provolatile != PROVOLATILE_VOLATILE);
2814 /* Fetch protrftypes */
2815 protrftypes_datum = SysCacheGetAttr(PROCOID, procTup,
2816 Anum_pg_proc_protrftypes, &isnull);
2817 MemoryContextSwitchTo(proc_cxt);
2818 prodesc->trftypes = isnull ? NIL : oid_array_to_list(protrftypes_datum);
2819 MemoryContextSwitchTo(oldcontext);
2821 /************************************************************
2822 * Lookup the pg_language tuple by Oid
2823 ************************************************************/
2824 langTup = SearchSysCache1(LANGOID,
2825 ObjectIdGetDatum(procStruct->prolang));
2826 if (!HeapTupleIsValid(langTup))
2827 elog(ERROR, "cache lookup failed for language %u",
2828 procStruct->prolang);
2829 langStruct = (Form_pg_language) GETSTRUCT(langTup);
2830 prodesc->lang_oid = langStruct->oid;
2831 prodesc->lanpltrusted = langStruct->lanpltrusted;
2832 ReleaseSysCache(langTup);
2834 /************************************************************
2835 * Get the required information for input conversion of the
2836 * return value.
2837 ************************************************************/
2838 if (!is_trigger && !is_event_trigger)
2840 Oid rettype = procStruct->prorettype;
2842 typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettype));
2843 if (!HeapTupleIsValid(typeTup))
2844 elog(ERROR, "cache lookup failed for type %u", rettype);
2845 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2847 /* Disallow pseudotype result, except VOID or RECORD */
2848 if (typeStruct->typtype == TYPTYPE_PSEUDO)
2850 if (rettype == VOIDOID ||
2851 rettype == RECORDOID)
2852 /* okay */ ;
2853 else if (rettype == TRIGGEROID ||
2854 rettype == EVENT_TRIGGEROID)
2855 ereport(ERROR,
2856 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2857 errmsg("trigger functions can only be called "
2858 "as triggers")));
2859 else
2860 ereport(ERROR,
2861 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2862 errmsg("PL/Perl functions cannot return type %s",
2863 format_type_be(rettype))));
2866 prodesc->result_oid = rettype;
2867 prodesc->fn_retisset = procStruct->proretset;
2868 prodesc->fn_retistuple = type_is_rowtype(rettype);
2869 prodesc->fn_retisarray = IsTrueArrayType(typeStruct);
2871 fmgr_info_cxt(typeStruct->typinput,
2872 &(prodesc->result_in_func),
2873 proc_cxt);
2874 prodesc->result_typioparam = getTypeIOParam(typeTup);
2876 ReleaseSysCache(typeTup);
2879 /************************************************************
2880 * Get the required information for output conversion
2881 * of all procedure arguments
2882 ************************************************************/
2883 if (!is_trigger && !is_event_trigger)
2885 int i;
2887 for (i = 0; i < prodesc->nargs; i++)
2889 Oid argtype = procStruct->proargtypes.values[i];
2891 typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype));
2892 if (!HeapTupleIsValid(typeTup))
2893 elog(ERROR, "cache lookup failed for type %u", argtype);
2894 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2896 /* Disallow pseudotype argument, except RECORD */
2897 if (typeStruct->typtype == TYPTYPE_PSEUDO &&
2898 argtype != RECORDOID)
2899 ereport(ERROR,
2900 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2901 errmsg("PL/Perl functions cannot accept type %s",
2902 format_type_be(argtype))));
2904 if (type_is_rowtype(argtype))
2905 prodesc->arg_is_rowtype[i] = true;
2906 else
2908 prodesc->arg_is_rowtype[i] = false;
2909 fmgr_info_cxt(typeStruct->typoutput,
2910 &(prodesc->arg_out_func[i]),
2911 proc_cxt);
2914 /* Identify array-type arguments */
2915 if (IsTrueArrayType(typeStruct))
2916 prodesc->arg_arraytype[i] = argtype;
2917 else
2918 prodesc->arg_arraytype[i] = InvalidOid;
2920 ReleaseSysCache(typeTup);
2924 /************************************************************
2925 * create the text of the anonymous subroutine.
2926 * we do not use a named subroutine so that we can call directly
2927 * through the reference.
2928 ************************************************************/
2929 prosrcdatum = SysCacheGetAttrNotNull(PROCOID, procTup,
2930 Anum_pg_proc_prosrc);
2931 proc_source = TextDatumGetCString(prosrcdatum);
2933 /************************************************************
2934 * Create the procedure in the appropriate interpreter
2935 ************************************************************/
2937 select_perl_context(prodesc->lanpltrusted);
2939 prodesc->interp = plperl_active_interp;
2941 plperl_create_sub(prodesc, proc_source, fn_oid);
2943 activate_interpreter(oldinterp);
2945 pfree(proc_source);
2947 if (!prodesc->reference) /* can this happen? */
2948 elog(ERROR, "could not create PL/Perl internal procedure");
2950 /************************************************************
2951 * OK, link the procedure into the correct hashtable entry.
2952 * Note we assume that the hashtable entry either doesn't exist yet,
2953 * or we already cleared its proc_ptr during the validation attempts
2954 * above. So no need to decrement an old refcount here.
2955 ************************************************************/
2956 proc_key.user_id = prodesc->lanpltrusted ? GetUserId() : InvalidOid;
2958 proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2959 HASH_ENTER, NULL);
2960 /* We assume these two steps can't throw an error: */
2961 proc_ptr->proc_ptr = prodesc;
2962 increment_prodesc_refcount(prodesc);
2964 PG_CATCH();
2967 * If we got as far as creating a reference, we should be able to use
2968 * free_plperl_function() to clean up. If not, then at most we have
2969 * some PG memory resources in proc_cxt, which we can just delete.
2971 if (prodesc && prodesc->reference)
2972 free_plperl_function(prodesc);
2973 else if (proc_cxt)
2974 MemoryContextDelete(proc_cxt);
2976 /* Be sure to restore the previous interpreter, too, for luck */
2977 activate_interpreter(oldinterp);
2979 PG_RE_THROW();
2981 PG_END_TRY();
2983 /* restore previous error callback */
2984 error_context_stack = plperl_error_context.previous;
2986 ReleaseSysCache(procTup);
2988 return prodesc;
2991 /* Build a hash from a given composite/row datum */
2992 static SV *
2993 plperl_hash_from_datum(Datum attr)
2995 HeapTupleHeader td;
2996 Oid tupType;
2997 int32 tupTypmod;
2998 TupleDesc tupdesc;
2999 HeapTupleData tmptup;
3000 SV *sv;
3002 td = DatumGetHeapTupleHeader(attr);
3004 /* Extract rowtype info and find a tupdesc */
3005 tupType = HeapTupleHeaderGetTypeId(td);
3006 tupTypmod = HeapTupleHeaderGetTypMod(td);
3007 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3009 /* Build a temporary HeapTuple control structure */
3010 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3011 tmptup.t_data = td;
3013 sv = plperl_hash_from_tuple(&tmptup, tupdesc, true);
3014 ReleaseTupleDesc(tupdesc);
3016 return sv;
3019 /* Build a hash from all attributes of a given tuple. */
3020 static SV *
3021 plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
3023 dTHX;
3024 HV *hv;
3025 int i;
3027 /* since this function recurses, it could be driven to stack overflow */
3028 check_stack_depth();
3030 hv = newHV();
3031 hv_ksplit(hv, tupdesc->natts); /* pre-grow the hash */
3033 for (i = 0; i < tupdesc->natts; i++)
3035 Datum attr;
3036 bool isnull,
3037 typisvarlena;
3038 char *attname;
3039 Oid typoutput;
3040 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3042 if (att->attisdropped)
3043 continue;
3045 if (att->attgenerated)
3047 /* don't include unless requested */
3048 if (!include_generated)
3049 continue;
3052 attname = NameStr(att->attname);
3053 attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3055 if (isnull)
3058 * Store (attname => undef) and move on. Note we can't use
3059 * &PL_sv_undef here; see "AVs, HVs and undefined values" in
3060 * perlguts for an explanation.
3062 hv_store_string(hv, attname, newSV(0));
3063 continue;
3066 if (type_is_rowtype(att->atttypid))
3068 SV *sv = plperl_hash_from_datum(attr);
3070 hv_store_string(hv, attname, sv);
3072 else
3074 SV *sv;
3075 Oid funcid;
3077 if (OidIsValid(get_base_element_type(att->atttypid)))
3078 sv = plperl_ref_from_pg_array(attr, att->atttypid);
3079 else if ((funcid = get_transform_fromsql(att->atttypid, current_call_data->prodesc->lang_oid, current_call_data->prodesc->trftypes)))
3080 sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, attr));
3081 else
3083 char *outputstr;
3085 /* XXX should have a way to cache these lookups */
3086 getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
3088 outputstr = OidOutputFunctionCall(typoutput, attr);
3089 sv = cstr2sv(outputstr);
3090 pfree(outputstr);
3093 hv_store_string(hv, attname, sv);
3096 return newRV_noinc((SV *) hv);
3100 static void
3101 check_spi_usage_allowed(void)
3103 /* see comment in plperl_fini() */
3104 if (plperl_ending)
3106 /* simple croak as we don't want to involve PostgreSQL code */
3107 croak("SPI functions can not be used in END blocks");
3111 * Disallow SPI usage if we're not executing a fully-compiled plperl
3112 * function. It might seem impossible to get here in that case, but there
3113 * are cases where Perl will try to execute code during compilation. If
3114 * we proceed we are likely to crash trying to dereference the prodesc
3115 * pointer. Working around that might be possible, but it seems unwise
3116 * because it'd allow code execution to happen while validating a
3117 * function, which is undesirable.
3119 if (current_call_data == NULL || current_call_data->prodesc == NULL)
3121 /* simple croak as we don't want to involve PostgreSQL code */
3122 croak("SPI functions can not be used during function compilation");
3127 HV *
3128 plperl_spi_exec(char *query, int limit)
3130 HV *ret_hv;
3133 * Execute the query inside a sub-transaction, so we can cope with errors
3134 * sanely
3136 MemoryContext oldcontext = CurrentMemoryContext;
3137 ResourceOwner oldowner = CurrentResourceOwner;
3139 check_spi_usage_allowed();
3141 BeginInternalSubTransaction(NULL);
3142 /* Want to run inside function's memory context */
3143 MemoryContextSwitchTo(oldcontext);
3145 PG_TRY();
3147 int spi_rv;
3149 pg_verifymbstr(query, strlen(query), false);
3151 spi_rv = SPI_execute(query, current_call_data->prodesc->fn_readonly,
3152 limit);
3153 ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
3154 spi_rv);
3156 /* Commit the inner transaction, return to outer xact context */
3157 ReleaseCurrentSubTransaction();
3158 MemoryContextSwitchTo(oldcontext);
3159 CurrentResourceOwner = oldowner;
3161 PG_CATCH();
3163 ErrorData *edata;
3165 /* Save error info */
3166 MemoryContextSwitchTo(oldcontext);
3167 edata = CopyErrorData();
3168 FlushErrorState();
3170 /* Abort the inner transaction */
3171 RollbackAndReleaseCurrentSubTransaction();
3172 MemoryContextSwitchTo(oldcontext);
3173 CurrentResourceOwner = oldowner;
3175 /* Punt the error to Perl */
3176 croak_cstr(edata->message);
3178 /* Can't get here, but keep compiler quiet */
3179 return NULL;
3181 PG_END_TRY();
3183 return ret_hv;
3187 static HV *
3188 plperl_spi_execute_fetch_result(SPITupleTable *tuptable, uint64 processed,
3189 int status)
3191 dTHX;
3192 HV *result;
3194 check_spi_usage_allowed();
3196 result = newHV();
3198 hv_store_string(result, "status",
3199 cstr2sv(SPI_result_code_string(status)));
3200 hv_store_string(result, "processed",
3201 (processed > (uint64) UV_MAX) ?
3202 newSVnv((NV) processed) :
3203 newSVuv((UV) processed));
3205 if (status > 0 && tuptable)
3207 AV *rows;
3208 SV *row;
3209 uint64 i;
3211 /* Prevent overflow in call to av_extend() */
3212 if (processed > (uint64) AV_SIZE_MAX)
3213 ereport(ERROR,
3214 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3215 errmsg("query result has too many rows to fit in a Perl array")));
3217 rows = newAV();
3218 av_extend(rows, processed);
3219 for (i = 0; i < processed; i++)
3221 row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc, true);
3222 av_push(rows, row);
3224 hv_store_string(result, "rows",
3225 newRV_noinc((SV *) rows));
3228 SPI_freetuptable(tuptable);
3230 return result;
3235 * plperl_return_next catches any error and converts it to a Perl error.
3236 * We assume (perhaps without adequate justification) that we need not abort
3237 * the current transaction if the Perl code traps the error.
3239 void
3240 plperl_return_next(SV *sv)
3242 MemoryContext oldcontext = CurrentMemoryContext;
3244 check_spi_usage_allowed();
3246 PG_TRY();
3248 plperl_return_next_internal(sv);
3250 PG_CATCH();
3252 ErrorData *edata;
3254 /* Must reset elog.c's state */
3255 MemoryContextSwitchTo(oldcontext);
3256 edata = CopyErrorData();
3257 FlushErrorState();
3259 /* Punt the error to Perl */
3260 croak_cstr(edata->message);
3262 PG_END_TRY();
3266 * plperl_return_next_internal reports any errors in Postgres fashion
3267 * (via ereport).
3269 static void
3270 plperl_return_next_internal(SV *sv)
3272 plperl_proc_desc *prodesc;
3273 FunctionCallInfo fcinfo;
3274 ReturnSetInfo *rsi;
3275 MemoryContext old_cxt;
3277 if (!sv)
3278 return;
3280 prodesc = current_call_data->prodesc;
3281 fcinfo = current_call_data->fcinfo;
3282 rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3284 if (!prodesc->fn_retisset)
3285 ereport(ERROR,
3286 (errcode(ERRCODE_SYNTAX_ERROR),
3287 errmsg("cannot use return_next in a non-SETOF function")));
3289 if (!current_call_data->ret_tdesc)
3291 TupleDesc tupdesc;
3293 Assert(!current_call_data->tuple_store);
3296 * This is the first call to return_next in the current PL/Perl
3297 * function call, so identify the output tuple type and create a
3298 * tuplestore to hold the result rows.
3300 if (prodesc->fn_retistuple)
3302 TypeFuncClass funcclass;
3303 Oid typid;
3305 funcclass = get_call_result_type(fcinfo, &typid, &tupdesc);
3306 if (funcclass != TYPEFUNC_COMPOSITE &&
3307 funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
3308 ereport(ERROR,
3309 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3310 errmsg("function returning record called in context "
3311 "that cannot accept type record")));
3312 /* if domain-over-composite, remember the domain's type OID */
3313 if (funcclass == TYPEFUNC_COMPOSITE_DOMAIN)
3314 current_call_data->cdomain_oid = typid;
3316 else
3318 tupdesc = rsi->expectedDesc;
3319 /* Protect assumption below that we return exactly one column */
3320 if (tupdesc == NULL || tupdesc->natts != 1)
3321 elog(ERROR, "expected single-column result descriptor for non-composite SETOF result");
3325 * Make sure the tuple_store and ret_tdesc are sufficiently
3326 * long-lived.
3328 old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
3330 current_call_data->ret_tdesc = CreateTupleDescCopy(tupdesc);
3331 current_call_data->tuple_store =
3332 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
3333 false, work_mem);
3335 MemoryContextSwitchTo(old_cxt);
3339 * Producing the tuple we want to return requires making plenty of
3340 * palloc() allocations that are not cleaned up. Since this function can
3341 * be called many times before the current memory context is reset, we
3342 * need to do those allocations in a temporary context.
3344 if (!current_call_data->tmp_cxt)
3346 current_call_data->tmp_cxt =
3347 AllocSetContextCreate(CurrentMemoryContext,
3348 "PL/Perl return_next temporary cxt",
3349 ALLOCSET_DEFAULT_SIZES);
3352 old_cxt = MemoryContextSwitchTo(current_call_data->tmp_cxt);
3354 if (prodesc->fn_retistuple)
3356 HeapTuple tuple;
3358 if (!(SvOK(sv) && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV))
3359 ereport(ERROR,
3360 (errcode(ERRCODE_DATATYPE_MISMATCH),
3361 errmsg("SETOF-composite-returning PL/Perl function "
3362 "must call return_next with reference to hash")));
3364 tuple = plperl_build_tuple_result((HV *) SvRV(sv),
3365 current_call_data->ret_tdesc);
3367 if (OidIsValid(current_call_data->cdomain_oid))
3368 domain_check(HeapTupleGetDatum(tuple), false,
3369 current_call_data->cdomain_oid,
3370 &current_call_data->cdomain_info,
3371 rsi->econtext->ecxt_per_query_memory);
3373 tuplestore_puttuple(current_call_data->tuple_store, tuple);
3375 else if (prodesc->result_oid)
3377 Datum ret[1];
3378 bool isNull[1];
3380 ret[0] = plperl_sv_to_datum(sv,
3381 prodesc->result_oid,
3383 fcinfo,
3384 &prodesc->result_in_func,
3385 prodesc->result_typioparam,
3386 &isNull[0]);
3388 tuplestore_putvalues(current_call_data->tuple_store,
3389 current_call_data->ret_tdesc,
3390 ret, isNull);
3393 MemoryContextSwitchTo(old_cxt);
3394 MemoryContextReset(current_call_data->tmp_cxt);
3398 SV *
3399 plperl_spi_query(char *query)
3401 SV *cursor;
3404 * Execute the query inside a sub-transaction, so we can cope with errors
3405 * sanely
3407 MemoryContext oldcontext = CurrentMemoryContext;
3408 ResourceOwner oldowner = CurrentResourceOwner;
3410 check_spi_usage_allowed();
3412 BeginInternalSubTransaction(NULL);
3413 /* Want to run inside function's memory context */
3414 MemoryContextSwitchTo(oldcontext);
3416 PG_TRY();
3418 SPIPlanPtr plan;
3419 Portal portal;
3421 /* Make sure the query is validly encoded */
3422 pg_verifymbstr(query, strlen(query), false);
3424 /* Create a cursor for the query */
3425 plan = SPI_prepare(query, 0, NULL);
3426 if (plan == NULL)
3427 elog(ERROR, "SPI_prepare() failed:%s",
3428 SPI_result_code_string(SPI_result));
3430 portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
3431 SPI_freeplan(plan);
3432 if (portal == NULL)
3433 elog(ERROR, "SPI_cursor_open() failed:%s",
3434 SPI_result_code_string(SPI_result));
3435 cursor = cstr2sv(portal->name);
3437 PinPortal(portal);
3439 /* Commit the inner transaction, return to outer xact context */
3440 ReleaseCurrentSubTransaction();
3441 MemoryContextSwitchTo(oldcontext);
3442 CurrentResourceOwner = oldowner;
3444 PG_CATCH();
3446 ErrorData *edata;
3448 /* Save error info */
3449 MemoryContextSwitchTo(oldcontext);
3450 edata = CopyErrorData();
3451 FlushErrorState();
3453 /* Abort the inner transaction */
3454 RollbackAndReleaseCurrentSubTransaction();
3455 MemoryContextSwitchTo(oldcontext);
3456 CurrentResourceOwner = oldowner;
3458 /* Punt the error to Perl */
3459 croak_cstr(edata->message);
3461 /* Can't get here, but keep compiler quiet */
3462 return NULL;
3464 PG_END_TRY();
3466 return cursor;
3470 SV *
3471 plperl_spi_fetchrow(char *cursor)
3473 SV *row;
3476 * Execute the FETCH inside a sub-transaction, so we can cope with errors
3477 * sanely
3479 MemoryContext oldcontext = CurrentMemoryContext;
3480 ResourceOwner oldowner = CurrentResourceOwner;
3482 check_spi_usage_allowed();
3484 BeginInternalSubTransaction(NULL);
3485 /* Want to run inside function's memory context */
3486 MemoryContextSwitchTo(oldcontext);
3488 PG_TRY();
3490 dTHX;
3491 Portal p = SPI_cursor_find(cursor);
3493 if (!p)
3495 row = &PL_sv_undef;
3497 else
3499 SPI_cursor_fetch(p, true, 1);
3500 if (SPI_processed == 0)
3502 UnpinPortal(p);
3503 SPI_cursor_close(p);
3504 row = &PL_sv_undef;
3506 else
3508 row = plperl_hash_from_tuple(SPI_tuptable->vals[0],
3509 SPI_tuptable->tupdesc,
3510 true);
3512 SPI_freetuptable(SPI_tuptable);
3515 /* Commit the inner transaction, return to outer xact context */
3516 ReleaseCurrentSubTransaction();
3517 MemoryContextSwitchTo(oldcontext);
3518 CurrentResourceOwner = oldowner;
3520 PG_CATCH();
3522 ErrorData *edata;
3524 /* Save error info */
3525 MemoryContextSwitchTo(oldcontext);
3526 edata = CopyErrorData();
3527 FlushErrorState();
3529 /* Abort the inner transaction */
3530 RollbackAndReleaseCurrentSubTransaction();
3531 MemoryContextSwitchTo(oldcontext);
3532 CurrentResourceOwner = oldowner;
3534 /* Punt the error to Perl */
3535 croak_cstr(edata->message);
3537 /* Can't get here, but keep compiler quiet */
3538 return NULL;
3540 PG_END_TRY();
3542 return row;
3545 void
3546 plperl_spi_cursor_close(char *cursor)
3548 Portal p;
3550 check_spi_usage_allowed();
3552 p = SPI_cursor_find(cursor);
3554 if (p)
3556 UnpinPortal(p);
3557 SPI_cursor_close(p);
3561 SV *
3562 plperl_spi_prepare(char *query, int argc, SV **argv)
3564 volatile SPIPlanPtr plan = NULL;
3565 volatile MemoryContext plan_cxt = NULL;
3566 plperl_query_desc *volatile qdesc = NULL;
3567 plperl_query_entry *volatile hash_entry = NULL;
3568 MemoryContext oldcontext = CurrentMemoryContext;
3569 ResourceOwner oldowner = CurrentResourceOwner;
3570 MemoryContext work_cxt;
3571 bool found;
3572 int i;
3574 check_spi_usage_allowed();
3576 BeginInternalSubTransaction(NULL);
3577 MemoryContextSwitchTo(oldcontext);
3579 PG_TRY();
3581 CHECK_FOR_INTERRUPTS();
3583 /************************************************************
3584 * Allocate the new querydesc structure
3586 * The qdesc struct, as well as all its subsidiary data, lives in its
3587 * plan_cxt. But note that the SPIPlan does not.
3588 ************************************************************/
3589 plan_cxt = AllocSetContextCreate(TopMemoryContext,
3590 "PL/Perl spi_prepare query",
3591 ALLOCSET_SMALL_SIZES);
3592 MemoryContextSwitchTo(plan_cxt);
3593 qdesc = (plperl_query_desc *) palloc0(sizeof(plperl_query_desc));
3594 snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
3595 qdesc->plan_cxt = plan_cxt;
3596 qdesc->nargs = argc;
3597 qdesc->argtypes = (Oid *) palloc(argc * sizeof(Oid));
3598 qdesc->arginfuncs = (FmgrInfo *) palloc(argc * sizeof(FmgrInfo));
3599 qdesc->argtypioparams = (Oid *) palloc(argc * sizeof(Oid));
3600 MemoryContextSwitchTo(oldcontext);
3602 /************************************************************
3603 * Do the following work in a short-lived context so that we don't
3604 * leak a lot of memory in the PL/Perl function's SPI Proc context.
3605 ************************************************************/
3606 work_cxt = AllocSetContextCreate(CurrentMemoryContext,
3607 "PL/Perl spi_prepare workspace",
3608 ALLOCSET_DEFAULT_SIZES);
3609 MemoryContextSwitchTo(work_cxt);
3611 /************************************************************
3612 * Resolve argument type names and then look them up by oid
3613 * in the system cache, and remember the required information
3614 * for input conversion.
3615 ************************************************************/
3616 for (i = 0; i < argc; i++)
3618 Oid typId,
3619 typInput,
3620 typIOParam;
3621 int32 typmod;
3622 char *typstr;
3624 typstr = sv2cstr(argv[i]);
3625 (void) parseTypeString(typstr, &typId, &typmod, NULL);
3626 pfree(typstr);
3628 getTypeInputInfo(typId, &typInput, &typIOParam);
3630 qdesc->argtypes[i] = typId;
3631 fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
3632 qdesc->argtypioparams[i] = typIOParam;
3635 /* Make sure the query is validly encoded */
3636 pg_verifymbstr(query, strlen(query), false);
3638 /************************************************************
3639 * Prepare the plan and check for errors
3640 ************************************************************/
3641 plan = SPI_prepare(query, argc, qdesc->argtypes);
3643 if (plan == NULL)
3644 elog(ERROR, "SPI_prepare() failed:%s",
3645 SPI_result_code_string(SPI_result));
3647 /************************************************************
3648 * Save the plan into permanent memory (right now it's in the
3649 * SPI procCxt, which will go away at function end).
3650 ************************************************************/
3651 if (SPI_keepplan(plan))
3652 elog(ERROR, "SPI_keepplan() failed");
3653 qdesc->plan = plan;
3655 /************************************************************
3656 * Insert a hashtable entry for the plan.
3657 ************************************************************/
3658 hash_entry = hash_search(plperl_active_interp->query_hash,
3659 qdesc->qname,
3660 HASH_ENTER, &found);
3661 hash_entry->query_data = qdesc;
3663 /* Get rid of workspace */
3664 MemoryContextDelete(work_cxt);
3666 /* Commit the inner transaction, return to outer xact context */
3667 ReleaseCurrentSubTransaction();
3668 MemoryContextSwitchTo(oldcontext);
3669 CurrentResourceOwner = oldowner;
3671 PG_CATCH();
3673 ErrorData *edata;
3675 /* Save error info */
3676 MemoryContextSwitchTo(oldcontext);
3677 edata = CopyErrorData();
3678 FlushErrorState();
3680 /* Drop anything we managed to allocate */
3681 if (hash_entry)
3682 hash_search(plperl_active_interp->query_hash,
3683 qdesc->qname,
3684 HASH_REMOVE, NULL);
3685 if (plan_cxt)
3686 MemoryContextDelete(plan_cxt);
3687 if (plan)
3688 SPI_freeplan(plan);
3690 /* Abort the inner transaction */
3691 RollbackAndReleaseCurrentSubTransaction();
3692 MemoryContextSwitchTo(oldcontext);
3693 CurrentResourceOwner = oldowner;
3695 /* Punt the error to Perl */
3696 croak_cstr(edata->message);
3698 /* Can't get here, but keep compiler quiet */
3699 return NULL;
3701 PG_END_TRY();
3703 /************************************************************
3704 * Return the query's hash key to the caller.
3705 ************************************************************/
3706 return cstr2sv(qdesc->qname);
3709 HV *
3710 plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
3712 HV *ret_hv;
3713 SV **sv;
3714 int i,
3715 limit,
3716 spi_rv;
3717 char *nulls;
3718 Datum *argvalues;
3719 plperl_query_desc *qdesc;
3720 plperl_query_entry *hash_entry;
3723 * Execute the query inside a sub-transaction, so we can cope with errors
3724 * sanely
3726 MemoryContext oldcontext = CurrentMemoryContext;
3727 ResourceOwner oldowner = CurrentResourceOwner;
3729 check_spi_usage_allowed();
3731 BeginInternalSubTransaction(NULL);
3732 /* Want to run inside function's memory context */
3733 MemoryContextSwitchTo(oldcontext);
3735 PG_TRY();
3737 dTHX;
3739 /************************************************************
3740 * Fetch the saved plan descriptor, see if it's o.k.
3741 ************************************************************/
3742 hash_entry = hash_search(plperl_active_interp->query_hash, query,
3743 HASH_FIND, NULL);
3744 if (hash_entry == NULL)
3745 elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
3747 qdesc = hash_entry->query_data;
3748 if (qdesc == NULL)
3749 elog(ERROR, "spi_exec_prepared: plperl query_hash value vanished");
3751 if (qdesc->nargs != argc)
3752 elog(ERROR, "spi_exec_prepared: expected %d argument(s), %d passed",
3753 qdesc->nargs, argc);
3755 /************************************************************
3756 * Parse eventual attributes
3757 ************************************************************/
3758 limit = 0;
3759 if (attr != NULL)
3761 sv = hv_fetch_string(attr, "limit");
3762 if (sv && *sv && SvIOK(*sv))
3763 limit = SvIV(*sv);
3765 /************************************************************
3766 * Set up arguments
3767 ************************************************************/
3768 if (argc > 0)
3770 nulls = (char *) palloc(argc);
3771 argvalues = (Datum *) palloc(argc * sizeof(Datum));
3773 else
3775 nulls = NULL;
3776 argvalues = NULL;
3779 for (i = 0; i < argc; i++)
3781 bool isnull;
3783 argvalues[i] = plperl_sv_to_datum(argv[i],
3784 qdesc->argtypes[i],
3786 NULL,
3787 &qdesc->arginfuncs[i],
3788 qdesc->argtypioparams[i],
3789 &isnull);
3790 nulls[i] = isnull ? 'n' : ' ';
3793 /************************************************************
3794 * go
3795 ************************************************************/
3796 spi_rv = SPI_execute_plan(qdesc->plan, argvalues, nulls,
3797 current_call_data->prodesc->fn_readonly, limit);
3798 ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
3799 spi_rv);
3800 if (argc > 0)
3802 pfree(argvalues);
3803 pfree(nulls);
3806 /* Commit the inner transaction, return to outer xact context */
3807 ReleaseCurrentSubTransaction();
3808 MemoryContextSwitchTo(oldcontext);
3809 CurrentResourceOwner = oldowner;
3811 PG_CATCH();
3813 ErrorData *edata;
3815 /* Save error info */
3816 MemoryContextSwitchTo(oldcontext);
3817 edata = CopyErrorData();
3818 FlushErrorState();
3820 /* Abort the inner transaction */
3821 RollbackAndReleaseCurrentSubTransaction();
3822 MemoryContextSwitchTo(oldcontext);
3823 CurrentResourceOwner = oldowner;
3825 /* Punt the error to Perl */
3826 croak_cstr(edata->message);
3828 /* Can't get here, but keep compiler quiet */
3829 return NULL;
3831 PG_END_TRY();
3833 return ret_hv;
3836 SV *
3837 plperl_spi_query_prepared(char *query, int argc, SV **argv)
3839 int i;
3840 char *nulls;
3841 Datum *argvalues;
3842 plperl_query_desc *qdesc;
3843 plperl_query_entry *hash_entry;
3844 SV *cursor;
3845 Portal portal = NULL;
3848 * Execute the query inside a sub-transaction, so we can cope with errors
3849 * sanely
3851 MemoryContext oldcontext = CurrentMemoryContext;
3852 ResourceOwner oldowner = CurrentResourceOwner;
3854 check_spi_usage_allowed();
3856 BeginInternalSubTransaction(NULL);
3857 /* Want to run inside function's memory context */
3858 MemoryContextSwitchTo(oldcontext);
3860 PG_TRY();
3862 /************************************************************
3863 * Fetch the saved plan descriptor, see if it's o.k.
3864 ************************************************************/
3865 hash_entry = hash_search(plperl_active_interp->query_hash, query,
3866 HASH_FIND, NULL);
3867 if (hash_entry == NULL)
3868 elog(ERROR, "spi_query_prepared: Invalid prepared query passed");
3870 qdesc = hash_entry->query_data;
3871 if (qdesc == NULL)
3872 elog(ERROR, "spi_query_prepared: plperl query_hash value vanished");
3874 if (qdesc->nargs != argc)
3875 elog(ERROR, "spi_query_prepared: expected %d argument(s), %d passed",
3876 qdesc->nargs, argc);
3878 /************************************************************
3879 * Set up arguments
3880 ************************************************************/
3881 if (argc > 0)
3883 nulls = (char *) palloc(argc);
3884 argvalues = (Datum *) palloc(argc * sizeof(Datum));
3886 else
3888 nulls = NULL;
3889 argvalues = NULL;
3892 for (i = 0; i < argc; i++)
3894 bool isnull;
3896 argvalues[i] = plperl_sv_to_datum(argv[i],
3897 qdesc->argtypes[i],
3899 NULL,
3900 &qdesc->arginfuncs[i],
3901 qdesc->argtypioparams[i],
3902 &isnull);
3903 nulls[i] = isnull ? 'n' : ' ';
3906 /************************************************************
3907 * go
3908 ************************************************************/
3909 portal = SPI_cursor_open(NULL, qdesc->plan, argvalues, nulls,
3910 current_call_data->prodesc->fn_readonly);
3911 if (argc > 0)
3913 pfree(argvalues);
3914 pfree(nulls);
3916 if (portal == NULL)
3917 elog(ERROR, "SPI_cursor_open() failed:%s",
3918 SPI_result_code_string(SPI_result));
3920 cursor = cstr2sv(portal->name);
3922 PinPortal(portal);
3924 /* Commit the inner transaction, return to outer xact context */
3925 ReleaseCurrentSubTransaction();
3926 MemoryContextSwitchTo(oldcontext);
3927 CurrentResourceOwner = oldowner;
3929 PG_CATCH();
3931 ErrorData *edata;
3933 /* Save error info */
3934 MemoryContextSwitchTo(oldcontext);
3935 edata = CopyErrorData();
3936 FlushErrorState();
3938 /* Abort the inner transaction */
3939 RollbackAndReleaseCurrentSubTransaction();
3940 MemoryContextSwitchTo(oldcontext);
3941 CurrentResourceOwner = oldowner;
3943 /* Punt the error to Perl */
3944 croak_cstr(edata->message);
3946 /* Can't get here, but keep compiler quiet */
3947 return NULL;
3949 PG_END_TRY();
3951 return cursor;
3954 void
3955 plperl_spi_freeplan(char *query)
3957 SPIPlanPtr plan;
3958 plperl_query_desc *qdesc;
3959 plperl_query_entry *hash_entry;
3961 check_spi_usage_allowed();
3963 hash_entry = hash_search(plperl_active_interp->query_hash, query,
3964 HASH_FIND, NULL);
3965 if (hash_entry == NULL)
3966 elog(ERROR, "spi_freeplan: Invalid prepared query passed");
3968 qdesc = hash_entry->query_data;
3969 if (qdesc == NULL)
3970 elog(ERROR, "spi_freeplan: plperl query_hash value vanished");
3971 plan = qdesc->plan;
3974 * free all memory before SPI_freeplan, so if it dies, nothing will be
3975 * left over
3977 hash_search(plperl_active_interp->query_hash, query,
3978 HASH_REMOVE, NULL);
3980 MemoryContextDelete(qdesc->plan_cxt);
3982 SPI_freeplan(plan);
3985 void
3986 plperl_spi_commit(void)
3988 MemoryContext oldcontext = CurrentMemoryContext;
3990 check_spi_usage_allowed();
3992 PG_TRY();
3994 SPI_commit();
3996 PG_CATCH();
3998 ErrorData *edata;
4000 /* Save error info */
4001 MemoryContextSwitchTo(oldcontext);
4002 edata = CopyErrorData();
4003 FlushErrorState();
4005 /* Punt the error to Perl */
4006 croak_cstr(edata->message);
4008 PG_END_TRY();
4011 void
4012 plperl_spi_rollback(void)
4014 MemoryContext oldcontext = CurrentMemoryContext;
4016 check_spi_usage_allowed();
4018 PG_TRY();
4020 SPI_rollback();
4022 PG_CATCH();
4024 ErrorData *edata;
4026 /* Save error info */
4027 MemoryContextSwitchTo(oldcontext);
4028 edata = CopyErrorData();
4029 FlushErrorState();
4031 /* Punt the error to Perl */
4032 croak_cstr(edata->message);
4034 PG_END_TRY();
4038 * Implementation of plperl's elog() function
4040 * If the error level is less than ERROR, we'll just emit the message and
4041 * return. When it is ERROR, elog() will longjmp, which we catch and
4042 * turn into a Perl croak(). Note we are assuming that elog() can't have
4043 * any internal failures that are so bad as to require a transaction abort.
4045 * The main reason this is out-of-line is to avoid conflicts between XSUB.h
4046 * and the PG_TRY macros.
4048 void
4049 plperl_util_elog(int level, SV *msg)
4051 MemoryContext oldcontext = CurrentMemoryContext;
4052 char *volatile cmsg = NULL;
4055 * We intentionally omit check_spi_usage_allowed() here, as this seems
4056 * safe to allow even in the contexts that that function rejects.
4059 PG_TRY();
4061 cmsg = sv2cstr(msg);
4062 elog(level, "%s", cmsg);
4063 pfree(cmsg);
4065 PG_CATCH();
4067 ErrorData *edata;
4069 /* Must reset elog.c's state */
4070 MemoryContextSwitchTo(oldcontext);
4071 edata = CopyErrorData();
4072 FlushErrorState();
4074 if (cmsg)
4075 pfree(cmsg);
4077 /* Punt the error to Perl */
4078 croak_cstr(edata->message);
4080 PG_END_TRY();
4084 * Store an SV into a hash table under a key that is a string assumed to be
4085 * in the current database's encoding.
4087 static SV **
4088 hv_store_string(HV *hv, const char *key, SV *val)
4090 dTHX;
4091 int32 hlen;
4092 char *hkey;
4093 SV **ret;
4095 hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4098 * hv_store() recognizes a negative klen parameter as meaning a UTF-8
4099 * encoded key.
4101 hlen = -(int) strlen(hkey);
4102 ret = hv_store(hv, hkey, hlen, val, 0);
4104 if (hkey != key)
4105 pfree(hkey);
4107 return ret;
4111 * Fetch an SV from a hash table under a key that is a string assumed to be
4112 * in the current database's encoding.
4114 static SV **
4115 hv_fetch_string(HV *hv, const char *key)
4117 dTHX;
4118 int32 hlen;
4119 char *hkey;
4120 SV **ret;
4122 hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4124 /* See notes in hv_store_string */
4125 hlen = -(int) strlen(hkey);
4126 ret = hv_fetch(hv, hkey, hlen, 0);
4128 if (hkey != key)
4129 pfree(hkey);
4131 return ret;
4135 * Provide function name for PL/Perl execution errors
4137 static void
4138 plperl_exec_callback(void *arg)
4140 char *procname = (char *) arg;
4142 if (procname)
4143 errcontext("PL/Perl function \"%s\"", procname);
4147 * Provide function name for PL/Perl compilation errors
4149 static void
4150 plperl_compile_callback(void *arg)
4152 char *procname = (char *) arg;
4154 if (procname)
4155 errcontext("compilation of PL/Perl function \"%s\"", procname);
4159 * Provide error context for the inline handler
4161 static void
4162 plperl_inline_callback(void *arg)
4164 errcontext("PL/Perl anonymous code block");
4169 * Perl's own setlocale(), copied from POSIX.xs
4170 * (needed because of the calls to new_*())
4172 * Starting in 5.28, perl exposes Perl_setlocale to do so.
4174 #if defined(WIN32) && PERL_VERSION_LT(5, 28, 0)
4175 static char *
4176 setlocale_perl(int category, char *locale)
4178 dTHX;
4179 char *RETVAL = setlocale(category, locale);
4181 if (RETVAL)
4183 #ifdef USE_LOCALE_CTYPE
4184 if (category == LC_CTYPE
4185 #ifdef LC_ALL
4186 || category == LC_ALL
4187 #endif
4190 char *newctype;
4192 #ifdef LC_ALL
4193 if (category == LC_ALL)
4194 newctype = setlocale(LC_CTYPE, NULL);
4195 else
4196 #endif
4197 newctype = RETVAL;
4198 new_ctype(newctype);
4200 #endif /* USE_LOCALE_CTYPE */
4201 #ifdef USE_LOCALE_COLLATE
4202 if (category == LC_COLLATE
4203 #ifdef LC_ALL
4204 || category == LC_ALL
4205 #endif
4208 char *newcoll;
4210 #ifdef LC_ALL
4211 if (category == LC_ALL)
4212 newcoll = setlocale(LC_COLLATE, NULL);
4213 else
4214 #endif
4215 newcoll = RETVAL;
4216 new_collate(newcoll);
4218 #endif /* USE_LOCALE_COLLATE */
4220 #ifdef USE_LOCALE_NUMERIC
4221 if (category == LC_NUMERIC
4222 #ifdef LC_ALL
4223 || category == LC_ALL
4224 #endif
4227 char *newnum;
4229 #ifdef LC_ALL
4230 if (category == LC_ALL)
4231 newnum = setlocale(LC_NUMERIC, NULL);
4232 else
4233 #endif
4234 newnum = RETVAL;
4235 new_numeric(newnum);
4237 #endif /* USE_LOCALE_NUMERIC */
4240 return RETVAL;
4242 #endif /* defined(WIN32) && PERL_VERSION_LT(5, 28, 0) */