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