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