1 /**********************************************************************
2 * plperl.c - perl as a procedural language for PostgreSQL
4 * src/pl/plperl/plperl.c
6 **********************************************************************/
16 /* postgreSQL stuff */
17 #include "access/htup_details.h"
18 #include "access/xact.h"
19 #include "catalog/pg_language.h"
20 #include "catalog/pg_proc.h"
21 #include "catalog/pg_type.h"
22 #include "commands/event_trigger.h"
23 #include "commands/trigger.h"
24 #include "executor/spi.h"
26 #include "mb/pg_wchar.h"
27 #include "miscadmin.h"
28 #include "nodes/makefuncs.h"
29 #include "parser/parse_type.h"
30 #include "storage/ipc.h"
31 #include "tcop/tcopprot.h"
32 #include "utils/builtins.h"
33 #include "utils/fmgroids.h"
34 #include "utils/guc.h"
35 #include "utils/hsearch.h"
36 #include "utils/lsyscache.h"
37 #include "utils/memutils.h"
38 #include "utils/rel.h"
39 #include "utils/syscache.h"
40 #include "utils/typcache.h"
42 /* define our text domain for translations */
44 #define TEXTDOMAIN PG_TEXTDOMAIN("plperl")
47 /* string literal macros defining chunks of perl code */
48 #include "perlchunks.h"
50 #include "plperl_helpers.h"
51 /* defines PLPERL_SET_OPMASK */
52 #include "plperl_opmask.h"
54 EXTERN_C
void boot_DynaLoader(pTHX_ CV
*cv
);
55 EXTERN_C
void boot_PostgreSQL__InServer__Util(pTHX_ CV
*cv
);
56 EXTERN_C
void boot_PostgreSQL__InServer__SPI(pTHX_ CV
*cv
);
60 /**********************************************************************
61 * Information associated with a Perl interpreter. We have one interpreter
62 * that is used for all plperlu (untrusted) functions. For plperl (trusted)
63 * functions, there is a separate interpreter for each effective SQL userid.
64 * (This is needed to ensure that an unprivileged user can't inject Perl code
65 * that'll be executed with the privileges of some other SQL user.)
67 * The plperl_interp_desc structs are kept in a Postgres hash table indexed
68 * by userid OID, with OID 0 used for the single untrusted interpreter.
69 * Once created, an interpreter is kept for the life of the process.
71 * We start out by creating a "held" interpreter, which we initialize
72 * only as far as we can do without deciding if it will be trusted or
73 * untrusted. Later, when we first need to run a plperl or plperlu
74 * function, we complete the initialization appropriately and move the
75 * PerlInterpreter pointer into the plperl_interp_hash hashtable. If after
76 * that we need more interpreters, we create them as needed if we can, or
77 * fail if the Perl build doesn't support multiple interpreters.
79 * The reason for all the dancing about with a held interpreter is to make
80 * it possible for people to preload a lot of Perl code at postmaster startup
81 * (using plperl.on_init) and then use that code in backends. Of course this
82 * will only work for the first interpreter created in any backend, but it's
83 * still useful with that restriction.
84 **********************************************************************/
85 typedef struct plperl_interp_desc
87 Oid user_id
; /* Hash key (must be first!) */
88 PerlInterpreter
*interp
; /* The interpreter */
89 HTAB
*query_hash
; /* plperl_query_entry structs */
93 /**********************************************************************
94 * The information we cache about loaded procedures
96 * The fn_refcount field counts the struct's reference from the hash table
97 * shown below, plus one reference for each function call level that is using
98 * the struct. We can release the struct, and the associated Perl sub, when
99 * the fn_refcount goes to zero. Releasing the struct itself is done by
100 * deleting the fn_cxt, which also gets rid of all subsidiary data.
101 **********************************************************************/
102 typedef struct plperl_proc_desc
104 char *proname
; /* user name of procedure */
105 MemoryContext fn_cxt
; /* memory context for this procedure */
106 unsigned long fn_refcount
; /* number of active references */
107 TransactionId fn_xmin
; /* xmin/TID of procedure's pg_proc tuple */
108 ItemPointerData fn_tid
;
109 SV
*reference
; /* CODE reference for Perl sub */
110 plperl_interp_desc
*interp
; /* interpreter it's created in */
111 bool fn_readonly
; /* is function readonly (not volatile)? */
114 bool lanpltrusted
; /* is it plperl, rather than plperlu? */
115 bool fn_retistuple
; /* true, if function returns tuple */
116 bool fn_retisset
; /* true, if function returns set */
117 bool fn_retisarray
; /* true if function returns array */
118 /* Conversion info for function's result type: */
119 Oid result_oid
; /* Oid of result type */
120 FmgrInfo result_in_func
; /* I/O function and arg for result type */
121 Oid result_typioparam
;
122 /* Per-argument info for function's argument types: */
124 FmgrInfo
*arg_out_func
; /* output fns for arg types */
125 bool *arg_is_rowtype
; /* is each arg composite? */
126 Oid
*arg_arraytype
; /* InvalidOid if not an array */
129 #define increment_prodesc_refcount(prodesc) \
130 ((prodesc)->fn_refcount++)
131 #define decrement_prodesc_refcount(prodesc) \
133 Assert((prodesc)->fn_refcount > 0); \
134 if (--((prodesc)->fn_refcount) == 0) \
135 free_plperl_function(prodesc); \
138 /**********************************************************************
139 * For speedy lookup, we maintain a hash table mapping from
140 * function OID + trigger flag + user OID to plperl_proc_desc pointers.
141 * The reason the plperl_proc_desc struct isn't directly part of the hash
142 * entry is to simplify recovery from errors during compile_plperl_function.
144 * Note: if the same function is called by multiple userIDs within a session,
145 * there will be a separate plperl_proc_desc entry for each userID in the case
146 * of plperl functions, but only one entry for plperlu functions, because we
147 * set user_id = 0 for that case. If the user redeclares the same function
148 * from plperl to plperlu or vice versa, there might be multiple
149 * plperl_proc_ptr entries in the hashtable, but only one is valid.
150 **********************************************************************/
151 typedef struct plperl_proc_key
153 Oid proc_id
; /* Function OID */
156 * is_trigger is really a bool, but declare as Oid to ensure this struct
157 * contains no padding
159 Oid is_trigger
; /* is it a trigger function? */
160 Oid user_id
; /* User calling the function, or 0 */
163 typedef struct plperl_proc_ptr
165 plperl_proc_key proc_key
; /* Hash key (must be first!) */
166 plperl_proc_desc
*proc_ptr
;
170 * The information we cache for the duration of a single call to a
173 typedef struct plperl_call_data
175 plperl_proc_desc
*prodesc
;
176 FunctionCallInfo fcinfo
;
177 /* remaining fields are used only in a function returning set: */
178 Tuplestorestate
*tuple_store
;
180 Oid cdomain_oid
; /* 0 unless returning domain-over-composite */
182 MemoryContext tmp_cxt
;
185 /**********************************************************************
186 * The information we cache about prepared and saved plans
187 **********************************************************************/
188 typedef struct plperl_query_desc
191 MemoryContext plan_cxt
; /* context holding this struct */
195 FmgrInfo
*arginfuncs
;
199 /* hash table entry for query desc */
201 typedef struct plperl_query_entry
203 char query_name
[NAMEDATALEN
];
204 plperl_query_desc
*query_data
;
205 } plperl_query_entry
;
207 /**********************************************************************
208 * Information for PostgreSQL - Perl array conversion.
209 **********************************************************************/
210 typedef struct plperl_array_info
213 bool elem_is_rowtype
; /* 't' if element type is a rowtype */
218 FmgrInfo transform_proc
;
221 /**********************************************************************
223 **********************************************************************/
225 static HTAB
*plperl_interp_hash
= NULL
;
226 static HTAB
*plperl_proc_hash
= NULL
;
227 static plperl_interp_desc
*plperl_active_interp
= NULL
;
229 /* If we have an unassigned "held" interpreter, it's stored here */
230 static PerlInterpreter
*plperl_held_interp
= NULL
;
233 static bool plperl_use_strict
= false;
234 static char *plperl_on_init
= NULL
;
235 static char *plperl_on_plperl_init
= NULL
;
236 static char *plperl_on_plperlu_init
= NULL
;
238 static bool plperl_ending
= false;
239 static OP
*(*pp_require_orig
) (pTHX
) = NULL
;
240 static char plperl_opmask
[MAXO
];
242 /* this is saved and restored by plperl_call_handler */
243 static plperl_call_data
*current_call_data
= NULL
;
245 /**********************************************************************
246 * Forward declarations
247 **********************************************************************/
250 static PerlInterpreter
*plperl_init_interp(void);
251 static void plperl_destroy_interp(PerlInterpreter
**);
252 static void plperl_fini(int code
, Datum arg
);
253 static void set_interp_require(bool trusted
);
255 static Datum
plperl_func_handler(PG_FUNCTION_ARGS
);
256 static Datum
plperl_trigger_handler(PG_FUNCTION_ARGS
);
257 static void plperl_event_trigger_handler(PG_FUNCTION_ARGS
);
259 static void free_plperl_function(plperl_proc_desc
*prodesc
);
261 static plperl_proc_desc
*compile_plperl_function(Oid fn_oid
,
263 bool is_event_trigger
);
265 static SV
*plperl_hash_from_tuple(HeapTuple tuple
, TupleDesc tupdesc
, bool include_generated
);
266 static SV
*plperl_hash_from_datum(Datum attr
);
267 static SV
*plperl_ref_from_pg_array(Datum arg
, Oid typid
);
268 static SV
*split_array(plperl_array_info
*info
, int first
, int last
, int nest
);
269 static SV
*make_array_ref(plperl_array_info
*info
, int first
, int last
);
270 static SV
*get_perl_array_ref(SV
*sv
);
271 static Datum
plperl_sv_to_datum(SV
*sv
, Oid typid
, int32 typmod
,
272 FunctionCallInfo fcinfo
,
273 FmgrInfo
*finfo
, Oid typioparam
,
275 static void _sv_to_datum_finfo(Oid typid
, FmgrInfo
*finfo
, Oid
*typioparam
);
276 static Datum
plperl_array_to_datum(SV
*src
, Oid typid
, int32 typmod
);
277 static void array_to_datum_internal(AV
*av
, ArrayBuildState
*astate
,
278 int *ndims
, int *dims
, int cur_depth
,
279 Oid arraytypid
, Oid elemtypid
, int32 typmod
,
280 FmgrInfo
*finfo
, Oid typioparam
);
281 static Datum
plperl_hash_to_datum(SV
*src
, TupleDesc td
);
283 static void plperl_init_shared_libs(pTHX
);
284 static void plperl_trusted_init(void);
285 static void plperl_untrusted_init(void);
286 static HV
*plperl_spi_execute_fetch_result(SPITupleTable
*, uint64
, int);
287 static void plperl_return_next_internal(SV
*sv
);
288 static char *hek2cstr(HE
*he
);
289 static SV
**hv_store_string(HV
*hv
, const char *key
, SV
*val
);
290 static SV
**hv_fetch_string(HV
*hv
, const char *key
);
291 static void plperl_create_sub(plperl_proc_desc
*desc
, const char *s
, Oid fn_oid
);
292 static SV
*plperl_call_perl_func(plperl_proc_desc
*desc
,
293 FunctionCallInfo fcinfo
);
294 static void plperl_compile_callback(void *arg
);
295 static void plperl_exec_callback(void *arg
);
296 static void plperl_inline_callback(void *arg
);
297 static char *strip_trailing_ws(const char *msg
);
298 static OP
*pp_require_safe(pTHX
);
299 static void activate_interpreter(plperl_interp_desc
*interp_desc
);
302 static char *setlocale_perl(int category
, char *locale
);
306 * Decrement the refcount of the given SV within the active Perl interpreter
308 * This is handy because it reloads the active-interpreter pointer, saving
309 * some notation in callers that switch the active interpreter.
312 SvREFCNT_dec_current(SV
*sv
)
320 * convert a HE (hash entry) key to a cstr in the current database encoding
330 * HeSVKEY_force will return a temporary mortal SV*, so we need to make
331 * sure to free it with ENTER/SAVE/FREE/LEAVE
336 /*-------------------------
337 * Unfortunately, while HeUTF8 is true for most things > 256, for values
338 * 128..255 it's not, but perl will treat them as unicode code points if
339 * the utf8 flag is not set ( see The "Unicode Bug" in perldoc perlunicode
342 * So if we did the expected:
345 * else // must be ascii
347 * we won't match columns with codepoints from 128..255
349 * For a more concrete example given a column with the name of the unicode
350 * codepoint U+00ae (registered sign) and a UTF8 database and the perl
351 * return_next { "\N{U+00ae}=>'text } would always fail as heUTF8 returns
352 * 0 and HePV() would give us a char * with 1 byte contains the decimal
355 * Perl has the brains to know when it should utf8 encode 174 properly, so
356 * here we force it into an SV so that perl will figure it out and do the
358 *-------------------------
361 sv
= HeSVKEY_force(he
);
375 * _PG_init() - library load-time initialization
377 * DO NOT make this static nor change its name!
383 * Be sure we do initialization only once.
385 * If initialization fails due to, e.g., plperl_init_interp() throwing an
386 * exception, then we'll return here on the next usage and the user will
387 * get a rather cryptic: ERROR: attempt to redefine parameter
388 * "plperl.use_strict"
390 static bool inited
= false;
397 * Support localized messages.
399 pg_bindtextdomain(TEXTDOMAIN
);
402 * Initialize plperl's GUCs.
404 DefineCustomBoolVariable("plperl.use_strict",
405 gettext_noop("If true, trusted and untrusted Perl code will be compiled in strict mode."),
413 * plperl.on_init is marked PGC_SIGHUP to support the idea that it might
414 * be executed in the postmaster (if plperl is loaded into the postmaster
415 * via shared_preload_libraries). This isn't really right either way,
418 DefineCustomStringVariable("plperl.on_init",
419 gettext_noop("Perl initialization code to execute when a Perl interpreter is initialized."),
427 * plperl.on_plperl_init is marked PGC_SUSET to avoid issues whereby a
428 * user who might not even have USAGE privilege on the plperl language
429 * could nonetheless use SET plperl.on_plperl_init='...' to influence the
430 * behaviour of any existing plperl function that they can execute (which
431 * might be SECURITY DEFINER, leading to a privilege escalation). See
432 * http://archives.postgresql.org/pgsql-hackers/2010-02/msg00281.php and
433 * the overall thread.
435 * Note that because plperl.use_strict is USERSET, a nefarious user could
436 * set it to be applied against other people's functions. This is judged
437 * OK since the worst result would be an error. Your code oughta pass
438 * use_strict anyway ;-)
440 DefineCustomStringVariable("plperl.on_plperl_init",
441 gettext_noop("Perl initialization code to execute once when plperl is first used."),
443 &plperl_on_plperl_init
,
448 DefineCustomStringVariable("plperl.on_plperlu_init",
449 gettext_noop("Perl initialization code to execute once when plperlu is first used."),
451 &plperl_on_plperlu_init
,
456 EmitWarningsOnPlaceholders("plperl");
459 * Create hash tables.
461 hash_ctl
.keysize
= sizeof(Oid
);
462 hash_ctl
.entrysize
= sizeof(plperl_interp_desc
);
463 plperl_interp_hash
= hash_create("PL/Perl interpreters",
466 HASH_ELEM
| HASH_BLOBS
);
468 hash_ctl
.keysize
= sizeof(plperl_proc_key
);
469 hash_ctl
.entrysize
= sizeof(plperl_proc_ptr
);
470 plperl_proc_hash
= hash_create("PL/Perl procedures",
473 HASH_ELEM
| HASH_BLOBS
);
476 * Save the default opmask.
478 PLPERL_SET_OPMASK(plperl_opmask
);
481 * Create the first Perl interpreter, but only partially initialize it.
483 plperl_held_interp
= plperl_init_interp();
490 set_interp_require(bool trusted
)
494 PL_ppaddr
[OP_REQUIRE
] = pp_require_safe
;
495 PL_ppaddr
[OP_DOFILE
] = pp_require_safe
;
499 PL_ppaddr
[OP_REQUIRE
] = pp_require_orig
;
500 PL_ppaddr
[OP_DOFILE
] = pp_require_orig
;
505 * Cleanup perl interpreters, including running END blocks.
506 * Does not fully undo the actions of _PG_init() nor make it callable again.
509 plperl_fini(int code
, Datum arg
)
511 HASH_SEQ_STATUS hash_seq
;
512 plperl_interp_desc
*interp_desc
;
514 elog(DEBUG3
, "plperl_fini");
517 * Indicate that perl is terminating. Disables use of spi_* functions when
518 * running END/DESTROY code. See check_spi_usage_allowed(). Could be
519 * enabled in future, with care, using a transaction
520 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02743.php
522 plperl_ending
= true;
524 /* Only perform perl cleanup if we're exiting cleanly */
527 elog(DEBUG3
, "plperl_fini: skipped");
531 /* Zap the "held" interpreter, if we still have it */
532 plperl_destroy_interp(&plperl_held_interp
);
534 /* Zap any fully-initialized interpreters */
535 hash_seq_init(&hash_seq
, plperl_interp_hash
);
536 while ((interp_desc
= hash_seq_search(&hash_seq
)) != NULL
)
538 if (interp_desc
->interp
)
540 activate_interpreter(interp_desc
);
541 plperl_destroy_interp(&interp_desc
->interp
);
545 elog(DEBUG3
, "plperl_fini: done");
550 * Select and activate an appropriate Perl interpreter.
553 select_perl_context(bool trusted
)
556 plperl_interp_desc
*interp_desc
;
558 PerlInterpreter
*interp
= NULL
;
560 /* Find or create the interpreter hashtable entry for this userid */
562 user_id
= GetUserId();
564 user_id
= InvalidOid
;
566 interp_desc
= hash_search(plperl_interp_hash
, &user_id
,
571 /* Initialize newly-created hashtable entry */
572 interp_desc
->interp
= NULL
;
573 interp_desc
->query_hash
= NULL
;
576 /* Make sure we have a query_hash for this interpreter */
577 if (interp_desc
->query_hash
== NULL
)
581 hash_ctl
.keysize
= NAMEDATALEN
;
582 hash_ctl
.entrysize
= sizeof(plperl_query_entry
);
583 interp_desc
->query_hash
= hash_create("PL/Perl queries",
586 HASH_ELEM
| HASH_STRINGS
);
590 * Quick exit if already have an interpreter
592 if (interp_desc
->interp
)
594 activate_interpreter(interp_desc
);
599 * adopt held interp if free, else create new one if possible
601 if (plperl_held_interp
!= NULL
)
603 /* first actual use of a perl interpreter */
604 interp
= plperl_held_interp
;
607 * Reset the plperl_held_interp pointer first; if we fail during init
608 * we don't want to try again with the partially-initialized interp.
610 plperl_held_interp
= NULL
;
613 plperl_trusted_init();
615 plperl_untrusted_init();
617 /* successfully initialized, so arrange for cleanup */
618 on_proc_exit(plperl_fini
, 0);
625 * plperl_init_interp will change Perl's idea of the active
626 * interpreter. Reset plperl_active_interp temporarily, so that if we
627 * hit an error partway through here, we'll make sure to switch back
628 * to a non-broken interpreter before running any other Perl
631 plperl_active_interp
= NULL
;
633 /* Now build the new interpreter */
634 interp
= plperl_init_interp();
637 plperl_trusted_init();
639 plperl_untrusted_init();
642 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
643 errmsg("cannot allocate multiple Perl interpreters on this platform")));
647 set_interp_require(trusted
);
650 * Since the timing of first use of PL/Perl can't be predicted, any
651 * database interaction during initialization is problematic. Including,
652 * but not limited to, security definer issues. So we only enable access
653 * to the database AFTER on_*_init code has run. See
654 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02669.php
659 newXS("PostgreSQL::InServer::SPI::bootstrap",
660 boot_PostgreSQL__InServer__SPI
, __FILE__
);
662 eval_pv("PostgreSQL::InServer::SPI::bootstrap()", FALSE
);
665 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
666 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
))),
667 errcontext("while executing PostgreSQL::InServer::SPI::bootstrap")));
670 /* Fully initialized, so mark the hashtable entry valid */
671 interp_desc
->interp
= interp
;
673 /* And mark this as the active interpreter */
674 plperl_active_interp
= interp_desc
;
678 * Make the specified interpreter the active one
680 * A call with NULL does nothing. This is so that "restoring" to a previously
681 * null state of plperl_active_interp doesn't result in useless thrashing.
684 activate_interpreter(plperl_interp_desc
*interp_desc
)
686 if (interp_desc
&& plperl_active_interp
!= interp_desc
)
688 Assert(interp_desc
->interp
);
689 PERL_SET_CONTEXT(interp_desc
->interp
);
690 /* trusted iff user_id isn't InvalidOid */
691 set_interp_require(OidIsValid(interp_desc
->user_id
));
692 plperl_active_interp
= interp_desc
;
697 * Create a new Perl interpreter.
699 * We initialize the interpreter as far as we can without knowing whether
700 * it will become a trusted or untrusted interpreter; in particular, the
701 * plperl.on_init code will get executed. Later, either plperl_trusted_init
702 * or plperl_untrusted_init must be called to complete the initialization.
704 static PerlInterpreter
*
705 plperl_init_interp(void)
707 PerlInterpreter
*plperl
;
709 static char *embedding
[3 + 2] = {
710 "", "-e", PLC_PERLBOOT
717 * The perl library on startup does horrible things like call
718 * setlocale(LC_ALL,""). We have protected against that on most platforms
719 * by setting the environment appropriately. However, on Windows,
720 * setlocale() does not consult the environment, so we need to save the
721 * existing locale settings before perl has a chance to mangle them and
722 * restore them after its dirty deeds are done.
725 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_locale.asp
727 * It appears that we only need to do this on interpreter startup, and
728 * subsequent calls to the interpreter don't mess with the locale
731 * We restore them using setlocale_perl(), defined below, so that Perl
732 * doesn't have a different idea of the locale from Postgres.
743 loc
= setlocale(LC_COLLATE
, NULL
);
744 save_collate
= loc
? pstrdup(loc
) : NULL
;
745 loc
= setlocale(LC_CTYPE
, NULL
);
746 save_ctype
= loc
? pstrdup(loc
) : NULL
;
747 loc
= setlocale(LC_MONETARY
, NULL
);
748 save_monetary
= loc
? pstrdup(loc
) : NULL
;
749 loc
= setlocale(LC_NUMERIC
, NULL
);
750 save_numeric
= loc
? pstrdup(loc
) : NULL
;
751 loc
= setlocale(LC_TIME
, NULL
);
752 save_time
= loc
? pstrdup(loc
) : NULL
;
754 #define PLPERL_RESTORE_LOCALE(name, saved) \
756 if (saved != NULL) { setlocale_perl(name, saved); pfree(saved); } \
760 if (plperl_on_init
&& *plperl_on_init
)
762 embedding
[nargs
++] = "-e";
763 embedding
[nargs
++] = plperl_on_init
;
767 * The perl API docs state that PERL_SYS_INIT3 should be called before
768 * allocating interpreters. Unfortunately, on some platforms this fails in
769 * the Perl_do_taint() routine, which is called when the platform is using
770 * the system's malloc() instead of perl's own. Other platforms, notably
771 * Windows, fail if PERL_SYS_INIT3 is not called. So we call it if it's
772 * available, unless perl is using the system malloc(), which is true when
775 #if defined(PERL_SYS_INIT3) && !defined(MYMALLOC)
777 static int perl_sys_init_done
;
779 /* only call this the first time through, as per perlembed man page */
780 if (!perl_sys_init_done
)
782 char *dummy_env
[1] = {NULL
};
784 PERL_SYS_INIT3(&nargs
, (char ***) &embedding
, (char ***) &dummy_env
);
787 * For unclear reasons, PERL_SYS_INIT3 sets the SIGFPE handler to
788 * SIG_IGN. Aside from being extremely unfriendly behavior for a
789 * library, this is dumb on the grounds that the results of a
790 * SIGFPE in this state are undefined according to POSIX, and in
791 * fact you get a forced process kill at least on Linux. Hence,
792 * restore the SIGFPE handler to the backend's standard setting.
793 * (See Perl bug 114574 for more information.)
795 pqsignal(SIGFPE
, FloatExceptionHandler
);
797 perl_sys_init_done
= 1;
798 /* quiet warning if PERL_SYS_INIT3 doesn't use the third argument */
804 plperl
= perl_alloc();
806 elog(ERROR
, "could not allocate Perl interpreter");
808 PERL_SET_CONTEXT(plperl
);
809 perl_construct(plperl
);
812 * Run END blocks in perl_destruct instead of perl_run. Note that dTHX
813 * loads up a pointer to the current interpreter, so we have to postpone
814 * it to here rather than put it at the function head.
819 PL_exit_flags
|= PERL_EXIT_DESTRUCT_END
;
822 * Record the original function for the 'require' and 'dofile'
823 * opcodes. (They share the same implementation.) Ensure it's used
824 * for new interpreters.
826 if (!pp_require_orig
)
827 pp_require_orig
= PL_ppaddr
[OP_REQUIRE
];
830 PL_ppaddr
[OP_REQUIRE
] = pp_require_orig
;
831 PL_ppaddr
[OP_DOFILE
] = pp_require_orig
;
834 #ifdef PLPERL_ENABLE_OPMASK_EARLY
837 * For regression testing to prove that the PLC_PERLBOOT and
838 * PLC_TRUSTED code doesn't even compile any unsafe ops. In future
839 * there may be a valid need for them to do so, in which case this
840 * could be softened (perhaps moved to plperl_trusted_init()) or
843 PL_op_mask
= plperl_opmask
;
846 if (perl_parse(plperl
, plperl_init_shared_libs
,
847 nargs
, embedding
, NULL
) != 0)
849 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
850 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
))),
851 errcontext("while parsing Perl initialization")));
853 if (perl_run(plperl
) != 0)
855 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
856 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
))),
857 errcontext("while running Perl initialization")));
859 #ifdef PLPERL_RESTORE_LOCALE
860 PLPERL_RESTORE_LOCALE(LC_COLLATE
, save_collate
);
861 PLPERL_RESTORE_LOCALE(LC_CTYPE
, save_ctype
);
862 PLPERL_RESTORE_LOCALE(LC_MONETARY
, save_monetary
);
863 PLPERL_RESTORE_LOCALE(LC_NUMERIC
, save_numeric
);
864 PLPERL_RESTORE_LOCALE(LC_TIME
, save_time
);
873 * Our safe implementation of the require opcode.
874 * This is safe because it's completely unable to load any code.
875 * If the requested file/module has already been loaded it'll return true.
877 * So now "use Foo;" will work iff Foo has already been loaded.
880 pp_require_safe(pTHX
)
890 name
= SvPV(sv
, len
);
891 if (!(name
&& len
> 0 && *name
))
894 svp
= hv_fetch(GvHVn(PL_incgv
), name
, len
, 0);
895 if (svp
&& *svp
!= &PL_sv_undef
)
898 DIE(aTHX_
"Unable to load %s into plperl", name
);
901 * In most Perl versions, DIE() expands to a return statement, so the next
902 * line is not necessary. But in versions between but not including
903 * 5.11.1 and 5.13.3 it does not, so the next line is necessary to avoid a
904 * "control reaches end of non-void function" warning from gcc. Other
905 * compilers such as Solaris Studio will, however, issue a "statement not
906 * reached" warning instead.
913 * Destroy one Perl interpreter ... actually we just run END blocks.
915 * Caller must have ensured this interpreter is the active one.
918 plperl_destroy_interp(PerlInterpreter
**interp
)
920 if (interp
&& *interp
)
923 * Only a very minimal destruction is performed: - just call END
926 * We could call perl_destruct() but we'd need to audit its actions
927 * very carefully and work-around any that impact us. (Calling
928 * sv_clean_objs() isn't an option because it's not part of perl's
929 * public API so isn't portably available.) Meanwhile END blocks can
930 * be used to perform manual cleanup.
934 /* Run END blocks - based on perl's perl_destruct() */
935 if (PL_exit_flags
& PERL_EXIT_DESTRUCT_END
)
942 if (PL_endav
&& !PL_minus_c
)
943 call_list(PL_scopestack_ix
, PL_endav
);
954 * Initialize the current Perl interpreter as a trusted interp
957 plperl_trusted_init(void)
965 /* use original require while we set up */
966 PL_ppaddr
[OP_REQUIRE
] = pp_require_orig
;
967 PL_ppaddr
[OP_DOFILE
] = pp_require_orig
;
969 eval_pv(PLC_TRUSTED
, FALSE
);
972 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
973 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
))),
974 errcontext("while executing PLC_TRUSTED")));
977 * Force loading of utf8 module now to prevent errors that can arise from
978 * the regex code later trying to load utf8 modules. See
979 * http://rt.perl.org/rt3/Ticket/Display.html?id=47576
981 eval_pv("my $a=chr(0x100); return $a =~ /\\xa9/i", FALSE
);
984 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
985 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
))),
986 errcontext("while executing utf8fix")));
989 * Lock down the interpreter
992 /* switch to the safe require/dofile opcode for future code */
993 PL_ppaddr
[OP_REQUIRE
] = pp_require_safe
;
994 PL_ppaddr
[OP_DOFILE
] = pp_require_safe
;
997 * prevent (any more) unsafe opcodes being compiled PL_op_mask is per
998 * interpreter, so this only needs to be set once
1000 PL_op_mask
= plperl_opmask
;
1002 /* delete the DynaLoader:: namespace so extensions can't be loaded */
1003 stash
= gv_stashpv("DynaLoader", GV_ADDWARN
);
1005 while ((sv
= hv_iternextsv(stash
, &key
, &klen
)))
1007 if (!isGV_with_GP(sv
) || !GvCV(sv
))
1009 SvREFCNT_dec(GvCV(sv
)); /* free the CV */
1010 GvCV_set(sv
, NULL
); /* prevent call via GV */
1014 /* invalidate assorted caches */
1015 ++PL_sub_generation
;
1016 hv_clear(PL_stashcache
);
1019 * Execute plperl.on_plperl_init in the locked-down interpreter
1021 if (plperl_on_plperl_init
&& *plperl_on_plperl_init
)
1023 eval_pv(plperl_on_plperl_init
, FALSE
);
1024 /* XXX need to find a way to determine a better errcode here */
1027 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
1028 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
))),
1029 errcontext("while executing plperl.on_plperl_init")));
1035 * Initialize the current Perl interpreter as an untrusted interp
1038 plperl_untrusted_init(void)
1043 * Nothing to do except execute plperl.on_plperlu_init
1045 if (plperl_on_plperlu_init
&& *plperl_on_plperlu_init
)
1047 eval_pv(plperl_on_plperlu_init
, FALSE
);
1050 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
1051 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
))),
1052 errcontext("while executing plperl.on_plperlu_init")));
1058 * Perl likes to put a newline after its error messages; clean up such
1061 strip_trailing_ws(const char *msg
)
1063 char *res
= pstrdup(msg
);
1064 int len
= strlen(res
);
1066 while (len
> 0 && isspace((unsigned char) res
[len
- 1]))
1072 /* Build a tuple from a hash. */
1075 plperl_build_tuple_result(HV
*perlhash
, TupleDesc td
)
1083 values
= palloc0(sizeof(Datum
) * td
->natts
);
1084 nulls
= palloc(sizeof(bool) * td
->natts
);
1085 memset(nulls
, true, sizeof(bool) * td
->natts
);
1087 hv_iterinit(perlhash
);
1088 while ((he
= hv_iternext(perlhash
)))
1090 SV
*val
= HeVAL(he
);
1091 char *key
= hek2cstr(he
);
1092 int attn
= SPI_fnumber(td
, key
);
1093 Form_pg_attribute attr
= TupleDescAttr(td
, attn
- 1);
1095 if (attn
== SPI_ERROR_NOATTRIBUTE
)
1097 (errcode(ERRCODE_UNDEFINED_COLUMN
),
1098 errmsg("Perl hash contains nonexistent column \"%s\"",
1102 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1103 errmsg("cannot set system attribute \"%s\"",
1106 values
[attn
- 1] = plperl_sv_to_datum(val
,
1116 hv_iterinit(perlhash
);
1118 tup
= heap_form_tuple(td
, values
, nulls
);
1124 /* convert a hash reference to a datum */
1126 plperl_hash_to_datum(SV
*src
, TupleDesc td
)
1128 HeapTuple tup
= plperl_build_tuple_result((HV
*) SvRV(src
), td
);
1130 return HeapTupleGetDatum(tup
);
1134 * if we are an array ref return the reference. this is special in that if we
1135 * are a PostgreSQL::InServer::ARRAY object we will return the 'magic' array.
1138 get_perl_array_ref(SV
*sv
)
1142 if (SvOK(sv
) && SvROK(sv
))
1144 if (SvTYPE(SvRV(sv
)) == SVt_PVAV
)
1146 else if (sv_isa(sv
, "PostgreSQL::InServer::ARRAY"))
1148 HV
*hv
= (HV
*) SvRV(sv
);
1149 SV
**sav
= hv_fetch_string(hv
, "array");
1151 if (*sav
&& SvOK(*sav
) && SvROK(*sav
) &&
1152 SvTYPE(SvRV(*sav
)) == SVt_PVAV
)
1155 elog(ERROR
, "could not get array reference from PostgreSQL::InServer::ARRAY object");
1162 * helper function for plperl_array_to_datum, recurses for multi-D arrays
1165 array_to_datum_internal(AV
*av
, ArrayBuildState
*astate
,
1166 int *ndims
, int *dims
, int cur_depth
,
1167 Oid arraytypid
, Oid elemtypid
, int32 typmod
,
1168 FmgrInfo
*finfo
, Oid typioparam
)
1172 int len
= av_len(av
) + 1;
1174 for (i
= 0; i
< len
; i
++)
1176 /* fetch the array element */
1177 SV
**svp
= av_fetch(av
, i
, FALSE
);
1179 /* see if this element is an array, if so get that */
1180 SV
*sav
= svp
? get_perl_array_ref(*svp
) : NULL
;
1182 /* multi-dimensional array? */
1185 AV
*nav
= (AV
*) SvRV(sav
);
1187 /* dimensionality checks */
1188 if (cur_depth
+ 1 > MAXDIM
)
1190 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED
),
1191 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
1192 cur_depth
+ 1, MAXDIM
)));
1194 /* set size when at first element in this level, else compare */
1195 if (i
== 0 && *ndims
== cur_depth
)
1197 dims
[*ndims
] = av_len(nav
) + 1;
1200 else if (av_len(nav
) + 1 != dims
[cur_depth
])
1202 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION
),
1203 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1205 /* recurse to fetch elements of this sub-array */
1206 array_to_datum_internal(nav
, astate
,
1207 ndims
, dims
, cur_depth
+ 1,
1208 arraytypid
, elemtypid
, typmod
,
1216 /* scalar after some sub-arrays at same level? */
1217 if (*ndims
!= cur_depth
)
1219 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION
),
1220 errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1222 dat
= plperl_sv_to_datum(svp
? *svp
: NULL
,
1230 (void) accumArrayResult(astate
, dat
, isnull
,
1231 elemtypid
, CurrentMemoryContext
);
1237 * convert perl array ref to a datum
1240 plperl_array_to_datum(SV
*src
, Oid typid
, int32 typmod
)
1243 ArrayBuildState
*astate
;
1252 elemtypid
= get_element_type(typid
);
1255 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1256 errmsg("cannot convert Perl array to non-array type %s",
1257 format_type_be(typid
))));
1259 astate
= initArrayResult(elemtypid
, CurrentMemoryContext
, true);
1261 _sv_to_datum_finfo(elemtypid
, &finfo
, &typioparam
);
1263 memset(dims
, 0, sizeof(dims
));
1264 dims
[0] = av_len((AV
*) SvRV(src
)) + 1;
1266 array_to_datum_internal((AV
*) SvRV(src
), astate
,
1268 typid
, elemtypid
, typmod
,
1269 &finfo
, typioparam
);
1271 /* ensure we get zero-D array for no inputs, as per PG convention */
1275 for (i
= 0; i
< ndims
; i
++)
1278 return makeMdArrayResult(astate
, ndims
, dims
, lbs
,
1279 CurrentMemoryContext
, true);
1282 /* Get the information needed to convert data to the specified PG type */
1284 _sv_to_datum_finfo(Oid typid
, FmgrInfo
*finfo
, Oid
*typioparam
)
1288 /* XXX would be better to cache these lookups */
1289 getTypeInputInfo(typid
,
1290 &typinput
, typioparam
);
1291 fmgr_info(typinput
, finfo
);
1295 * convert Perl SV to PG datum of type typid, typmod typmod
1297 * Pass the PL/Perl function's fcinfo when attempting to convert to the
1298 * function's result type; otherwise pass NULL. This is used when we need to
1299 * resolve the actual result type of a function returning RECORD.
1301 * finfo and typioparam should be the results of _sv_to_datum_finfo for the
1302 * given typid, or NULL/InvalidOid to let this function do the lookups.
1304 * *isnull is an output parameter.
1307 plperl_sv_to_datum(SV
*sv
, Oid typid
, int32 typmod
,
1308 FunctionCallInfo fcinfo
,
1309 FmgrInfo
*finfo
, Oid typioparam
,
1315 /* we might recurse */
1316 check_stack_depth();
1321 * Return NULL if result is undef, or if we're in a function returning
1322 * VOID. In the latter case, we should pay no attention to the last Perl
1323 * statement's result, and this is a convenient means to ensure that.
1325 if (!sv
|| !SvOK(sv
) || typid
== VOIDOID
)
1327 /* look up type info if they did not pass it */
1330 _sv_to_datum_finfo(typid
, &tmp
, &typioparam
);
1334 /* must call typinput in case it wants to reject NULL */
1335 return InputFunctionCall(finfo
, NULL
, typioparam
, typmod
);
1337 else if ((funcid
= get_transform_tosql(typid
, current_call_data
->prodesc
->lang_oid
, current_call_data
->prodesc
->trftypes
)))
1338 return OidFunctionCall1(funcid
, PointerGetDatum(sv
));
1341 /* handle references */
1342 SV
*sav
= get_perl_array_ref(sv
);
1346 /* handle an arrayref */
1347 return plperl_array_to_datum(sav
, typid
, typmod
);
1349 else if (SvTYPE(SvRV(sv
)) == SVt_PVHV
)
1351 /* handle a hashref */
1356 if (!type_is_rowtype(typid
))
1358 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1359 errmsg("cannot convert Perl hash to non-composite type %s",
1360 format_type_be(typid
))));
1362 td
= lookup_rowtype_tupdesc_domain(typid
, typmod
, true);
1365 /* Did we look through a domain? */
1366 isdomain
= (typid
!= td
->tdtypeid
);
1370 /* Must be RECORD, try to resolve based on call info */
1371 TypeFuncClass funcclass
;
1374 funcclass
= get_call_result_type(fcinfo
, &typid
, &td
);
1376 funcclass
= TYPEFUNC_OTHER
;
1377 if (funcclass
!= TYPEFUNC_COMPOSITE
&&
1378 funcclass
!= TYPEFUNC_COMPOSITE_DOMAIN
)
1380 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1381 errmsg("function returning record called in context "
1382 "that cannot accept type record")));
1384 isdomain
= (funcclass
== TYPEFUNC_COMPOSITE_DOMAIN
);
1387 ret
= plperl_hash_to_datum(sv
, td
);
1390 domain_check(ret
, false, typid
, NULL
, NULL
);
1392 /* Release on the result of get_call_result_type is harmless */
1393 ReleaseTupleDesc(td
);
1399 * If it's a reference to something else, such as a scalar, just
1400 * recursively look through the reference.
1402 return plperl_sv_to_datum(SvRV(sv
), typid
, typmod
,
1403 fcinfo
, finfo
, typioparam
,
1408 /* handle a string/number */
1410 char *str
= sv2cstr(sv
);
1412 /* did not pass in any typeinfo? look it up */
1415 _sv_to_datum_finfo(typid
, &tmp
, &typioparam
);
1419 ret
= InputFunctionCall(finfo
, str
, typioparam
, typmod
);
1426 /* Convert the perl SV to a string returned by the type output function */
1428 plperl_sv_to_literal(SV
*sv
, char *fqtypename
)
1430 Datum str
= CStringGetDatum(fqtypename
);
1431 Oid typid
= DirectFunctionCall1(regtypein
, str
);
1437 if (!OidIsValid(typid
))
1439 (errcode(ERRCODE_UNDEFINED_OBJECT
),
1440 errmsg("lookup failed for type %s", fqtypename
)));
1442 datum
= plperl_sv_to_datum(sv
,
1444 NULL
, NULL
, InvalidOid
,
1450 getTypeOutputInfo(typid
,
1451 &typoutput
, &typisvarlena
);
1453 return OidOutputFunctionCall(typoutput
, datum
);
1457 * Convert PostgreSQL array datum to a perl array reference.
1459 * typid is arg's OID, which must be an array type.
1462 plperl_ref_from_pg_array(Datum arg
, Oid typid
)
1465 ArrayType
*ar
= DatumGetArrayTypeP(arg
);
1466 Oid elementtype
= ARR_ELEMTYPE(ar
);
1473 Oid transform_funcid
;
1477 plperl_array_info
*info
;
1482 * Currently we make no effort to cache any of the stuff we look up here,
1485 info
= palloc0(sizeof(plperl_array_info
));
1487 /* get element type information, including output conversion function */
1488 get_type_io_data(elementtype
, IOFunc_output
,
1489 &typlen
, &typbyval
, &typalign
,
1490 &typdelim
, &typioparam
, &typoutputfunc
);
1492 /* Check for a transform function */
1493 transform_funcid
= get_transform_fromsql(elementtype
,
1494 current_call_data
->prodesc
->lang_oid
,
1495 current_call_data
->prodesc
->trftypes
);
1497 /* Look up transform or output function as appropriate */
1498 if (OidIsValid(transform_funcid
))
1499 fmgr_info(transform_funcid
, &info
->transform_proc
);
1501 fmgr_info(typoutputfunc
, &info
->proc
);
1503 info
->elem_is_rowtype
= type_is_rowtype(elementtype
);
1505 /* Get the number and bounds of array dimensions */
1506 info
->ndims
= ARR_NDIM(ar
);
1507 dims
= ARR_DIMS(ar
);
1509 /* No dimensions? Return an empty array */
1510 if (info
->ndims
== 0)
1512 av
= newRV_noinc((SV
*) newAV());
1516 deconstruct_array(ar
, elementtype
, typlen
, typbyval
,
1517 typalign
, &info
->elements
, &info
->nulls
,
1520 /* Get total number of elements in each dimension */
1521 info
->nelems
= palloc(sizeof(int) * info
->ndims
);
1522 info
->nelems
[0] = nitems
;
1523 for (i
= 1; i
< info
->ndims
; i
++)
1524 info
->nelems
[i
] = info
->nelems
[i
- 1] / dims
[i
- 1];
1526 av
= split_array(info
, 0, nitems
, 0);
1530 (void) hv_store(hv
, "array", 5, av
, 0);
1531 (void) hv_store(hv
, "typeoid", 7, newSVuv(typid
), 0);
1533 return sv_bless(newRV_noinc((SV
*) hv
),
1534 gv_stashpv("PostgreSQL::InServer::ARRAY", 0));
1538 * Recursively form array references from splices of the initial array
1541 split_array(plperl_array_info
*info
, int first
, int last
, int nest
)
1547 /* we should only be called when we have something to split */
1548 Assert(info
->ndims
> 0);
1550 /* since this function recurses, it could be driven to stack overflow */
1551 check_stack_depth();
1554 * Base case, return a reference to a single-dimensional array
1556 if (nest
>= info
->ndims
- 1)
1557 return make_array_ref(info
, first
, last
);
1560 for (i
= first
; i
< last
; i
+= info
->nelems
[nest
+ 1])
1562 /* Recursively form references to arrays of lower dimensions */
1563 SV
*ref
= split_array(info
, i
, i
+ info
->nelems
[nest
+ 1], nest
+ 1);
1565 av_push(result
, ref
);
1567 return newRV_noinc((SV
*) result
);
1571 * Create a Perl reference from a one-dimensional C array, converting
1572 * composite type elements to hash references.
1575 make_array_ref(plperl_array_info
*info
, int first
, int last
)
1579 AV
*result
= newAV();
1581 for (i
= first
; i
< last
; i
++)
1586 * We can't use &PL_sv_undef here. See "AVs, HVs and undefined
1587 * values" in perlguts.
1589 av_push(result
, newSV(0));
1593 Datum itemvalue
= info
->elements
[i
];
1595 if (info
->transform_proc
.fn_oid
)
1596 av_push(result
, (SV
*) DatumGetPointer(FunctionCall1(&info
->transform_proc
, itemvalue
)));
1597 else if (info
->elem_is_rowtype
)
1598 /* Handle composite type elements */
1599 av_push(result
, plperl_hash_from_datum(itemvalue
));
1602 char *val
= OutputFunctionCall(&info
->proc
, itemvalue
);
1604 av_push(result
, cstr2sv(val
));
1608 return newRV_noinc((SV
*) result
);
1611 /* Set up the arguments for a trigger call. */
1613 plperl_trigger_build_args(FunctionCallInfo fcinfo
)
1626 hv_ksplit(hv
, 12); /* pre-grow the hash */
1628 tdata
= (TriggerData
*) fcinfo
->context
;
1629 tupdesc
= tdata
->tg_relation
->rd_att
;
1631 relid
= DatumGetCString(DirectFunctionCall1(oidout
,
1632 ObjectIdGetDatum(tdata
->tg_relation
->rd_id
)));
1634 hv_store_string(hv
, "name", cstr2sv(tdata
->tg_trigger
->tgname
));
1635 hv_store_string(hv
, "relid", cstr2sv(relid
));
1638 * Note: In BEFORE trigger, stored generated columns are not computed yet,
1639 * so don't make them accessible in NEW row.
1642 if (TRIGGER_FIRED_BY_INSERT(tdata
->tg_event
))
1645 if (TRIGGER_FIRED_FOR_ROW(tdata
->tg_event
))
1646 hv_store_string(hv
, "new",
1647 plperl_hash_from_tuple(tdata
->tg_trigtuple
,
1649 !TRIGGER_FIRED_BEFORE(tdata
->tg_event
)));
1651 else if (TRIGGER_FIRED_BY_DELETE(tdata
->tg_event
))
1654 if (TRIGGER_FIRED_FOR_ROW(tdata
->tg_event
))
1655 hv_store_string(hv
, "old",
1656 plperl_hash_from_tuple(tdata
->tg_trigtuple
,
1660 else if (TRIGGER_FIRED_BY_UPDATE(tdata
->tg_event
))
1663 if (TRIGGER_FIRED_FOR_ROW(tdata
->tg_event
))
1665 hv_store_string(hv
, "old",
1666 plperl_hash_from_tuple(tdata
->tg_trigtuple
,
1669 hv_store_string(hv
, "new",
1670 plperl_hash_from_tuple(tdata
->tg_newtuple
,
1672 !TRIGGER_FIRED_BEFORE(tdata
->tg_event
)));
1675 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata
->tg_event
))
1680 hv_store_string(hv
, "event", cstr2sv(event
));
1681 hv_store_string(hv
, "argc", newSViv(tdata
->tg_trigger
->tgnargs
));
1683 if (tdata
->tg_trigger
->tgnargs
> 0)
1687 av_extend(av
, tdata
->tg_trigger
->tgnargs
);
1688 for (i
= 0; i
< tdata
->tg_trigger
->tgnargs
; i
++)
1689 av_push(av
, cstr2sv(tdata
->tg_trigger
->tgargs
[i
]));
1690 hv_store_string(hv
, "args", newRV_noinc((SV
*) av
));
1693 hv_store_string(hv
, "relname",
1694 cstr2sv(SPI_getrelname(tdata
->tg_relation
)));
1696 hv_store_string(hv
, "table_name",
1697 cstr2sv(SPI_getrelname(tdata
->tg_relation
)));
1699 hv_store_string(hv
, "table_schema",
1700 cstr2sv(SPI_getnspname(tdata
->tg_relation
)));
1702 if (TRIGGER_FIRED_BEFORE(tdata
->tg_event
))
1704 else if (TRIGGER_FIRED_AFTER(tdata
->tg_event
))
1706 else if (TRIGGER_FIRED_INSTEAD(tdata
->tg_event
))
1707 when
= "INSTEAD OF";
1710 hv_store_string(hv
, "when", cstr2sv(when
));
1712 if (TRIGGER_FIRED_FOR_ROW(tdata
->tg_event
))
1714 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata
->tg_event
))
1715 level
= "STATEMENT";
1718 hv_store_string(hv
, "level", cstr2sv(level
));
1720 return newRV_noinc((SV
*) hv
);
1724 /* Set up the arguments for an event trigger call. */
1726 plperl_event_trigger_build_args(FunctionCallInfo fcinfo
)
1729 EventTriggerData
*tdata
;
1734 tdata
= (EventTriggerData
*) fcinfo
->context
;
1736 hv_store_string(hv
, "event", cstr2sv(tdata
->event
));
1737 hv_store_string(hv
, "tag", cstr2sv(GetCommandTagName(tdata
->tag
)));
1739 return newRV_noinc((SV
*) hv
);
1742 /* Construct the modified new tuple to be returned from a trigger. */
1744 plperl_modify_tuple(HV
*hvTD
, TriggerData
*tdata
, HeapTuple otup
)
1757 svp
= hv_fetch_string(hvTD
, "new");
1760 (errcode(ERRCODE_UNDEFINED_COLUMN
),
1761 errmsg("$_TD->{new} does not exist")));
1762 if (!SvOK(*svp
) || !SvROK(*svp
) || SvTYPE(SvRV(*svp
)) != SVt_PVHV
)
1764 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1765 errmsg("$_TD->{new} is not a hash reference")));
1766 hvNew
= (HV
*) SvRV(*svp
);
1768 tupdesc
= tdata
->tg_relation
->rd_att
;
1769 natts
= tupdesc
->natts
;
1771 modvalues
= (Datum
*) palloc0(natts
* sizeof(Datum
));
1772 modnulls
= (bool *) palloc0(natts
* sizeof(bool));
1773 modrepls
= (bool *) palloc0(natts
* sizeof(bool));
1776 while ((he
= hv_iternext(hvNew
)))
1778 char *key
= hek2cstr(he
);
1779 SV
*val
= HeVAL(he
);
1780 int attn
= SPI_fnumber(tupdesc
, key
);
1781 Form_pg_attribute attr
= TupleDescAttr(tupdesc
, attn
- 1);
1783 if (attn
== SPI_ERROR_NOATTRIBUTE
)
1785 (errcode(ERRCODE_UNDEFINED_COLUMN
),
1786 errmsg("Perl hash contains nonexistent column \"%s\"",
1790 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1791 errmsg("cannot set system attribute \"%s\"",
1793 if (attr
->attgenerated
)
1795 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED
),
1796 errmsg("cannot set generated column \"%s\"",
1799 modvalues
[attn
- 1] = plperl_sv_to_datum(val
,
1805 &modnulls
[attn
- 1]);
1806 modrepls
[attn
- 1] = true;
1812 rtup
= heap_modify_tuple(otup
, tupdesc
, modvalues
, modnulls
, modrepls
);
1823 * There are three externally visible pieces to plperl: plperl_call_handler,
1824 * plperl_inline_handler, and plperl_validator.
1828 * The call handler is called to run normal functions (including trigger
1829 * functions) that are defined in pg_proc.
1831 PG_FUNCTION_INFO_V1(plperl_call_handler
);
1834 plperl_call_handler(PG_FUNCTION_ARGS
)
1836 Datum retval
= (Datum
) 0;
1837 plperl_call_data
*volatile save_call_data
= current_call_data
;
1838 plperl_interp_desc
*volatile oldinterp
= plperl_active_interp
;
1839 plperl_call_data this_call_data
;
1841 /* Initialize current-call status record */
1842 MemSet(&this_call_data
, 0, sizeof(this_call_data
));
1843 this_call_data
.fcinfo
= fcinfo
;
1847 current_call_data
= &this_call_data
;
1848 if (CALLED_AS_TRIGGER(fcinfo
))
1849 retval
= PointerGetDatum(plperl_trigger_handler(fcinfo
));
1850 else if (CALLED_AS_EVENT_TRIGGER(fcinfo
))
1852 plperl_event_trigger_handler(fcinfo
);
1856 retval
= plperl_func_handler(fcinfo
);
1860 current_call_data
= save_call_data
;
1861 activate_interpreter(oldinterp
);
1862 if (this_call_data
.prodesc
)
1863 decrement_prodesc_refcount(this_call_data
.prodesc
);
1871 * The inline handler runs anonymous code blocks (DO blocks).
1873 PG_FUNCTION_INFO_V1(plperl_inline_handler
);
1876 plperl_inline_handler(PG_FUNCTION_ARGS
)
1878 LOCAL_FCINFO(fake_fcinfo
, 0);
1879 InlineCodeBlock
*codeblock
= (InlineCodeBlock
*) PG_GETARG_POINTER(0);
1881 plperl_proc_desc desc
;
1882 plperl_call_data
*volatile save_call_data
= current_call_data
;
1883 plperl_interp_desc
*volatile oldinterp
= plperl_active_interp
;
1884 plperl_call_data this_call_data
;
1885 ErrorContextCallback pl_error_context
;
1887 /* Initialize current-call status record */
1888 MemSet(&this_call_data
, 0, sizeof(this_call_data
));
1890 /* Set up a callback for error reporting */
1891 pl_error_context
.callback
= plperl_inline_callback
;
1892 pl_error_context
.previous
= error_context_stack
;
1893 pl_error_context
.arg
= NULL
;
1894 error_context_stack
= &pl_error_context
;
1897 * Set up a fake fcinfo and descriptor with just enough info to satisfy
1898 * plperl_call_perl_func(). In particular note that this sets things up
1899 * with no arguments passed, and a result type of VOID.
1901 MemSet(fake_fcinfo
, 0, SizeForFunctionCallInfo(0));
1902 MemSet(&flinfo
, 0, sizeof(flinfo
));
1903 MemSet(&desc
, 0, sizeof(desc
));
1904 fake_fcinfo
->flinfo
= &flinfo
;
1905 flinfo
.fn_oid
= InvalidOid
;
1906 flinfo
.fn_mcxt
= CurrentMemoryContext
;
1908 desc
.proname
= "inline_code_block";
1909 desc
.fn_readonly
= false;
1911 desc
.lang_oid
= codeblock
->langOid
;
1912 desc
.trftypes
= NIL
;
1913 desc
.lanpltrusted
= codeblock
->langIsTrusted
;
1915 desc
.fn_retistuple
= false;
1916 desc
.fn_retisset
= false;
1917 desc
.fn_retisarray
= false;
1918 desc
.result_oid
= InvalidOid
;
1920 desc
.reference
= NULL
;
1922 this_call_data
.fcinfo
= fake_fcinfo
;
1923 this_call_data
.prodesc
= &desc
;
1924 /* we do not bother with refcounting the fake prodesc */
1930 current_call_data
= &this_call_data
;
1932 if (SPI_connect_ext(codeblock
->atomic
? 0 : SPI_OPT_NONATOMIC
) != SPI_OK_CONNECT
)
1933 elog(ERROR
, "could not connect to SPI manager");
1935 select_perl_context(desc
.lanpltrusted
);
1937 plperl_create_sub(&desc
, codeblock
->source_text
, 0);
1939 if (!desc
.reference
) /* can this happen? */
1940 elog(ERROR
, "could not create internal procedure for anonymous code block");
1942 perlret
= plperl_call_perl_func(&desc
, fake_fcinfo
);
1944 SvREFCNT_dec_current(perlret
);
1946 if (SPI_finish() != SPI_OK_FINISH
)
1947 elog(ERROR
, "SPI_finish() failed");
1952 SvREFCNT_dec_current(desc
.reference
);
1953 current_call_data
= save_call_data
;
1954 activate_interpreter(oldinterp
);
1958 error_context_stack
= pl_error_context
.previous
;
1964 * The validator is called during CREATE FUNCTION to validate the function
1965 * being created/replaced. The precise behavior of the validator may be
1966 * modified by the check_function_bodies GUC.
1968 PG_FUNCTION_INFO_V1(plperl_validator
);
1971 plperl_validator(PG_FUNCTION_ARGS
)
1973 Oid funcoid
= PG_GETARG_OID(0);
1981 bool is_trigger
= false;
1982 bool is_event_trigger
= false;
1985 if (!CheckFunctionValidatorAccess(fcinfo
->flinfo
->fn_oid
, funcoid
))
1988 /* Get the new function's pg_proc entry */
1989 tuple
= SearchSysCache1(PROCOID
, ObjectIdGetDatum(funcoid
));
1990 if (!HeapTupleIsValid(tuple
))
1991 elog(ERROR
, "cache lookup failed for function %u", funcoid
);
1992 proc
= (Form_pg_proc
) GETSTRUCT(tuple
);
1994 functyptype
= get_typtype(proc
->prorettype
);
1996 /* Disallow pseudotype result */
1997 /* except for TRIGGER, EVTTRIGGER, RECORD, or VOID */
1998 if (functyptype
== TYPTYPE_PSEUDO
)
2000 if (proc
->prorettype
== TRIGGEROID
)
2002 else if (proc
->prorettype
== EVENT_TRIGGEROID
)
2003 is_event_trigger
= true;
2004 else if (proc
->prorettype
!= RECORDOID
&&
2005 proc
->prorettype
!= VOIDOID
)
2007 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2008 errmsg("PL/Perl functions cannot return type %s",
2009 format_type_be(proc
->prorettype
))));
2012 /* Disallow pseudotypes in arguments (either IN or OUT) */
2013 numargs
= get_func_arg_info(tuple
,
2014 &argtypes
, &argnames
, &argmodes
);
2015 for (i
= 0; i
< numargs
; i
++)
2017 if (get_typtype(argtypes
[i
]) == TYPTYPE_PSEUDO
&&
2018 argtypes
[i
] != RECORDOID
)
2020 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2021 errmsg("PL/Perl functions cannot accept type %s",
2022 format_type_be(argtypes
[i
]))));
2025 ReleaseSysCache(tuple
);
2027 /* Postpone body checks if !check_function_bodies */
2028 if (check_function_bodies
)
2030 (void) compile_plperl_function(funcoid
, is_trigger
, is_event_trigger
);
2033 /* the result of a validator is ignored */
2039 * plperlu likewise requires three externally visible functions:
2040 * plperlu_call_handler, plperlu_inline_handler, and plperlu_validator.
2041 * These are currently just aliases that send control to the plperl
2042 * handler functions, and we decide whether a particular function is
2043 * trusted or not by inspecting the actual pg_language tuple.
2046 PG_FUNCTION_INFO_V1(plperlu_call_handler
);
2049 plperlu_call_handler(PG_FUNCTION_ARGS
)
2051 return plperl_call_handler(fcinfo
);
2054 PG_FUNCTION_INFO_V1(plperlu_inline_handler
);
2057 plperlu_inline_handler(PG_FUNCTION_ARGS
)
2059 return plperl_inline_handler(fcinfo
);
2062 PG_FUNCTION_INFO_V1(plperlu_validator
);
2065 plperlu_validator(PG_FUNCTION_ARGS
)
2067 /* call plperl validator with our fcinfo so it gets our oid */
2068 return plperl_validator(fcinfo
);
2073 * Uses mkfunc to create a subroutine whose text is
2074 * supplied in s, and returns a reference to it
2077 plperl_create_sub(plperl_proc_desc
*prodesc
, const char *s
, Oid fn_oid
)
2081 char subname
[NAMEDATALEN
+ 40];
2082 HV
*pragma_hv
= newHV();
2086 sprintf(subname
, "%s__%u", prodesc
->proname
, fn_oid
);
2088 if (plperl_use_strict
)
2089 hv_store_string(pragma_hv
, "strict", (SV
*) newAV());
2095 PUSHs(sv_2mortal(cstr2sv(subname
)));
2096 PUSHs(sv_2mortal(newRV_noinc((SV
*) pragma_hv
)));
2099 * Use 'false' for $prolog in mkfunc, which is kept for compatibility in
2100 * case a module such as PostgreSQL::PLPerl::NYTprof replaces the function
2104 PUSHs(sv_2mortal(cstr2sv(s
)));
2108 * G_KEEPERR seems to be needed here, else we don't recognize compile
2109 * errors properly. Perhaps it's because there's another level of eval
2110 * inside mksafefunc?
2112 count
= perl_call_pv("PostgreSQL::InServer::mkfunc",
2113 G_SCALAR
| G_EVAL
| G_KEEPERR
);
2118 SV
*sub_rv
= (SV
*) POPs
;
2120 if (sub_rv
&& SvROK(sub_rv
) && SvTYPE(SvRV(sub_rv
)) == SVt_PVCV
)
2122 subref
= newRV_inc(SvRV(sub_rv
));
2132 (errcode(ERRCODE_SYNTAX_ERROR
),
2133 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
)))));
2137 (errcode(ERRCODE_SYNTAX_ERROR
),
2138 errmsg("didn't get a CODE reference from compiling function \"%s\"",
2139 prodesc
->proname
)));
2141 prodesc
->reference
= subref
;
2145 /**********************************************************************
2146 * plperl_init_shared_libs() -
2147 **********************************************************************/
2150 plperl_init_shared_libs(pTHX
)
2152 char *file
= __FILE__
;
2154 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader
, file
);
2155 newXS("PostgreSQL::InServer::Util::bootstrap",
2156 boot_PostgreSQL__InServer__Util
, file
);
2157 /* newXS for...::SPI::bootstrap is in select_perl_context() */
2162 plperl_call_perl_func(plperl_proc_desc
*desc
, FunctionCallInfo fcinfo
)
2169 Oid
*argtypes
= NULL
;
2176 EXTEND(sp
, desc
->nargs
);
2178 /* Get signature for true functions; inline blocks have no args. */
2179 if (fcinfo
->flinfo
->fn_oid
)
2180 get_func_signature(fcinfo
->flinfo
->fn_oid
, &argtypes
, &nargs
);
2181 Assert(nargs
== desc
->nargs
);
2183 for (i
= 0; i
< desc
->nargs
; i
++)
2185 if (fcinfo
->args
[i
].isnull
)
2186 PUSHs(&PL_sv_undef
);
2187 else if (desc
->arg_is_rowtype
[i
])
2189 SV
*sv
= plperl_hash_from_datum(fcinfo
->args
[i
].value
);
2191 PUSHs(sv_2mortal(sv
));
2198 if (OidIsValid(desc
->arg_arraytype
[i
]))
2199 sv
= plperl_ref_from_pg_array(fcinfo
->args
[i
].value
, desc
->arg_arraytype
[i
]);
2200 else if ((funcid
= get_transform_fromsql(argtypes
[i
], current_call_data
->prodesc
->lang_oid
, current_call_data
->prodesc
->trftypes
)))
2201 sv
= (SV
*) DatumGetPointer(OidFunctionCall1(funcid
, fcinfo
->args
[i
].value
));
2206 tmp
= OutputFunctionCall(&(desc
->arg_out_func
[i
]),
2207 fcinfo
->args
[i
].value
);
2212 PUSHs(sv_2mortal(sv
));
2217 /* Do NOT use G_KEEPERR here */
2218 count
= perl_call_sv(desc
->reference
, G_SCALAR
| G_EVAL
);
2228 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
2229 errmsg("didn't get a return item from function")));
2238 /* XXX need to find a way to determine a better errcode here */
2240 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
2241 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
)))));
2244 retval
= newSVsv(POPs
);
2255 plperl_call_perl_trigger_func(plperl_proc_desc
*desc
, FunctionCallInfo fcinfo
,
2264 Trigger
*tg_trigger
= ((TriggerData
*) fcinfo
->context
)->tg_trigger
;
2269 TDsv
= get_sv("main::_TD", 0);
2272 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
2273 errmsg("couldn't fetch $_TD")));
2275 save_item(TDsv
); /* local $_TD */
2279 EXTEND(sp
, tg_trigger
->tgnargs
);
2281 for (i
= 0; i
< tg_trigger
->tgnargs
; i
++)
2282 PUSHs(sv_2mortal(cstr2sv(tg_trigger
->tgargs
[i
])));
2285 /* Do NOT use G_KEEPERR here */
2286 count
= perl_call_sv(desc
->reference
, G_SCALAR
| G_EVAL
);
2296 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
2297 errmsg("didn't get a return item from trigger function")));
2306 /* XXX need to find a way to determine a better errcode here */
2308 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
2309 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
)))));
2312 retval
= newSVsv(POPs
);
2323 plperl_call_perl_event_trigger_func(plperl_proc_desc
*desc
,
2324 FunctionCallInfo fcinfo
,
2336 TDsv
= get_sv("main::_TD", 0);
2339 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
2340 errmsg("couldn't fetch $_TD")));
2342 save_item(TDsv
); /* local $_TD */
2348 /* Do NOT use G_KEEPERR here */
2349 count
= perl_call_sv(desc
->reference
, G_SCALAR
| G_EVAL
);
2359 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
2360 errmsg("didn't get a return item from trigger function")));
2369 /* XXX need to find a way to determine a better errcode here */
2371 (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION
),
2372 errmsg("%s", strip_trailing_ws(sv2cstr(ERRSV
)))));
2375 retval
= newSVsv(POPs
);
2376 (void) retval
; /* silence compiler warning */
2384 plperl_func_handler(PG_FUNCTION_ARGS
)
2387 plperl_proc_desc
*prodesc
;
2391 ErrorContextCallback pl_error_context
;
2393 nonatomic
= fcinfo
->context
&&
2394 IsA(fcinfo
->context
, CallContext
) &&
2395 !castNode(CallContext
, fcinfo
->context
)->atomic
;
2397 if (SPI_connect_ext(nonatomic
? SPI_OPT_NONATOMIC
: 0) != SPI_OK_CONNECT
)
2398 elog(ERROR
, "could not connect to SPI manager");
2400 prodesc
= compile_plperl_function(fcinfo
->flinfo
->fn_oid
, false, false);
2401 current_call_data
->prodesc
= prodesc
;
2402 increment_prodesc_refcount(prodesc
);
2404 /* Set a callback for error reporting */
2405 pl_error_context
.callback
= plperl_exec_callback
;
2406 pl_error_context
.previous
= error_context_stack
;
2407 pl_error_context
.arg
= prodesc
->proname
;
2408 error_context_stack
= &pl_error_context
;
2410 rsi
= (ReturnSetInfo
*) fcinfo
->resultinfo
;
2412 if (prodesc
->fn_retisset
)
2414 /* Check context before allowing the call to go through */
2415 if (!rsi
|| !IsA(rsi
, ReturnSetInfo
) ||
2416 (rsi
->allowedModes
& SFRM_Materialize
) == 0)
2418 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2419 errmsg("set-valued function called in context that "
2420 "cannot accept a set")));
2423 activate_interpreter(prodesc
->interp
);
2425 perlret
= plperl_call_perl_func(prodesc
, fcinfo
);
2427 /************************************************************
2428 * Disconnect from SPI manager and then create the return
2429 * values datum (if the input function does a palloc for it
2430 * this must not be allocated in the SPI memory context
2431 * because SPI_finish would free it).
2432 ************************************************************/
2433 if (SPI_finish() != SPI_OK_FINISH
)
2434 elog(ERROR
, "SPI_finish() failed");
2436 if (prodesc
->fn_retisset
)
2441 * If the Perl function returned an arrayref, we pretend that it
2442 * called return_next() for each element of the array, to handle old
2443 * SRFs that didn't know about return_next(). Any other sort of return
2444 * value is an error, except undef which means return an empty set.
2446 sav
= get_perl_array_ref(perlret
);
2452 AV
*rav
= (AV
*) SvRV(sav
);
2454 while ((svp
= av_fetch(rav
, i
, FALSE
)) != NULL
)
2456 plperl_return_next_internal(*svp
);
2460 else if (SvOK(perlret
))
2463 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2464 errmsg("set-returning PL/Perl function must return "
2465 "reference to array or use return_next")));
2468 rsi
->returnMode
= SFRM_Materialize
;
2469 if (current_call_data
->tuple_store
)
2471 rsi
->setResult
= current_call_data
->tuple_store
;
2472 rsi
->setDesc
= current_call_data
->ret_tdesc
;
2476 else if (prodesc
->result_oid
)
2478 retval
= plperl_sv_to_datum(perlret
,
2479 prodesc
->result_oid
,
2482 &prodesc
->result_in_func
,
2483 prodesc
->result_typioparam
,
2486 if (fcinfo
->isnull
&& rsi
&& IsA(rsi
, ReturnSetInfo
))
2487 rsi
->isDone
= ExprEndResult
;
2490 /* Restore the previous error callback */
2491 error_context_stack
= pl_error_context
.previous
;
2493 SvREFCNT_dec_current(perlret
);
2500 plperl_trigger_handler(PG_FUNCTION_ARGS
)
2502 plperl_proc_desc
*prodesc
;
2507 ErrorContextCallback pl_error_context
;
2509 int rc PG_USED_FOR_ASSERTS_ONLY
;
2511 /* Connect to SPI manager */
2512 if (SPI_connect() != SPI_OK_CONNECT
)
2513 elog(ERROR
, "could not connect to SPI manager");
2515 /* Make transition tables visible to this SPI connection */
2516 tdata
= (TriggerData
*) fcinfo
->context
;
2517 rc
= SPI_register_trigger_data(tdata
);
2520 /* Find or compile the function */
2521 prodesc
= compile_plperl_function(fcinfo
->flinfo
->fn_oid
, true, false);
2522 current_call_data
->prodesc
= prodesc
;
2523 increment_prodesc_refcount(prodesc
);
2525 /* Set a callback for error reporting */
2526 pl_error_context
.callback
= plperl_exec_callback
;
2527 pl_error_context
.previous
= error_context_stack
;
2528 pl_error_context
.arg
= prodesc
->proname
;
2529 error_context_stack
= &pl_error_context
;
2531 activate_interpreter(prodesc
->interp
);
2533 svTD
= plperl_trigger_build_args(fcinfo
);
2534 perlret
= plperl_call_perl_trigger_func(prodesc
, fcinfo
, svTD
);
2535 hvTD
= (HV
*) SvRV(svTD
);
2537 /************************************************************
2538 * Disconnect from SPI manager and then create the return
2539 * values datum (if the input function does a palloc for it
2540 * this must not be allocated in the SPI memory context
2541 * because SPI_finish would free it).
2542 ************************************************************/
2543 if (SPI_finish() != SPI_OK_FINISH
)
2544 elog(ERROR
, "SPI_finish() failed");
2546 if (perlret
== NULL
|| !SvOK(perlret
))
2548 /* undef result means go ahead with original tuple */
2549 TriggerData
*trigdata
= ((TriggerData
*) fcinfo
->context
);
2551 if (TRIGGER_FIRED_BY_INSERT(trigdata
->tg_event
))
2552 retval
= (Datum
) trigdata
->tg_trigtuple
;
2553 else if (TRIGGER_FIRED_BY_UPDATE(trigdata
->tg_event
))
2554 retval
= (Datum
) trigdata
->tg_newtuple
;
2555 else if (TRIGGER_FIRED_BY_DELETE(trigdata
->tg_event
))
2556 retval
= (Datum
) trigdata
->tg_trigtuple
;
2557 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata
->tg_event
))
2558 retval
= (Datum
) trigdata
->tg_trigtuple
;
2560 retval
= (Datum
) 0; /* can this happen? */
2567 tmp
= sv2cstr(perlret
);
2569 if (pg_strcasecmp(tmp
, "SKIP") == 0)
2571 else if (pg_strcasecmp(tmp
, "MODIFY") == 0)
2573 TriggerData
*trigdata
= (TriggerData
*) fcinfo
->context
;
2575 if (TRIGGER_FIRED_BY_INSERT(trigdata
->tg_event
))
2576 trv
= plperl_modify_tuple(hvTD
, trigdata
,
2577 trigdata
->tg_trigtuple
);
2578 else if (TRIGGER_FIRED_BY_UPDATE(trigdata
->tg_event
))
2579 trv
= plperl_modify_tuple(hvTD
, trigdata
,
2580 trigdata
->tg_newtuple
);
2584 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED
),
2585 errmsg("ignoring modified row in DELETE trigger")));
2592 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED
),
2593 errmsg("result of PL/Perl trigger function must be undef, "
2594 "\"SKIP\", or \"MODIFY\"")));
2597 retval
= PointerGetDatum(trv
);
2601 /* Restore the previous error callback */
2602 error_context_stack
= pl_error_context
.previous
;
2604 SvREFCNT_dec_current(svTD
);
2606 SvREFCNT_dec_current(perlret
);
2613 plperl_event_trigger_handler(PG_FUNCTION_ARGS
)
2615 plperl_proc_desc
*prodesc
;
2617 ErrorContextCallback pl_error_context
;
2619 /* Connect to SPI manager */
2620 if (SPI_connect() != SPI_OK_CONNECT
)
2621 elog(ERROR
, "could not connect to SPI manager");
2623 /* Find or compile the function */
2624 prodesc
= compile_plperl_function(fcinfo
->flinfo
->fn_oid
, false, true);
2625 current_call_data
->prodesc
= prodesc
;
2626 increment_prodesc_refcount(prodesc
);
2628 /* Set a callback for error reporting */
2629 pl_error_context
.callback
= plperl_exec_callback
;
2630 pl_error_context
.previous
= error_context_stack
;
2631 pl_error_context
.arg
= prodesc
->proname
;
2632 error_context_stack
= &pl_error_context
;
2634 activate_interpreter(prodesc
->interp
);
2636 svTD
= plperl_event_trigger_build_args(fcinfo
);
2637 plperl_call_perl_event_trigger_func(prodesc
, fcinfo
, svTD
);
2639 if (SPI_finish() != SPI_OK_FINISH
)
2640 elog(ERROR
, "SPI_finish() failed");
2642 /* Restore the previous error callback */
2643 error_context_stack
= pl_error_context
.previous
;
2645 SvREFCNT_dec_current(svTD
);
2650 validate_plperl_function(plperl_proc_ptr
*proc_ptr
, HeapTuple procTup
)
2652 if (proc_ptr
&& proc_ptr
->proc_ptr
)
2654 plperl_proc_desc
*prodesc
= proc_ptr
->proc_ptr
;
2657 /************************************************************
2658 * If it's present, must check whether it's still up to date.
2659 * This is needed because CREATE OR REPLACE FUNCTION can modify the
2660 * function's pg_proc entry without changing its OID.
2661 ************************************************************/
2662 uptodate
= (prodesc
->fn_xmin
== HeapTupleHeaderGetRawXmin(procTup
->t_data
) &&
2663 ItemPointerEquals(&prodesc
->fn_tid
, &procTup
->t_self
));
2668 /* Otherwise, unlink the obsoleted entry from the hashtable ... */
2669 proc_ptr
->proc_ptr
= NULL
;
2670 /* ... and release the corresponding refcount, probably deleting it */
2671 decrement_prodesc_refcount(prodesc
);
2679 free_plperl_function(plperl_proc_desc
*prodesc
)
2681 Assert(prodesc
->fn_refcount
== 0);
2682 /* Release CODE reference, if we have one, from the appropriate interp */
2683 if (prodesc
->reference
)
2685 plperl_interp_desc
*oldinterp
= plperl_active_interp
;
2687 activate_interpreter(prodesc
->interp
);
2688 SvREFCNT_dec_current(prodesc
->reference
);
2689 activate_interpreter(oldinterp
);
2691 /* Release all PG-owned data for this proc */
2692 MemoryContextDelete(prodesc
->fn_cxt
);
2696 static plperl_proc_desc
*
2697 compile_plperl_function(Oid fn_oid
, bool is_trigger
, bool is_event_trigger
)
2700 Form_pg_proc procStruct
;
2701 plperl_proc_key proc_key
;
2702 plperl_proc_ptr
*proc_ptr
;
2703 plperl_proc_desc
*volatile prodesc
= NULL
;
2704 volatile MemoryContext proc_cxt
= NULL
;
2705 plperl_interp_desc
*oldinterp
= plperl_active_interp
;
2706 ErrorContextCallback plperl_error_context
;
2708 /* We'll need the pg_proc tuple in any case... */
2709 procTup
= SearchSysCache1(PROCOID
, ObjectIdGetDatum(fn_oid
));
2710 if (!HeapTupleIsValid(procTup
))
2711 elog(ERROR
, "cache lookup failed for function %u", fn_oid
);
2712 procStruct
= (Form_pg_proc
) GETSTRUCT(procTup
);
2715 * Try to find function in plperl_proc_hash. The reason for this
2716 * overcomplicated-seeming lookup procedure is that we don't know whether
2717 * it's plperl or plperlu, and don't want to spend a lookup in pg_language
2720 proc_key
.proc_id
= fn_oid
;
2721 proc_key
.is_trigger
= is_trigger
;
2722 proc_key
.user_id
= GetUserId();
2723 proc_ptr
= hash_search(plperl_proc_hash
, &proc_key
,
2725 if (validate_plperl_function(proc_ptr
, procTup
))
2727 /* Found valid plperl entry */
2728 ReleaseSysCache(procTup
);
2729 return proc_ptr
->proc_ptr
;
2732 /* If not found or obsolete, maybe it's plperlu */
2733 proc_key
.user_id
= InvalidOid
;
2734 proc_ptr
= hash_search(plperl_proc_hash
, &proc_key
,
2736 if (validate_plperl_function(proc_ptr
, procTup
))
2738 /* Found valid plperlu entry */
2739 ReleaseSysCache(procTup
);
2740 return proc_ptr
->proc_ptr
;
2743 /************************************************************
2744 * If we haven't found it in the hashtable, we analyze
2745 * the function's arguments and return type and store
2746 * the in-/out-functions in the prodesc block,
2747 * then we load the procedure into the Perl interpreter,
2748 * and last we create a new hashtable entry for it.
2749 ************************************************************/
2751 /* Set a callback for reporting compilation errors */
2752 plperl_error_context
.callback
= plperl_compile_callback
;
2753 plperl_error_context
.previous
= error_context_stack
;
2754 plperl_error_context
.arg
= NameStr(procStruct
->proname
);
2755 error_context_stack
= &plperl_error_context
;
2761 Form_pg_language langStruct
;
2762 Form_pg_type typeStruct
;
2763 Datum protrftypes_datum
;
2767 MemoryContext oldcontext
;
2769 /************************************************************
2770 * Allocate a context that will hold all PG data for the procedure.
2771 ************************************************************/
2772 proc_cxt
= AllocSetContextCreate(TopMemoryContext
,
2774 ALLOCSET_SMALL_SIZES
);
2776 /************************************************************
2777 * Allocate and fill a new procedure description block.
2778 * struct prodesc and subsidiary data must all live in proc_cxt.
2779 ************************************************************/
2780 oldcontext
= MemoryContextSwitchTo(proc_cxt
);
2781 prodesc
= (plperl_proc_desc
*) palloc0(sizeof(plperl_proc_desc
));
2782 prodesc
->proname
= pstrdup(NameStr(procStruct
->proname
));
2783 MemoryContextSetIdentifier(proc_cxt
, prodesc
->proname
);
2784 prodesc
->fn_cxt
= proc_cxt
;
2785 prodesc
->fn_refcount
= 0;
2786 prodesc
->fn_xmin
= HeapTupleHeaderGetRawXmin(procTup
->t_data
);
2787 prodesc
->fn_tid
= procTup
->t_self
;
2788 prodesc
->nargs
= procStruct
->pronargs
;
2789 prodesc
->arg_out_func
= (FmgrInfo
*) palloc0(prodesc
->nargs
* sizeof(FmgrInfo
));
2790 prodesc
->arg_is_rowtype
= (bool *) palloc0(prodesc
->nargs
* sizeof(bool));
2791 prodesc
->arg_arraytype
= (Oid
*) palloc0(prodesc
->nargs
* sizeof(Oid
));
2792 MemoryContextSwitchTo(oldcontext
);
2794 /* Remember if function is STABLE/IMMUTABLE */
2795 prodesc
->fn_readonly
=
2796 (procStruct
->provolatile
!= PROVOLATILE_VOLATILE
);
2798 /* Fetch protrftypes */
2799 protrftypes_datum
= SysCacheGetAttr(PROCOID
, procTup
,
2800 Anum_pg_proc_protrftypes
, &isnull
);
2801 MemoryContextSwitchTo(proc_cxt
);
2802 prodesc
->trftypes
= isnull
? NIL
: oid_array_to_list(protrftypes_datum
);
2803 MemoryContextSwitchTo(oldcontext
);
2805 /************************************************************
2806 * Lookup the pg_language tuple by Oid
2807 ************************************************************/
2808 langTup
= SearchSysCache1(LANGOID
,
2809 ObjectIdGetDatum(procStruct
->prolang
));
2810 if (!HeapTupleIsValid(langTup
))
2811 elog(ERROR
, "cache lookup failed for language %u",
2812 procStruct
->prolang
);
2813 langStruct
= (Form_pg_language
) GETSTRUCT(langTup
);
2814 prodesc
->lang_oid
= langStruct
->oid
;
2815 prodesc
->lanpltrusted
= langStruct
->lanpltrusted
;
2816 ReleaseSysCache(langTup
);
2818 /************************************************************
2819 * Get the required information for input conversion of the
2821 ************************************************************/
2822 if (!is_trigger
&& !is_event_trigger
)
2824 Oid rettype
= procStruct
->prorettype
;
2826 typeTup
= SearchSysCache1(TYPEOID
, ObjectIdGetDatum(rettype
));
2827 if (!HeapTupleIsValid(typeTup
))
2828 elog(ERROR
, "cache lookup failed for type %u", rettype
);
2829 typeStruct
= (Form_pg_type
) GETSTRUCT(typeTup
);
2831 /* Disallow pseudotype result, except VOID or RECORD */
2832 if (typeStruct
->typtype
== TYPTYPE_PSEUDO
)
2834 if (rettype
== VOIDOID
||
2835 rettype
== RECORDOID
)
2837 else if (rettype
== TRIGGEROID
||
2838 rettype
== EVENT_TRIGGEROID
)
2840 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2841 errmsg("trigger functions can only be called "
2845 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2846 errmsg("PL/Perl functions cannot return type %s",
2847 format_type_be(rettype
))));
2850 prodesc
->result_oid
= rettype
;
2851 prodesc
->fn_retisset
= procStruct
->proretset
;
2852 prodesc
->fn_retistuple
= type_is_rowtype(rettype
);
2853 prodesc
->fn_retisarray
= IsTrueArrayType(typeStruct
);
2855 fmgr_info_cxt(typeStruct
->typinput
,
2856 &(prodesc
->result_in_func
),
2858 prodesc
->result_typioparam
= getTypeIOParam(typeTup
);
2860 ReleaseSysCache(typeTup
);
2863 /************************************************************
2864 * Get the required information for output conversion
2865 * of all procedure arguments
2866 ************************************************************/
2867 if (!is_trigger
&& !is_event_trigger
)
2871 for (i
= 0; i
< prodesc
->nargs
; i
++)
2873 Oid argtype
= procStruct
->proargtypes
.values
[i
];
2875 typeTup
= SearchSysCache1(TYPEOID
, ObjectIdGetDatum(argtype
));
2876 if (!HeapTupleIsValid(typeTup
))
2877 elog(ERROR
, "cache lookup failed for type %u", argtype
);
2878 typeStruct
= (Form_pg_type
) GETSTRUCT(typeTup
);
2880 /* Disallow pseudotype argument, except RECORD */
2881 if (typeStruct
->typtype
== TYPTYPE_PSEUDO
&&
2882 argtype
!= RECORDOID
)
2884 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2885 errmsg("PL/Perl functions cannot accept type %s",
2886 format_type_be(argtype
))));
2888 if (type_is_rowtype(argtype
))
2889 prodesc
->arg_is_rowtype
[i
] = true;
2892 prodesc
->arg_is_rowtype
[i
] = false;
2893 fmgr_info_cxt(typeStruct
->typoutput
,
2894 &(prodesc
->arg_out_func
[i
]),
2898 /* Identify array-type arguments */
2899 if (IsTrueArrayType(typeStruct
))
2900 prodesc
->arg_arraytype
[i
] = argtype
;
2902 prodesc
->arg_arraytype
[i
] = InvalidOid
;
2904 ReleaseSysCache(typeTup
);
2908 /************************************************************
2909 * create the text of the anonymous subroutine.
2910 * we do not use a named subroutine so that we can call directly
2911 * through the reference.
2912 ************************************************************/
2913 prosrcdatum
= SysCacheGetAttr(PROCOID
, procTup
,
2914 Anum_pg_proc_prosrc
, &isnull
);
2916 elog(ERROR
, "null prosrc");
2917 proc_source
= TextDatumGetCString(prosrcdatum
);
2919 /************************************************************
2920 * Create the procedure in the appropriate interpreter
2921 ************************************************************/
2923 select_perl_context(prodesc
->lanpltrusted
);
2925 prodesc
->interp
= plperl_active_interp
;
2927 plperl_create_sub(prodesc
, proc_source
, fn_oid
);
2929 activate_interpreter(oldinterp
);
2933 if (!prodesc
->reference
) /* can this happen? */
2934 elog(ERROR
, "could not create PL/Perl internal procedure");
2936 /************************************************************
2937 * OK, link the procedure into the correct hashtable entry.
2938 * Note we assume that the hashtable entry either doesn't exist yet,
2939 * or we already cleared its proc_ptr during the validation attempts
2940 * above. So no need to decrement an old refcount here.
2941 ************************************************************/
2942 proc_key
.user_id
= prodesc
->lanpltrusted
? GetUserId() : InvalidOid
;
2944 proc_ptr
= hash_search(plperl_proc_hash
, &proc_key
,
2946 /* We assume these two steps can't throw an error: */
2947 proc_ptr
->proc_ptr
= prodesc
;
2948 increment_prodesc_refcount(prodesc
);
2953 * If we got as far as creating a reference, we should be able to use
2954 * free_plperl_function() to clean up. If not, then at most we have
2955 * some PG memory resources in proc_cxt, which we can just delete.
2957 if (prodesc
&& prodesc
->reference
)
2958 free_plperl_function(prodesc
);
2960 MemoryContextDelete(proc_cxt
);
2962 /* Be sure to restore the previous interpreter, too, for luck */
2963 activate_interpreter(oldinterp
);
2969 /* restore previous error callback */
2970 error_context_stack
= plperl_error_context
.previous
;
2972 ReleaseSysCache(procTup
);
2977 /* Build a hash from a given composite/row datum */
2979 plperl_hash_from_datum(Datum attr
)
2985 HeapTupleData tmptup
;
2988 td
= DatumGetHeapTupleHeader(attr
);
2990 /* Extract rowtype info and find a tupdesc */
2991 tupType
= HeapTupleHeaderGetTypeId(td
);
2992 tupTypmod
= HeapTupleHeaderGetTypMod(td
);
2993 tupdesc
= lookup_rowtype_tupdesc(tupType
, tupTypmod
);
2995 /* Build a temporary HeapTuple control structure */
2996 tmptup
.t_len
= HeapTupleHeaderGetDatumLength(td
);
2999 sv
= plperl_hash_from_tuple(&tmptup
, tupdesc
, true);
3000 ReleaseTupleDesc(tupdesc
);
3005 /* Build a hash from all attributes of a given tuple. */
3007 plperl_hash_from_tuple(HeapTuple tuple
, TupleDesc tupdesc
, bool include_generated
)
3013 /* since this function recurses, it could be driven to stack overflow */
3014 check_stack_depth();
3017 hv_ksplit(hv
, tupdesc
->natts
); /* pre-grow the hash */
3019 for (i
= 0; i
< tupdesc
->natts
; i
++)
3026 Form_pg_attribute att
= TupleDescAttr(tupdesc
, i
);
3028 if (att
->attisdropped
)
3031 if (att
->attgenerated
)
3033 /* don't include unless requested */
3034 if (!include_generated
)
3038 attname
= NameStr(att
->attname
);
3039 attr
= heap_getattr(tuple
, i
+ 1, tupdesc
, &isnull
);
3044 * Store (attname => undef) and move on. Note we can't use
3045 * &PL_sv_undef here; see "AVs, HVs and undefined values" in
3046 * perlguts for an explanation.
3048 hv_store_string(hv
, attname
, newSV(0));
3052 if (type_is_rowtype(att
->atttypid
))
3054 SV
*sv
= plperl_hash_from_datum(attr
);
3056 hv_store_string(hv
, attname
, sv
);
3063 if (OidIsValid(get_base_element_type(att
->atttypid
)))
3064 sv
= plperl_ref_from_pg_array(attr
, att
->atttypid
);
3065 else if ((funcid
= get_transform_fromsql(att
->atttypid
, current_call_data
->prodesc
->lang_oid
, current_call_data
->prodesc
->trftypes
)))
3066 sv
= (SV
*) DatumGetPointer(OidFunctionCall1(funcid
, attr
));
3071 /* XXX should have a way to cache these lookups */
3072 getTypeOutputInfo(att
->atttypid
, &typoutput
, &typisvarlena
);
3074 outputstr
= OidOutputFunctionCall(typoutput
, attr
);
3075 sv
= cstr2sv(outputstr
);
3079 hv_store_string(hv
, attname
, sv
);
3082 return newRV_noinc((SV
*) hv
);
3087 check_spi_usage_allowed(void)
3089 /* see comment in plperl_fini() */
3092 /* simple croak as we don't want to involve PostgreSQL code */
3093 croak("SPI functions can not be used in END blocks");
3099 plperl_spi_exec(char *query
, int limit
)
3104 * Execute the query inside a sub-transaction, so we can cope with errors
3107 MemoryContext oldcontext
= CurrentMemoryContext
;
3108 ResourceOwner oldowner
= CurrentResourceOwner
;
3110 check_spi_usage_allowed();
3112 BeginInternalSubTransaction(NULL
);
3113 /* Want to run inside function's memory context */
3114 MemoryContextSwitchTo(oldcontext
);
3120 pg_verifymbstr(query
, strlen(query
), false);
3122 spi_rv
= SPI_execute(query
, current_call_data
->prodesc
->fn_readonly
,
3124 ret_hv
= plperl_spi_execute_fetch_result(SPI_tuptable
, SPI_processed
,
3127 /* Commit the inner transaction, return to outer xact context */
3128 ReleaseCurrentSubTransaction();
3129 MemoryContextSwitchTo(oldcontext
);
3130 CurrentResourceOwner
= oldowner
;
3136 /* Save error info */
3137 MemoryContextSwitchTo(oldcontext
);
3138 edata
= CopyErrorData();
3141 /* Abort the inner transaction */
3142 RollbackAndReleaseCurrentSubTransaction();
3143 MemoryContextSwitchTo(oldcontext
);
3144 CurrentResourceOwner
= oldowner
;
3146 /* Punt the error to Perl */
3147 croak_cstr(edata
->message
);
3149 /* Can't get here, but keep compiler quiet */
3159 plperl_spi_execute_fetch_result(SPITupleTable
*tuptable
, uint64 processed
,
3165 check_spi_usage_allowed();
3169 hv_store_string(result
, "status",
3170 cstr2sv(SPI_result_code_string(status
)));
3171 hv_store_string(result
, "processed",
3172 (processed
> (uint64
) UV_MAX
) ?
3173 newSVnv((NV
) processed
) :
3174 newSVuv((UV
) processed
));
3176 if (status
> 0 && tuptable
)
3182 /* Prevent overflow in call to av_extend() */
3183 if (processed
> (uint64
) AV_SIZE_MAX
)
3185 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED
),
3186 errmsg("query result has too many rows to fit in a Perl array")));
3189 av_extend(rows
, processed
);
3190 for (i
= 0; i
< processed
; i
++)
3192 row
= plperl_hash_from_tuple(tuptable
->vals
[i
], tuptable
->tupdesc
, true);
3195 hv_store_string(result
, "rows",
3196 newRV_noinc((SV
*) rows
));
3199 SPI_freetuptable(tuptable
);
3206 * plperl_return_next catches any error and converts it to a Perl error.
3207 * We assume (perhaps without adequate justification) that we need not abort
3208 * the current transaction if the Perl code traps the error.
3211 plperl_return_next(SV
*sv
)
3213 MemoryContext oldcontext
= CurrentMemoryContext
;
3217 plperl_return_next_internal(sv
);
3223 /* Must reset elog.c's state */
3224 MemoryContextSwitchTo(oldcontext
);
3225 edata
= CopyErrorData();
3228 /* Punt the error to Perl */
3229 croak_cstr(edata
->message
);
3235 * plperl_return_next_internal reports any errors in Postgres fashion
3239 plperl_return_next_internal(SV
*sv
)
3241 plperl_proc_desc
*prodesc
;
3242 FunctionCallInfo fcinfo
;
3244 MemoryContext old_cxt
;
3249 prodesc
= current_call_data
->prodesc
;
3250 fcinfo
= current_call_data
->fcinfo
;
3251 rsi
= (ReturnSetInfo
*) fcinfo
->resultinfo
;
3253 if (!prodesc
->fn_retisset
)
3255 (errcode(ERRCODE_SYNTAX_ERROR
),
3256 errmsg("cannot use return_next in a non-SETOF function")));
3258 if (!current_call_data
->ret_tdesc
)
3262 Assert(!current_call_data
->tuple_store
);
3265 * This is the first call to return_next in the current PL/Perl
3266 * function call, so identify the output tuple type and create a
3267 * tuplestore to hold the result rows.
3269 if (prodesc
->fn_retistuple
)
3271 TypeFuncClass funcclass
;
3274 funcclass
= get_call_result_type(fcinfo
, &typid
, &tupdesc
);
3275 if (funcclass
!= TYPEFUNC_COMPOSITE
&&
3276 funcclass
!= TYPEFUNC_COMPOSITE_DOMAIN
)
3278 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3279 errmsg("function returning record called in context "
3280 "that cannot accept type record")));
3281 /* if domain-over-composite, remember the domain's type OID */
3282 if (funcclass
== TYPEFUNC_COMPOSITE_DOMAIN
)
3283 current_call_data
->cdomain_oid
= typid
;
3287 tupdesc
= rsi
->expectedDesc
;
3288 /* Protect assumption below that we return exactly one column */
3289 if (tupdesc
== NULL
|| tupdesc
->natts
!= 1)
3290 elog(ERROR
, "expected single-column result descriptor for non-composite SETOF result");
3294 * Make sure the tuple_store and ret_tdesc are sufficiently
3297 old_cxt
= MemoryContextSwitchTo(rsi
->econtext
->ecxt_per_query_memory
);
3299 current_call_data
->ret_tdesc
= CreateTupleDescCopy(tupdesc
);
3300 current_call_data
->tuple_store
=
3301 tuplestore_begin_heap(rsi
->allowedModes
& SFRM_Materialize_Random
,
3304 MemoryContextSwitchTo(old_cxt
);
3308 * Producing the tuple we want to return requires making plenty of
3309 * palloc() allocations that are not cleaned up. Since this function can
3310 * be called many times before the current memory context is reset, we
3311 * need to do those allocations in a temporary context.
3313 if (!current_call_data
->tmp_cxt
)
3315 current_call_data
->tmp_cxt
=
3316 AllocSetContextCreate(CurrentMemoryContext
,
3317 "PL/Perl return_next temporary cxt",
3318 ALLOCSET_DEFAULT_SIZES
);
3321 old_cxt
= MemoryContextSwitchTo(current_call_data
->tmp_cxt
);
3323 if (prodesc
->fn_retistuple
)
3327 if (!(SvOK(sv
) && SvROK(sv
) && SvTYPE(SvRV(sv
)) == SVt_PVHV
))
3329 (errcode(ERRCODE_DATATYPE_MISMATCH
),
3330 errmsg("SETOF-composite-returning PL/Perl function "
3331 "must call return_next with reference to hash")));
3333 tuple
= plperl_build_tuple_result((HV
*) SvRV(sv
),
3334 current_call_data
->ret_tdesc
);
3336 if (OidIsValid(current_call_data
->cdomain_oid
))
3337 domain_check(HeapTupleGetDatum(tuple
), false,
3338 current_call_data
->cdomain_oid
,
3339 ¤t_call_data
->cdomain_info
,
3340 rsi
->econtext
->ecxt_per_query_memory
);
3342 tuplestore_puttuple(current_call_data
->tuple_store
, tuple
);
3344 else if (prodesc
->result_oid
)
3349 ret
[0] = plperl_sv_to_datum(sv
,
3350 prodesc
->result_oid
,
3353 &prodesc
->result_in_func
,
3354 prodesc
->result_typioparam
,
3357 tuplestore_putvalues(current_call_data
->tuple_store
,
3358 current_call_data
->ret_tdesc
,
3362 MemoryContextSwitchTo(old_cxt
);
3363 MemoryContextReset(current_call_data
->tmp_cxt
);
3368 plperl_spi_query(char *query
)
3373 * Execute the query inside a sub-transaction, so we can cope with errors
3376 MemoryContext oldcontext
= CurrentMemoryContext
;
3377 ResourceOwner oldowner
= CurrentResourceOwner
;
3379 check_spi_usage_allowed();
3381 BeginInternalSubTransaction(NULL
);
3382 /* Want to run inside function's memory context */
3383 MemoryContextSwitchTo(oldcontext
);
3390 /* Make sure the query is validly encoded */
3391 pg_verifymbstr(query
, strlen(query
), false);
3393 /* Create a cursor for the query */
3394 plan
= SPI_prepare(query
, 0, NULL
);
3396 elog(ERROR
, "SPI_prepare() failed:%s",
3397 SPI_result_code_string(SPI_result
));
3399 portal
= SPI_cursor_open(NULL
, plan
, NULL
, NULL
, false);
3402 elog(ERROR
, "SPI_cursor_open() failed:%s",
3403 SPI_result_code_string(SPI_result
));
3404 cursor
= cstr2sv(portal
->name
);
3408 /* Commit the inner transaction, return to outer xact context */
3409 ReleaseCurrentSubTransaction();
3410 MemoryContextSwitchTo(oldcontext
);
3411 CurrentResourceOwner
= oldowner
;
3417 /* Save error info */
3418 MemoryContextSwitchTo(oldcontext
);
3419 edata
= CopyErrorData();
3422 /* Abort the inner transaction */
3423 RollbackAndReleaseCurrentSubTransaction();
3424 MemoryContextSwitchTo(oldcontext
);
3425 CurrentResourceOwner
= oldowner
;
3427 /* Punt the error to Perl */
3428 croak_cstr(edata
->message
);
3430 /* Can't get here, but keep compiler quiet */
3440 plperl_spi_fetchrow(char *cursor
)
3445 * Execute the FETCH inside a sub-transaction, so we can cope with errors
3448 MemoryContext oldcontext
= CurrentMemoryContext
;
3449 ResourceOwner oldowner
= CurrentResourceOwner
;
3451 check_spi_usage_allowed();
3453 BeginInternalSubTransaction(NULL
);
3454 /* Want to run inside function's memory context */
3455 MemoryContextSwitchTo(oldcontext
);
3460 Portal p
= SPI_cursor_find(cursor
);
3468 SPI_cursor_fetch(p
, true, 1);
3469 if (SPI_processed
== 0)
3472 SPI_cursor_close(p
);
3477 row
= plperl_hash_from_tuple(SPI_tuptable
->vals
[0],
3478 SPI_tuptable
->tupdesc
,
3481 SPI_freetuptable(SPI_tuptable
);
3484 /* Commit the inner transaction, return to outer xact context */
3485 ReleaseCurrentSubTransaction();
3486 MemoryContextSwitchTo(oldcontext
);
3487 CurrentResourceOwner
= oldowner
;
3493 /* Save error info */
3494 MemoryContextSwitchTo(oldcontext
);
3495 edata
= CopyErrorData();
3498 /* Abort the inner transaction */
3499 RollbackAndReleaseCurrentSubTransaction();
3500 MemoryContextSwitchTo(oldcontext
);
3501 CurrentResourceOwner
= oldowner
;
3503 /* Punt the error to Perl */
3504 croak_cstr(edata
->message
);
3506 /* Can't get here, but keep compiler quiet */
3515 plperl_spi_cursor_close(char *cursor
)
3519 check_spi_usage_allowed();
3521 p
= SPI_cursor_find(cursor
);
3526 SPI_cursor_close(p
);
3531 plperl_spi_prepare(char *query
, int argc
, SV
**argv
)
3533 volatile SPIPlanPtr plan
= NULL
;
3534 volatile MemoryContext plan_cxt
= NULL
;
3535 plperl_query_desc
*volatile qdesc
= NULL
;
3536 plperl_query_entry
*volatile hash_entry
= NULL
;
3537 MemoryContext oldcontext
= CurrentMemoryContext
;
3538 ResourceOwner oldowner
= CurrentResourceOwner
;
3539 MemoryContext work_cxt
;
3543 check_spi_usage_allowed();
3545 BeginInternalSubTransaction(NULL
);
3546 MemoryContextSwitchTo(oldcontext
);
3550 CHECK_FOR_INTERRUPTS();
3552 /************************************************************
3553 * Allocate the new querydesc structure
3555 * The qdesc struct, as well as all its subsidiary data, lives in its
3556 * plan_cxt. But note that the SPIPlan does not.
3557 ************************************************************/
3558 plan_cxt
= AllocSetContextCreate(TopMemoryContext
,
3559 "PL/Perl spi_prepare query",
3560 ALLOCSET_SMALL_SIZES
);
3561 MemoryContextSwitchTo(plan_cxt
);
3562 qdesc
= (plperl_query_desc
*) palloc0(sizeof(plperl_query_desc
));
3563 snprintf(qdesc
->qname
, sizeof(qdesc
->qname
), "%p", qdesc
);
3564 qdesc
->plan_cxt
= plan_cxt
;
3565 qdesc
->nargs
= argc
;
3566 qdesc
->argtypes
= (Oid
*) palloc(argc
* sizeof(Oid
));
3567 qdesc
->arginfuncs
= (FmgrInfo
*) palloc(argc
* sizeof(FmgrInfo
));
3568 qdesc
->argtypioparams
= (Oid
*) palloc(argc
* sizeof(Oid
));
3569 MemoryContextSwitchTo(oldcontext
);
3571 /************************************************************
3572 * Do the following work in a short-lived context so that we don't
3573 * leak a lot of memory in the PL/Perl function's SPI Proc context.
3574 ************************************************************/
3575 work_cxt
= AllocSetContextCreate(CurrentMemoryContext
,
3576 "PL/Perl spi_prepare workspace",
3577 ALLOCSET_DEFAULT_SIZES
);
3578 MemoryContextSwitchTo(work_cxt
);
3580 /************************************************************
3581 * Resolve argument type names and then look them up by oid
3582 * in the system cache, and remember the required information
3583 * for input conversion.
3584 ************************************************************/
3585 for (i
= 0; i
< argc
; i
++)
3593 typstr
= sv2cstr(argv
[i
]);
3594 parseTypeString(typstr
, &typId
, &typmod
, false);
3597 getTypeInputInfo(typId
, &typInput
, &typIOParam
);
3599 qdesc
->argtypes
[i
] = typId
;
3600 fmgr_info_cxt(typInput
, &(qdesc
->arginfuncs
[i
]), plan_cxt
);
3601 qdesc
->argtypioparams
[i
] = typIOParam
;
3604 /* Make sure the query is validly encoded */
3605 pg_verifymbstr(query
, strlen(query
), false);
3607 /************************************************************
3608 * Prepare the plan and check for errors
3609 ************************************************************/
3610 plan
= SPI_prepare(query
, argc
, qdesc
->argtypes
);
3613 elog(ERROR
, "SPI_prepare() failed:%s",
3614 SPI_result_code_string(SPI_result
));
3616 /************************************************************
3617 * Save the plan into permanent memory (right now it's in the
3618 * SPI procCxt, which will go away at function end).
3619 ************************************************************/
3620 if (SPI_keepplan(plan
))
3621 elog(ERROR
, "SPI_keepplan() failed");
3624 /************************************************************
3625 * Insert a hashtable entry for the plan.
3626 ************************************************************/
3627 hash_entry
= hash_search(plperl_active_interp
->query_hash
,
3629 HASH_ENTER
, &found
);
3630 hash_entry
->query_data
= qdesc
;
3632 /* Get rid of workspace */
3633 MemoryContextDelete(work_cxt
);
3635 /* Commit the inner transaction, return to outer xact context */
3636 ReleaseCurrentSubTransaction();
3637 MemoryContextSwitchTo(oldcontext
);
3638 CurrentResourceOwner
= oldowner
;
3644 /* Save error info */
3645 MemoryContextSwitchTo(oldcontext
);
3646 edata
= CopyErrorData();
3649 /* Drop anything we managed to allocate */
3651 hash_search(plperl_active_interp
->query_hash
,
3655 MemoryContextDelete(plan_cxt
);
3659 /* Abort the inner transaction */
3660 RollbackAndReleaseCurrentSubTransaction();
3661 MemoryContextSwitchTo(oldcontext
);
3662 CurrentResourceOwner
= oldowner
;
3664 /* Punt the error to Perl */
3665 croak_cstr(edata
->message
);
3667 /* Can't get here, but keep compiler quiet */
3672 /************************************************************
3673 * Return the query's hash key to the caller.
3674 ************************************************************/
3675 return cstr2sv(qdesc
->qname
);
3679 plperl_spi_exec_prepared(char *query
, HV
*attr
, int argc
, SV
**argv
)
3688 plperl_query_desc
*qdesc
;
3689 plperl_query_entry
*hash_entry
;
3692 * Execute the query inside a sub-transaction, so we can cope with errors
3695 MemoryContext oldcontext
= CurrentMemoryContext
;
3696 ResourceOwner oldowner
= CurrentResourceOwner
;
3698 check_spi_usage_allowed();
3700 BeginInternalSubTransaction(NULL
);
3701 /* Want to run inside function's memory context */
3702 MemoryContextSwitchTo(oldcontext
);
3708 /************************************************************
3709 * Fetch the saved plan descriptor, see if it's o.k.
3710 ************************************************************/
3711 hash_entry
= hash_search(plperl_active_interp
->query_hash
, query
,
3713 if (hash_entry
== NULL
)
3714 elog(ERROR
, "spi_exec_prepared: Invalid prepared query passed");
3716 qdesc
= hash_entry
->query_data
;
3718 elog(ERROR
, "spi_exec_prepared: plperl query_hash value vanished");
3720 if (qdesc
->nargs
!= argc
)
3721 elog(ERROR
, "spi_exec_prepared: expected %d argument(s), %d passed",
3722 qdesc
->nargs
, argc
);
3724 /************************************************************
3725 * Parse eventual attributes
3726 ************************************************************/
3730 sv
= hv_fetch_string(attr
, "limit");
3731 if (sv
&& *sv
&& SvIOK(*sv
))
3734 /************************************************************
3736 ************************************************************/
3739 nulls
= (char *) palloc(argc
);
3740 argvalues
= (Datum
*) palloc(argc
* sizeof(Datum
));
3748 for (i
= 0; i
< argc
; i
++)
3752 argvalues
[i
] = plperl_sv_to_datum(argv
[i
],
3756 &qdesc
->arginfuncs
[i
],
3757 qdesc
->argtypioparams
[i
],
3759 nulls
[i
] = isnull
? 'n' : ' ';
3762 /************************************************************
3764 ************************************************************/
3765 spi_rv
= SPI_execute_plan(qdesc
->plan
, argvalues
, nulls
,
3766 current_call_data
->prodesc
->fn_readonly
, limit
);
3767 ret_hv
= plperl_spi_execute_fetch_result(SPI_tuptable
, SPI_processed
,
3775 /* Commit the inner transaction, return to outer xact context */
3776 ReleaseCurrentSubTransaction();
3777 MemoryContextSwitchTo(oldcontext
);
3778 CurrentResourceOwner
= oldowner
;
3784 /* Save error info */
3785 MemoryContextSwitchTo(oldcontext
);
3786 edata
= CopyErrorData();
3789 /* Abort the inner transaction */
3790 RollbackAndReleaseCurrentSubTransaction();
3791 MemoryContextSwitchTo(oldcontext
);
3792 CurrentResourceOwner
= oldowner
;
3794 /* Punt the error to Perl */
3795 croak_cstr(edata
->message
);
3797 /* Can't get here, but keep compiler quiet */
3806 plperl_spi_query_prepared(char *query
, int argc
, SV
**argv
)
3811 plperl_query_desc
*qdesc
;
3812 plperl_query_entry
*hash_entry
;
3814 Portal portal
= NULL
;
3817 * Execute the query inside a sub-transaction, so we can cope with errors
3820 MemoryContext oldcontext
= CurrentMemoryContext
;
3821 ResourceOwner oldowner
= CurrentResourceOwner
;
3823 check_spi_usage_allowed();
3825 BeginInternalSubTransaction(NULL
);
3826 /* Want to run inside function's memory context */
3827 MemoryContextSwitchTo(oldcontext
);
3831 /************************************************************
3832 * Fetch the saved plan descriptor, see if it's o.k.
3833 ************************************************************/
3834 hash_entry
= hash_search(plperl_active_interp
->query_hash
, query
,
3836 if (hash_entry
== NULL
)
3837 elog(ERROR
, "spi_query_prepared: Invalid prepared query passed");
3839 qdesc
= hash_entry
->query_data
;
3841 elog(ERROR
, "spi_query_prepared: plperl query_hash value vanished");
3843 if (qdesc
->nargs
!= argc
)
3844 elog(ERROR
, "spi_query_prepared: expected %d argument(s), %d passed",
3845 qdesc
->nargs
, argc
);
3847 /************************************************************
3849 ************************************************************/
3852 nulls
= (char *) palloc(argc
);
3853 argvalues
= (Datum
*) palloc(argc
* sizeof(Datum
));
3861 for (i
= 0; i
< argc
; i
++)
3865 argvalues
[i
] = plperl_sv_to_datum(argv
[i
],
3869 &qdesc
->arginfuncs
[i
],
3870 qdesc
->argtypioparams
[i
],
3872 nulls
[i
] = isnull
? 'n' : ' ';
3875 /************************************************************
3877 ************************************************************/
3878 portal
= SPI_cursor_open(NULL
, qdesc
->plan
, argvalues
, nulls
,
3879 current_call_data
->prodesc
->fn_readonly
);
3886 elog(ERROR
, "SPI_cursor_open() failed:%s",
3887 SPI_result_code_string(SPI_result
));
3889 cursor
= cstr2sv(portal
->name
);
3893 /* Commit the inner transaction, return to outer xact context */
3894 ReleaseCurrentSubTransaction();
3895 MemoryContextSwitchTo(oldcontext
);
3896 CurrentResourceOwner
= oldowner
;
3902 /* Save error info */
3903 MemoryContextSwitchTo(oldcontext
);
3904 edata
= CopyErrorData();
3907 /* Abort the inner transaction */
3908 RollbackAndReleaseCurrentSubTransaction();
3909 MemoryContextSwitchTo(oldcontext
);
3910 CurrentResourceOwner
= oldowner
;
3912 /* Punt the error to Perl */
3913 croak_cstr(edata
->message
);
3915 /* Can't get here, but keep compiler quiet */
3924 plperl_spi_freeplan(char *query
)
3927 plperl_query_desc
*qdesc
;
3928 plperl_query_entry
*hash_entry
;
3930 check_spi_usage_allowed();
3932 hash_entry
= hash_search(plperl_active_interp
->query_hash
, query
,
3934 if (hash_entry
== NULL
)
3935 elog(ERROR
, "spi_freeplan: Invalid prepared query passed");
3937 qdesc
= hash_entry
->query_data
;
3939 elog(ERROR
, "spi_freeplan: plperl query_hash value vanished");
3943 * free all memory before SPI_freeplan, so if it dies, nothing will be
3946 hash_search(plperl_active_interp
->query_hash
, query
,
3949 MemoryContextDelete(qdesc
->plan_cxt
);
3955 plperl_spi_commit(void)
3957 MemoryContext oldcontext
= CurrentMemoryContext
;
3962 SPI_start_transaction();
3968 /* Save error info */
3969 MemoryContextSwitchTo(oldcontext
);
3970 edata
= CopyErrorData();
3973 /* Punt the error to Perl */
3974 croak_cstr(edata
->message
);
3980 plperl_spi_rollback(void)
3982 MemoryContext oldcontext
= CurrentMemoryContext
;
3987 SPI_start_transaction();
3993 /* Save error info */
3994 MemoryContextSwitchTo(oldcontext
);
3995 edata
= CopyErrorData();
3998 /* Punt the error to Perl */
3999 croak_cstr(edata
->message
);
4005 * Implementation of plperl's elog() function
4007 * If the error level is less than ERROR, we'll just emit the message and
4008 * return. When it is ERROR, elog() will longjmp, which we catch and
4009 * turn into a Perl croak(). Note we are assuming that elog() can't have
4010 * any internal failures that are so bad as to require a transaction abort.
4012 * The main reason this is out-of-line is to avoid conflicts between XSUB.h
4013 * and the PG_TRY macros.
4016 plperl_util_elog(int level
, SV
*msg
)
4018 MemoryContext oldcontext
= CurrentMemoryContext
;
4019 char *volatile cmsg
= NULL
;
4023 cmsg
= sv2cstr(msg
);
4024 elog(level
, "%s", cmsg
);
4031 /* Must reset elog.c's state */
4032 MemoryContextSwitchTo(oldcontext
);
4033 edata
= CopyErrorData();
4039 /* Punt the error to Perl */
4040 croak_cstr(edata
->message
);
4046 * Store an SV into a hash table under a key that is a string assumed to be
4047 * in the current database's encoding.
4050 hv_store_string(HV
*hv
, const char *key
, SV
*val
)
4057 hkey
= pg_server_to_any(key
, strlen(key
), PG_UTF8
);
4060 * hv_store() recognizes a negative klen parameter as meaning a UTF-8
4063 hlen
= -(int) strlen(hkey
);
4064 ret
= hv_store(hv
, hkey
, hlen
, val
, 0);
4073 * Fetch an SV from a hash table under a key that is a string assumed to be
4074 * in the current database's encoding.
4077 hv_fetch_string(HV
*hv
, const char *key
)
4084 hkey
= pg_server_to_any(key
, strlen(key
), PG_UTF8
);
4086 /* See notes in hv_store_string */
4087 hlen
= -(int) strlen(hkey
);
4088 ret
= hv_fetch(hv
, hkey
, hlen
, 0);
4097 * Provide function name for PL/Perl execution errors
4100 plperl_exec_callback(void *arg
)
4102 char *procname
= (char *) arg
;
4105 errcontext("PL/Perl function \"%s\"", procname
);
4109 * Provide function name for PL/Perl compilation errors
4112 plperl_compile_callback(void *arg
)
4114 char *procname
= (char *) arg
;
4117 errcontext("compilation of PL/Perl function \"%s\"", procname
);
4121 * Provide error context for the inline handler
4124 plperl_inline_callback(void *arg
)
4126 errcontext("PL/Perl anonymous code block");
4131 * Perl's own setlocale(), copied from POSIX.xs
4132 * (needed because of the calls to new_*())
4136 setlocale_perl(int category
, char *locale
)
4139 char *RETVAL
= setlocale(category
, locale
);
4143 #ifdef USE_LOCALE_CTYPE
4144 if (category
== LC_CTYPE
4146 || category
== LC_ALL
4153 if (category
== LC_ALL
)
4154 newctype
= setlocale(LC_CTYPE
, NULL
);
4158 new_ctype(newctype
);
4160 #endif /* USE_LOCALE_CTYPE */
4161 #ifdef USE_LOCALE_COLLATE
4162 if (category
== LC_COLLATE
4164 || category
== LC_ALL
4171 if (category
== LC_ALL
)
4172 newcoll
= setlocale(LC_COLLATE
, NULL
);
4176 new_collate(newcoll
);
4178 #endif /* USE_LOCALE_COLLATE */
4180 #ifdef USE_LOCALE_NUMERIC
4181 if (category
== LC_NUMERIC
4183 || category
== LC_ALL
4190 if (category
== LC_ALL
)
4191 newnum
= setlocale(LC_NUMERIC
, NULL
);
4195 new_numeric(newnum
);
4197 #endif /* USE_LOCALE_NUMERIC */