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