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