1 /**********************************************************************
2 * plperl.c - perl as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plperl/plperl.c,v 1.168 2010/02/16 21:39:52 adunstan Exp $
6 **********************************************************************/
18 /* postgreSQL stuff */
19 #include "access/xact.h"
20 #include "catalog/pg_language.h"
21 #include "catalog/pg_proc.h"
22 #include "catalog/pg_type.h"
23 #include "commands/trigger.h"
24 #include "executor/spi.h"
26 #include "mb/pg_wchar.h"
27 #include "miscadmin.h"
28 #include "nodes/makefuncs.h"
29 #include "parser/parse_type.h"
30 #include "storage/ipc.h"
31 #include "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/syscache.h"
38 #include "utils/typcache.h"
40 /* define our text domain for translations */
42 #define TEXTDOMAIN PG_TEXTDOMAIN("plperl")
47 /* string literal macros defining chunks of perl code */
48 #include "perlchunks.h"
52 /**********************************************************************
53 * The information we cache about loaded procedures
54 **********************************************************************/
55 typedef struct plperl_proc_desc
57 char *proname; /* user name of procedure */
58 TransactionId fn_xmin;
59 ItemPointerData fn_tid;
62 bool fn_retistuple; /* true, if function returns tuple */
63 bool fn_retisset; /* true, if function returns set */
64 bool fn_retisarray; /* true if function returns array */
65 Oid result_oid; /* Oid of result type */
66 FmgrInfo result_in_func; /* I/O function and arg for result type */
67 Oid result_typioparam;
69 FmgrInfo arg_out_func[FUNC_MAX_ARGS];
70 bool arg_is_rowtype[FUNC_MAX_ARGS];
74 /* hash table entry for proc desc */
76 typedef struct plperl_proc_entry
78 char proc_name[NAMEDATALEN]; /* internal name, eg
79 * __PLPerl_proc_39987 */
80 plperl_proc_desc *proc_data;
84 * The information we cache for the duration of a single call to a
87 typedef struct plperl_call_data
89 plperl_proc_desc *prodesc;
90 FunctionCallInfo fcinfo;
91 Tuplestorestate *tuple_store;
93 AttInMetadata *attinmeta;
94 MemoryContext tmp_cxt;
97 /**********************************************************************
98 * The information we cache about prepared and saved plans
99 **********************************************************************/
100 typedef struct plperl_query_desc
106 FmgrInfo *arginfuncs;
110 /* hash table entry for query desc */
112 typedef struct plperl_query_entry
114 char query_name[NAMEDATALEN];
115 plperl_query_desc *query_data;
116 } plperl_query_entry;
118 /**********************************************************************
120 **********************************************************************/
131 static InterpState interp_state = INTERP_NONE;
133 static PerlInterpreter *plperl_trusted_interp = NULL;
134 static PerlInterpreter *plperl_untrusted_interp = NULL;
135 static PerlInterpreter *plperl_held_interp = NULL;
136 static OP *(*pp_require_orig)(pTHX) = NULL;
137 static bool trusted_context;
138 static HTAB *plperl_proc_hash = NULL;
139 static HTAB *plperl_query_hash = NULL;
141 static bool plperl_use_strict = false;
142 static char *plperl_on_init = NULL;
143 static char *plperl_on_plperl_init = NULL;
144 static char *plperl_on_plperlu_init = NULL;
145 static bool plperl_ending = false;
147 /* this is saved and restored by plperl_call_handler */
148 static plperl_call_data *current_call_data = NULL;
150 /**********************************************************************
151 * Forward declarations
152 **********************************************************************/
153 Datum plperl_call_handler(PG_FUNCTION_ARGS);
154 Datum plperl_inline_handler(PG_FUNCTION_ARGS);
155 Datum plperl_validator(PG_FUNCTION_ARGS);
158 static PerlInterpreter *plperl_init_interp(void);
159 static void plperl_destroy_interp(PerlInterpreter **);
160 static void plperl_fini(int code, Datum arg);
162 static Datum plperl_func_handler(PG_FUNCTION_ARGS);
163 static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
165 static plperl_proc_desc *compile_plperl_function(Oid fn_oid, bool is_trigger);
167 static SV *plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc);
168 static void plperl_init_shared_libs(pTHX);
169 static void plperl_trusted_init(void);
170 static void plperl_untrusted_init(void);
171 static HV *plperl_spi_execute_fetch_result(SPITupleTable *, int, int);
172 static SV *newSVstring(const char *str);
173 static SV **hv_store_string(HV *hv, const char *key, SV *val);
174 static SV **hv_fetch_string(HV *hv, const char *key);
175 static void plperl_create_sub(plperl_proc_desc *desc, char *s, Oid fn_oid);
176 static SV *plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo);
177 static void plperl_compile_callback(void *arg);
178 static void plperl_exec_callback(void *arg);
179 static void plperl_inline_callback(void *arg);
180 static char *strip_trailing_ws(const char *msg);
181 static OP * pp_require_safe(pTHX);
182 static int restore_context(bool);
185 * Convert an SV to char * and verify the encoding via pg_verifymbstr()
188 sv2text_mbverified(SV *sv)
193 /* The value returned here might include an
194 * embedded nul byte, because perl allows such things.
195 * That's OK, because pg_verifymbstr will choke on it, If
196 * we just used strlen() instead of getting perl's idea of
197 * the length, whatever uses the "verified" value might
198 * get something quite weird.
201 pg_verifymbstr(val, len, false);
206 * This routine is a crock, and so is everyplace that calls it. The problem
207 * is that the cached form of plperl functions/queries is allocated permanently
208 * (mostly via malloc()) and never released until backend exit. Subsidiary
209 * data structures such as fmgr info records therefore must live forever
210 * as well. A better implementation would store all this stuff in a per-
211 * function memory context that could be reclaimed at need. In the meantime,
212 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
213 * it might allocate, and whatever the eventual function might allocate using
214 * fn_mcxt, will live forever too.
217 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
219 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
224 * _PG_init() - library load-time initialization
226 * DO NOT make this static nor change its name!
231 /* Be sure we do initialization only once (should be redundant now) */
232 static bool inited = false;
238 pg_bindtextdomain(TEXTDOMAIN);
240 DefineCustomBoolVariable("plperl.use_strict",
241 gettext_noop("If true, trusted and untrusted Perl code will be compiled in strict mode."),
248 DefineCustomStringVariable("plperl.on_init",
249 gettext_noop("Perl initialization code to execute when a perl interpreter is initialized."),
257 * plperl.on_plperl_init is currently PGC_SUSET to avoid issues whereby a user
258 * who doesn't have USAGE privileges on the plperl language could possibly use
259 * SET plperl.on_plperl_init='...' to influence the behaviour of any existing
260 * plperl function that they can EXECUTE (which may be security definer).
261 * Set http://archives.postgresql.org/pgsql-hackers/2010-02/msg00281.php
262 * and the overall thread.
264 DefineCustomStringVariable("plperl.on_plperl_init",
265 gettext_noop("Perl initialization code to execute once when plperl is first used."),
267 &plperl_on_plperl_init,
272 DefineCustomStringVariable("plperl.on_plperlu_init",
273 gettext_noop("Perl initialization code to execute once when plperlu is first used."),
275 &plperl_on_plperlu_init,
280 EmitWarningsOnPlaceholders("plperl");
282 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
284 hash_ctl.keysize = NAMEDATALEN;
285 hash_ctl.entrysize = sizeof(plperl_proc_entry);
287 plperl_proc_hash = hash_create("PLPerl Procedures",
292 hash_ctl.entrysize = sizeof(plperl_query_entry);
293 plperl_query_hash = hash_create("PLPerl Queries",
298 plperl_held_interp = plperl_init_interp();
299 interp_state = INTERP_HELD;
306 * Cleanup perl interpreters, including running END blocks.
307 * Does not fully undo the actions of _PG_init() nor make it callable again.
310 plperl_fini(int code, Datum arg)
312 elog(DEBUG3, "plperl_fini");
315 * Indicate that perl is terminating.
316 * Disables use of spi_* functions when running END/DESTROY code.
317 * See check_spi_usage_allowed().
318 * Could be enabled in future, with care, using a transaction
319 * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02743.php
321 plperl_ending = true;
323 /* Only perform perl cleanup if we're exiting cleanly */
325 elog(DEBUG3, "plperl_fini: skipped");
329 plperl_destroy_interp(&plperl_trusted_interp);
330 plperl_destroy_interp(&plperl_untrusted_interp);
331 plperl_destroy_interp(&plperl_held_interp);
333 elog(DEBUG3, "plperl_fini: done");
337 #define SAFE_MODULE \
338 "require Safe; $Safe::VERSION"
340 /********************************************************************
342 * We start out by creating a "held" interpreter that we can use in
343 * trusted or untrusted mode (but not both) as the need arises. Later, we
344 * assign that interpreter if it is available to either the trusted or
345 * untrusted interpreter. If it has already been assigned, and we need to
346 * create the other interpreter, we do that if we can, or error out.
351 select_perl_context(bool trusted)
353 EXTERN_C void boot_PostgreSQL__InServer__SPI(pTHX_ CV *cv);
356 * handle simple cases
358 if (restore_context(trusted))
362 * adopt held interp if free, else create new one if possible
364 if (interp_state == INTERP_HELD)
366 /* first actual use of a perl interpreter */
370 plperl_trusted_init();
371 plperl_trusted_interp = plperl_held_interp;
372 interp_state = INTERP_TRUSTED;
376 plperl_untrusted_init();
377 plperl_untrusted_interp = plperl_held_interp;
378 interp_state = INTERP_UNTRUSTED;
381 /* successfully initialized, so arrange for cleanup */
382 on_proc_exit(plperl_fini, 0);
388 PerlInterpreter *plperl = plperl_init_interp();
390 plperl_trusted_init();
391 plperl_trusted_interp = plperl;
394 plperl_untrusted_init();
395 plperl_untrusted_interp = plperl;
397 interp_state = INTERP_BOTH;
400 "cannot allocate second Perl interpreter on this platform");
403 plperl_held_interp = NULL;
404 trusted_context = trusted;
407 * Since the timing of first use of PL/Perl can't be predicted,
408 * any database interaction during initialization is problematic.
409 * Including, but not limited to, security definer issues.
410 * So we only enable access to the database AFTER on_*_init code has run.
411 * See http://archives.postgresql.org/message-id/20100127143318.GE713@timac.local
413 newXS("PostgreSQL::InServer::SPI::bootstrap",
414 boot_PostgreSQL__InServer__SPI, __FILE__);
416 eval_pv("PostgreSQL::InServer::SPI::bootstrap()", FALSE);
419 (errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV))),
420 errdetail("While executing PostgreSQL::InServer::SPI::bootstrap.")));
424 * Restore previous interpreter selection, if two are active
427 restore_context(bool trusted)
429 if (interp_state == INTERP_BOTH ||
430 ( trusted && interp_state == INTERP_TRUSTED) ||
431 (!trusted && interp_state == INTERP_UNTRUSTED))
433 if (trusted_context != trusted)
436 PERL_SET_CONTEXT(plperl_trusted_interp);
437 PL_ppaddr[OP_REQUIRE] = pp_require_safe;
440 PERL_SET_CONTEXT(plperl_untrusted_interp);
441 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
443 trusted_context = trusted;
445 return 1; /* context restored */
448 return 0; /* unable - appropriate interpreter not available */
451 static PerlInterpreter *
452 plperl_init_interp(void)
454 PerlInterpreter *plperl;
455 static int perl_sys_init_done;
457 static char *embedding[3+2] = {
458 "", "-e", PLC_PERLBOOT
465 * The perl library on startup does horrible things like call
466 * setlocale(LC_ALL,""). We have protected against that on most platforms
467 * by setting the environment appropriately. However, on Windows,
468 * setlocale() does not consult the environment, so we need to save the
469 * existing locale settings before perl has a chance to mangle them and
470 * restore them after its dirty deeds are done.
473 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_locale.asp
475 * It appears that we only need to do this on interpreter startup, and
476 * subsequent calls to the interpreter don't mess with the locale
479 * We restore them using Perl's POSIX::setlocale() function so that Perl
480 * doesn't have a different idea of the locale from Postgres.
492 loc = setlocale(LC_COLLATE, NULL);
493 save_collate = loc ? pstrdup(loc) : NULL;
494 loc = setlocale(LC_CTYPE, NULL);
495 save_ctype = loc ? pstrdup(loc) : NULL;
496 loc = setlocale(LC_MONETARY, NULL);
497 save_monetary = loc ? pstrdup(loc) : NULL;
498 loc = setlocale(LC_NUMERIC, NULL);
499 save_numeric = loc ? pstrdup(loc) : NULL;
500 loc = setlocale(LC_TIME, NULL);
501 save_time = loc ? pstrdup(loc) : NULL;
506 embedding[nargs++] = "-e";
507 embedding[nargs++] = plperl_on_init;
511 * The perl API docs state that PERL_SYS_INIT3 should be called before
512 * allocating interprters. Unfortunately, on some platforms this fails
513 * in the Perl_do_taint() routine, which is called when the platform is
514 * using the system's malloc() instead of perl's own. Other platforms,
515 * notably Windows, fail if PERL_SYS_INIT3 is not called. So we call it
516 * if it's available, unless perl is using the system malloc(), which is
517 * true when MYMALLOC is set.
519 #if defined(PERL_SYS_INIT3) && !defined(MYMALLOC)
520 /* only call this the first time through, as per perlembed man page */
521 if (!perl_sys_init_done)
523 char *dummy_env[1] = {NULL};
525 PERL_SYS_INIT3(&nargs, (char ***) &embedding, (char ***) &dummy_env);
526 perl_sys_init_done = 1;
527 /* quiet warning if PERL_SYS_INIT3 doesn't use the third argument */
532 plperl = perl_alloc();
534 elog(ERROR, "could not allocate Perl interpreter");
536 PERL_SET_CONTEXT(plperl);
537 perl_construct(plperl);
539 /* run END blocks in perl_destruct instead of perl_run */
540 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
543 * Record the original function for the 'require' opcode.
544 * Ensure it's used for new interpreters.
546 if (!pp_require_orig)
547 pp_require_orig = PL_ppaddr[OP_REQUIRE];
549 PL_ppaddr[OP_REQUIRE] = pp_require_orig;
551 if (perl_parse(plperl, plperl_init_shared_libs,
552 nargs, embedding, NULL) != 0)
554 (errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV))),
555 errcontext("While parsing perl initialization.")));
557 if (perl_run(plperl) != 0)
559 (errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV))),
560 errcontext("While running perl initialization.")));
564 eval_pv("use POSIX qw(locale_h);", TRUE); /* croak on failure */
566 if (save_collate != NULL)
568 snprintf(buf, sizeof(buf), "setlocale(%s,'%s');",
569 "LC_COLLATE", save_collate);
573 if (save_ctype != NULL)
575 snprintf(buf, sizeof(buf), "setlocale(%s,'%s');",
576 "LC_CTYPE", save_ctype);
580 if (save_monetary != NULL)
582 snprintf(buf, sizeof(buf), "setlocale(%s,'%s');",
583 "LC_MONETARY", save_monetary);
585 pfree(save_monetary);
587 if (save_numeric != NULL)
589 snprintf(buf, sizeof(buf), "setlocale(%s,'%s');",
590 "LC_NUMERIC", save_numeric);
594 if (save_time != NULL)
596 snprintf(buf, sizeof(buf), "setlocale(%s,'%s');",
597 "LC_TIME", save_time);
608 * Our safe implementation of the require opcode.
609 * This is safe because it's completely unable to load any code.
610 * If the requested file/module has already been loaded it'll return true.
612 * So now "use Foo;" will work iff Foo has already been loaded.
615 pp_require_safe(pTHX)
623 name = SvPV(sv, len);
624 if (!(name && len > 0 && *name))
627 svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
628 if (svp && *svp != &PL_sv_undef)
631 DIE(aTHX_ "Unable to load %s into plperl", name);
636 plperl_destroy_interp(PerlInterpreter **interp)
638 if (interp && *interp)
641 * Only a very minimal destruction is performed:
642 * - just call END blocks.
644 * We could call perl_destruct() but we'd need to audit its
645 * actions very carefully and work-around any that impact us.
646 * (Calling sv_clean_objs() isn't an option because it's not
647 * part of perl's public API so isn't portably available.)
648 * Meanwhile END blocks can be used to perform manual cleanup.
651 PERL_SET_CONTEXT(*interp);
653 /* Run END blocks - based on perl's perl_destruct() */
654 if (PL_exit_flags & PERL_EXIT_DESTRUCT_END) {
660 if (PL_endav && !PL_minus_c)
661 call_list(PL_scopestack_ix, PL_endav);
673 plperl_trusted_init(void)
676 IV safe_version_x100;
678 safe_version_sv = eval_pv(SAFE_MODULE, FALSE);/* TRUE = croak if failure */
679 safe_version_x100 = (int)(SvNV(safe_version_sv) * 100);
682 * Reject too-old versions of Safe and some others:
683 * 2.20: http://rt.perl.org/rt3/Ticket/Display.html?id=72068
684 * 2.21: http://rt.perl.org/rt3/Ticket/Display.html?id=72700
686 if (safe_version_x100 < 209 || safe_version_x100 == 220 ||
687 safe_version_x100 == 221)
689 /* not safe, so disallow all trusted funcs */
690 eval_pv(PLC_SAFE_BAD, FALSE);
693 (errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV))),
694 errcontext("While executing PLC_SAFE_BAD.")));
698 eval_pv(PLC_SAFE_OK, FALSE);
701 (errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV))),
702 errcontext("While executing PLC_SAFE_OK.")));
704 if (GetDatabaseEncoding() == PG_UTF8)
707 * Force loading of utf8 module now to prevent errors that can
708 * arise from the regex code later trying to load utf8 modules.
709 * See http://rt.perl.org/rt3/Ticket/Display.html?id=47576
711 eval_pv("my $a=chr(0x100); return $a =~ /\\xa9/i", FALSE);
714 (errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV))),
715 errcontext("While executing utf8fix.")));
718 /* switch to the safe require opcode */
719 PL_ppaddr[OP_REQUIRE] = pp_require_safe;
721 if (plperl_on_plperl_init && *plperl_on_plperl_init)
726 XPUSHs(sv_2mortal(newSVstring(plperl_on_plperl_init)));
729 call_pv("PostgreSQL::InServer::safe::safe_eval", G_VOID);
734 (errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV))),
735 errcontext("While executing plperl.on_plperl_init.")));
743 plperl_untrusted_init(void)
745 if (plperl_on_plperlu_init && *plperl_on_plperlu_init)
747 eval_pv(plperl_on_plperlu_init, FALSE);
750 (errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV))),
751 errcontext("While executing plperl.on_plperlu_init.")));
757 * Perl likes to put a newline after its error messages; clean up such
760 strip_trailing_ws(const char *msg)
762 char *res = pstrdup(msg);
763 int len = strlen(res);
765 while (len > 0 && isspace((unsigned char) res[len - 1]))
771 /* Build a tuple from a hash. */
774 plperl_build_tuple_result(HV *perlhash, AttInMetadata *attinmeta)
776 TupleDesc td = attinmeta->tupdesc;
783 values = (char **) palloc0(td->natts * sizeof(char *));
785 hv_iterinit(perlhash);
786 while ((val = hv_iternextsv(perlhash, &key, &klen)))
788 int attn = SPI_fnumber(td, key);
790 if (attn <= 0 || td->attrs[attn - 1]->attisdropped)
792 (errcode(ERRCODE_UNDEFINED_COLUMN),
793 errmsg("Perl hash contains nonexistent column \"%s\"",
797 values[attn - 1] = sv2text_mbverified(val);
800 hv_iterinit(perlhash);
802 tup = BuildTupleFromCStrings(attinmeta, values);
808 * convert perl array to postgres string representation
811 plperl_convert_to_pg_array(SV *src)
821 count = perl_call_pv("::encode_array_literal", G_SCALAR);
826 elog(ERROR, "unexpected encode_array_literal failure");
836 /* Set up the arguments for a trigger call. */
839 plperl_trigger_build_args(FunctionCallInfo fcinfo)
851 hv_ksplit(hv, 12); /* pre-grow the hash */
853 tdata = (TriggerData *) fcinfo->context;
854 tupdesc = tdata->tg_relation->rd_att;
856 relid = DatumGetCString(
857 DirectFunctionCall1(oidout,
858 ObjectIdGetDatum(tdata->tg_relation->rd_id)
862 hv_store_string(hv, "name", newSVstring(tdata->tg_trigger->tgname));
863 hv_store_string(hv, "relid", newSVstring(relid));
865 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
868 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
869 hv_store_string(hv, "new",
870 plperl_hash_from_tuple(tdata->tg_trigtuple,
873 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
876 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
877 hv_store_string(hv, "old",
878 plperl_hash_from_tuple(tdata->tg_trigtuple,
881 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
884 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
886 hv_store_string(hv, "old",
887 plperl_hash_from_tuple(tdata->tg_trigtuple,
889 hv_store_string(hv, "new",
890 plperl_hash_from_tuple(tdata->tg_newtuple,
894 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
899 hv_store_string(hv, "event", newSVstring(event));
900 hv_store_string(hv, "argc", newSViv(tdata->tg_trigger->tgnargs));
902 if (tdata->tg_trigger->tgnargs > 0)
906 av_extend(av, tdata->tg_trigger->tgnargs);
907 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
908 av_push(av, newSVstring(tdata->tg_trigger->tgargs[i]));
909 hv_store_string(hv, "args", newRV_noinc((SV *) av));
912 hv_store_string(hv, "relname",
913 newSVstring(SPI_getrelname(tdata->tg_relation)));
915 hv_store_string(hv, "table_name",
916 newSVstring(SPI_getrelname(tdata->tg_relation)));
918 hv_store_string(hv, "table_schema",
919 newSVstring(SPI_getnspname(tdata->tg_relation)));
921 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
923 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
927 hv_store_string(hv, "when", newSVstring(when));
929 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
931 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
935 hv_store_string(hv, "level", newSVstring(level));
937 return newRV_noinc((SV *) hv);
941 /* Set up the new tuple returned from a trigger. */
944 plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup)
959 tupdesc = tdata->tg_relation->rd_att;
961 svp = hv_fetch_string(hvTD, "new");
964 (errcode(ERRCODE_UNDEFINED_COLUMN),
965 errmsg("$_TD->{new} does not exist")));
966 if (!SvOK(*svp) || SvTYPE(*svp) != SVt_RV || SvTYPE(SvRV(*svp)) != SVt_PVHV)
968 (errcode(ERRCODE_DATATYPE_MISMATCH),
969 errmsg("$_TD->{new} is not a hash reference")));
970 hvNew = (HV *) SvRV(*svp);
972 modattrs = palloc(tupdesc->natts * sizeof(int));
973 modvalues = palloc(tupdesc->natts * sizeof(Datum));
974 modnulls = palloc(tupdesc->natts * sizeof(char));
978 while ((val = hv_iternextsv(hvNew, &key, &klen)))
980 int attn = SPI_fnumber(tupdesc, key);
986 if (attn <= 0 || tupdesc->attrs[attn - 1]->attisdropped)
988 (errcode(ERRCODE_UNDEFINED_COLUMN),
989 errmsg("Perl hash contains nonexistent column \"%s\"",
991 /* XXX would be better to cache these lookups */
992 getTypeInputInfo(tupdesc->attrs[attn - 1]->atttypid,
993 &typinput, &typioparam);
994 fmgr_info(typinput, &finfo);
995 atttypmod = tupdesc->attrs[attn - 1]->atttypmod;
998 modvalues[slotsused] = InputFunctionCall(&finfo,
999 sv2text_mbverified(val),
1002 modnulls[slotsused] = ' ';
1006 modvalues[slotsused] = InputFunctionCall(&finfo,
1010 modnulls[slotsused] = 'n';
1012 modattrs[slotsused] = attn;
1017 rtup = SPI_modifytuple(tdata->tg_relation, otup, slotsused,
1018 modattrs, modvalues, modnulls);
1025 elog(ERROR, "SPI_modifytuple failed: %s",
1026 SPI_result_code_string(SPI_result));
1033 * There are three externally visible pieces to plperl: plperl_call_handler,
1034 * plperl_inline_handler, and plperl_validator.
1038 * The call handler is called to run normal functions (including trigger
1039 * functions) that are defined in pg_proc.
1041 PG_FUNCTION_INFO_V1(plperl_call_handler);
1044 plperl_call_handler(PG_FUNCTION_ARGS)
1047 plperl_call_data *save_call_data = current_call_data;
1048 bool oldcontext = trusted_context;
1052 if (CALLED_AS_TRIGGER(fcinfo))
1053 retval = PointerGetDatum(plperl_trigger_handler(fcinfo));
1055 retval = plperl_func_handler(fcinfo);
1059 current_call_data = save_call_data;
1060 restore_context(oldcontext);
1065 current_call_data = save_call_data;
1066 restore_context(oldcontext);
1071 * The inline handler runs anonymous code blocks (DO blocks).
1073 PG_FUNCTION_INFO_V1(plperl_inline_handler);
1076 plperl_inline_handler(PG_FUNCTION_ARGS)
1078 InlineCodeBlock *codeblock = (InlineCodeBlock *) PG_GETARG_POINTER(0);
1079 FunctionCallInfoData fake_fcinfo;
1081 plperl_proc_desc desc;
1082 plperl_call_data *save_call_data = current_call_data;
1083 bool oldcontext = trusted_context;
1084 ErrorContextCallback pl_error_context;
1086 /* Set up a callback for error reporting */
1087 pl_error_context.callback = plperl_inline_callback;
1088 pl_error_context.previous = error_context_stack;
1089 pl_error_context.arg = (Datum) 0;
1090 error_context_stack = &pl_error_context;
1093 * Set up a fake fcinfo and descriptor with just enough info to satisfy
1094 * plperl_call_perl_func(). In particular note that this sets things up
1095 * with no arguments passed, and a result type of VOID.
1097 MemSet(&fake_fcinfo, 0, sizeof(fake_fcinfo));
1098 MemSet(&flinfo, 0, sizeof(flinfo));
1099 MemSet(&desc, 0, sizeof(desc));
1100 fake_fcinfo.flinfo = &flinfo;
1101 flinfo.fn_oid = InvalidOid;
1102 flinfo.fn_mcxt = CurrentMemoryContext;
1104 desc.proname = "inline_code_block";
1105 desc.fn_readonly = false;
1107 desc.lanpltrusted = codeblock->langIsTrusted;
1109 desc.fn_retistuple = false;
1110 desc.fn_retisset = false;
1111 desc.fn_retisarray = false;
1112 desc.result_oid = VOIDOID;
1114 desc.reference = NULL;
1116 current_call_data = (plperl_call_data *) palloc0(sizeof(plperl_call_data));
1117 current_call_data->fcinfo = &fake_fcinfo;
1118 current_call_data->prodesc = &desc;
1124 if (SPI_connect() != SPI_OK_CONNECT)
1125 elog(ERROR, "could not connect to SPI manager");
1127 select_perl_context(desc.lanpltrusted);
1129 plperl_create_sub(&desc, codeblock->source_text, 0);
1131 if (!desc.reference) /* can this happen? */
1132 elog(ERROR, "could not create internal procedure for anonymous code block");
1134 perlret = plperl_call_perl_func(&desc, &fake_fcinfo);
1136 SvREFCNT_dec(perlret);
1138 if (SPI_finish() != SPI_OK_FINISH)
1139 elog(ERROR, "SPI_finish() failed");
1143 current_call_data = save_call_data;
1144 restore_context(oldcontext);
1146 SvREFCNT_dec(desc.reference);
1151 current_call_data = save_call_data;
1152 restore_context(oldcontext);
1154 SvREFCNT_dec(desc.reference);
1156 error_context_stack = pl_error_context.previous;
1162 * The validator is called during CREATE FUNCTION to validate the function
1163 * being created/replaced. The precise behavior of the validator may be
1164 * modified by the check_function_bodies GUC.
1166 PG_FUNCTION_INFO_V1(plperl_validator);
1169 plperl_validator(PG_FUNCTION_ARGS)
1171 Oid funcoid = PG_GETARG_OID(0);
1179 bool istrigger = false;
1182 /* Get the new function's pg_proc entry */
1183 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
1184 if (!HeapTupleIsValid(tuple))
1185 elog(ERROR, "cache lookup failed for function %u", funcoid);
1186 proc = (Form_pg_proc) GETSTRUCT(tuple);
1188 functyptype = get_typtype(proc->prorettype);
1190 /* Disallow pseudotype result */
1191 /* except for TRIGGER, RECORD, or VOID */
1192 if (functyptype == TYPTYPE_PSEUDO)
1194 /* we assume OPAQUE with no arguments means a trigger */
1195 if (proc->prorettype == TRIGGEROID ||
1196 (proc->prorettype == OPAQUEOID && proc->pronargs == 0))
1198 else if (proc->prorettype != RECORDOID &&
1199 proc->prorettype != VOIDOID)
1201 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1202 errmsg("PL/Perl functions cannot return type %s",
1203 format_type_be(proc->prorettype))));
1206 /* Disallow pseudotypes in arguments (either IN or OUT) */
1207 numargs = get_func_arg_info(tuple,
1208 &argtypes, &argnames, &argmodes);
1209 for (i = 0; i < numargs; i++)
1211 if (get_typtype(argtypes[i]) == TYPTYPE_PSEUDO)
1213 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1214 errmsg("PL/Perl functions cannot accept type %s",
1215 format_type_be(argtypes[i]))));
1218 ReleaseSysCache(tuple);
1220 /* Postpone body checks if !check_function_bodies */
1221 if (check_function_bodies)
1223 (void) compile_plperl_function(funcoid, istrigger);
1226 /* the result of a validator is ignored */
1232 * Uses mksafefunc/mkunsafefunc to create a subroutine whose text is
1233 * supplied in s, and returns a reference to it
1236 plperl_create_sub(plperl_proc_desc *prodesc, char *s, Oid fn_oid)
1239 bool trusted = prodesc->lanpltrusted;
1240 char subname[NAMEDATALEN+40];
1241 HV *pragma_hv = newHV();
1246 sprintf(subname, "%s__%u", prodesc->proname, fn_oid);
1248 if (plperl_use_strict)
1249 hv_store_string(pragma_hv, "strict", (SV*)newAV());
1255 PUSHs(sv_2mortal(newSVstring(subname)));
1256 PUSHs(sv_2mortal(newRV_noinc((SV*)pragma_hv)));
1257 PUSHs(sv_2mortal(newSVstring("our $_TD; local $_TD=shift;")));
1258 PUSHs(sv_2mortal(newSVstring(s)));
1262 * G_KEEPERR seems to be needed here, else we don't recognize compile
1263 * errors properly. Perhaps it's because there's another level of eval
1264 * inside mksafefunc?
1266 compile_sub = (trusted)
1267 ? "PostgreSQL::InServer::safe::mksafefunc"
1268 : "PostgreSQL::InServer::mkunsafefunc";
1269 count = perl_call_pv(compile_sub, G_SCALAR | G_EVAL | G_KEEPERR);
1273 GV *sub_glob = (GV*)POPs;
1274 if (sub_glob && SvTYPE(sub_glob) == SVt_PVGV) {
1275 SV *sv = (SV*)GvCVu((GV*)sub_glob);
1277 subref = newRV_inc(sv);
1287 (errcode(ERRCODE_SYNTAX_ERROR),
1288 errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV)))));
1292 (errmsg("didn't get a GLOB from compiling %s via %s",
1293 prodesc->proname, compile_sub)));
1295 prodesc->reference = newSVsv(subref);
1301 /**********************************************************************
1302 * plperl_init_shared_libs() -
1304 * We cannot use the DynaLoader directly to get at the Opcode
1305 * module (used by Safe.pm). So, we link Opcode into ourselves
1306 * and do the initialization behind perl's back.
1308 **********************************************************************/
1311 plperl_init_shared_libs(pTHX)
1313 char *file = __FILE__;
1314 EXTERN_C void boot_DynaLoader(pTHX_ CV *cv);
1315 EXTERN_C void boot_PostgreSQL__InServer__Util(pTHX_ CV *cv);
1317 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
1318 newXS("PostgreSQL::InServer::Util::bootstrap",
1319 boot_PostgreSQL__InServer__Util, file);
1320 /* newXS for...::SPI::bootstrap is in select_perl_context() */
1325 plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
1337 EXTEND(sp, 1 + desc->nargs);
1339 PUSHs(&PL_sv_undef); /* no trigger data */
1341 for (i = 0; i < desc->nargs; i++)
1343 if (fcinfo->argnull[i])
1344 PUSHs(&PL_sv_undef);
1345 else if (desc->arg_is_rowtype[i])
1351 HeapTupleData tmptup;
1354 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
1355 /* Extract rowtype info and find a tupdesc */
1356 tupType = HeapTupleHeaderGetTypeId(td);
1357 tupTypmod = HeapTupleHeaderGetTypMod(td);
1358 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1359 /* Build a temporary HeapTuple control structure */
1360 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1363 hashref = plperl_hash_from_tuple(&tmptup, tupdesc);
1364 PUSHs(sv_2mortal(hashref));
1365 ReleaseTupleDesc(tupdesc);
1371 tmp = OutputFunctionCall(&(desc->arg_out_func[i]),
1373 sv = newSVstring(tmp);
1374 PUSHs(sv_2mortal(sv));
1380 /* Do NOT use G_KEEPERR here */
1381 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
1390 elog(ERROR, "didn't get a return item from function");
1399 /* XXX need to find a way to assign an errcode here */
1401 (errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV)))));
1404 retval = newSVsv(POPs);
1415 plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo,
1420 Trigger *tg_trigger;
1431 tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
1432 for (i = 0; i < tg_trigger->tgnargs; i++)
1433 XPUSHs(sv_2mortal(newSVstring(tg_trigger->tgargs[i])));
1436 /* Do NOT use G_KEEPERR here */
1437 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
1446 elog(ERROR, "didn't get a return item from trigger function");
1455 /* XXX need to find a way to assign an errcode here */
1457 (errmsg("%s", strip_trailing_ws(SvPV_nolen(ERRSV)))));
1460 retval = newSVsv(POPs);
1471 plperl_func_handler(PG_FUNCTION_ARGS)
1473 plperl_proc_desc *prodesc;
1477 SV *array_ret = NULL;
1478 ErrorContextCallback pl_error_context;
1481 * Create the call_data beforing connecting to SPI, so that it is not
1482 * allocated in the SPI memory context
1484 current_call_data = (plperl_call_data *) palloc0(sizeof(plperl_call_data));
1485 current_call_data->fcinfo = fcinfo;
1487 if (SPI_connect() != SPI_OK_CONNECT)
1488 elog(ERROR, "could not connect to SPI manager");
1490 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false);
1491 current_call_data->prodesc = prodesc;
1493 /* Set a callback for error reporting */
1494 pl_error_context.callback = plperl_exec_callback;
1495 pl_error_context.previous = error_context_stack;
1496 pl_error_context.arg = prodesc->proname;
1497 error_context_stack = &pl_error_context;
1499 rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1501 if (prodesc->fn_retisset)
1503 /* Check context before allowing the call to go through */
1504 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1505 (rsi->allowedModes & SFRM_Materialize) == 0 ||
1506 rsi->expectedDesc == NULL)
1508 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1509 errmsg("set-valued function called in context that "
1510 "cannot accept a set")));
1513 select_perl_context(prodesc->lanpltrusted);
1515 perlret = plperl_call_perl_func(prodesc, fcinfo);
1517 /************************************************************
1518 * Disconnect from SPI manager and then create the return
1519 * values datum (if the input function does a palloc for it
1520 * this must not be allocated in the SPI memory context
1521 * because SPI_finish would free it).
1522 ************************************************************/
1523 if (SPI_finish() != SPI_OK_FINISH)
1524 elog(ERROR, "SPI_finish() failed");
1526 if (prodesc->fn_retisset)
1529 * If the Perl function returned an arrayref, we pretend that it
1530 * called return_next() for each element of the array, to handle old
1531 * SRFs that didn't know about return_next(). Any other sort of return
1532 * value is an error, except undef which means return an empty set.
1534 if (SvOK(perlret) &&
1535 SvTYPE(perlret) == SVt_RV &&
1536 SvTYPE(SvRV(perlret)) == SVt_PVAV)
1540 AV *rav = (AV *) SvRV(perlret);
1542 while ((svp = av_fetch(rav, i, FALSE)) != NULL)
1544 plperl_return_next(*svp);
1548 else if (SvOK(perlret))
1551 (errcode(ERRCODE_DATATYPE_MISMATCH),
1552 errmsg("set-returning PL/Perl function must return "
1553 "reference to array or use return_next")));
1556 rsi->returnMode = SFRM_Materialize;
1557 if (current_call_data->tuple_store)
1559 rsi->setResult = current_call_data->tuple_store;
1560 rsi->setDesc = current_call_data->ret_tdesc;
1564 else if (!SvOK(perlret))
1566 /* Return NULL if Perl code returned undef */
1567 if (rsi && IsA(rsi, ReturnSetInfo))
1568 rsi->isDone = ExprEndResult;
1569 retval = InputFunctionCall(&prodesc->result_in_func, NULL,
1570 prodesc->result_typioparam, -1);
1571 fcinfo->isnull = true;
1573 else if (prodesc->fn_retistuple)
1575 /* Return a perl hash converted to a Datum */
1577 AttInMetadata *attinmeta;
1580 if (!SvOK(perlret) || SvTYPE(perlret) != SVt_RV ||
1581 SvTYPE(SvRV(perlret)) != SVt_PVHV)
1584 (errcode(ERRCODE_DATATYPE_MISMATCH),
1585 errmsg("composite-returning PL/Perl function "
1586 "must return reference to hash")));
1589 /* XXX should cache the attinmeta data instead of recomputing */
1590 if (get_call_result_type(fcinfo, NULL, &td) != TYPEFUNC_COMPOSITE)
1593 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1594 errmsg("function returning record called in context "
1595 "that cannot accept type record")));
1598 attinmeta = TupleDescGetAttInMetadata(td);
1599 tup = plperl_build_tuple_result((HV *) SvRV(perlret), attinmeta);
1600 retval = HeapTupleGetDatum(tup);
1604 /* Return a perl string converted to a Datum */
1606 if (prodesc->fn_retisarray && SvROK(perlret) &&
1607 SvTYPE(SvRV(perlret)) == SVt_PVAV)
1609 array_ret = plperl_convert_to_pg_array(perlret);
1610 SvREFCNT_dec(perlret);
1611 perlret = array_ret;
1614 retval = InputFunctionCall(&prodesc->result_in_func,
1615 sv2text_mbverified(perlret),
1616 prodesc->result_typioparam, -1);
1619 /* Restore the previous error callback */
1620 error_context_stack = pl_error_context.previous;
1622 if (array_ret == NULL)
1623 SvREFCNT_dec(perlret);
1630 plperl_trigger_handler(PG_FUNCTION_ARGS)
1632 plperl_proc_desc *prodesc;
1637 ErrorContextCallback pl_error_context;
1640 * Create the call_data beforing connecting to SPI, so that it is not
1641 * allocated in the SPI memory context
1643 current_call_data = (plperl_call_data *) palloc0(sizeof(plperl_call_data));
1644 current_call_data->fcinfo = fcinfo;
1646 /* Connect to SPI manager */
1647 if (SPI_connect() != SPI_OK_CONNECT)
1648 elog(ERROR, "could not connect to SPI manager");
1650 /* Find or compile the function */
1651 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true);
1652 current_call_data->prodesc = prodesc;
1654 /* Set a callback for error reporting */
1655 pl_error_context.callback = plperl_exec_callback;
1656 pl_error_context.previous = error_context_stack;
1657 pl_error_context.arg = prodesc->proname;
1658 error_context_stack = &pl_error_context;
1660 select_perl_context(prodesc->lanpltrusted);
1662 svTD = plperl_trigger_build_args(fcinfo);
1663 perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
1664 hvTD = (HV *) SvRV(svTD);
1666 /************************************************************
1667 * Disconnect from SPI manager and then create the return
1668 * values datum (if the input function does a palloc for it
1669 * this must not be allocated in the SPI memory context
1670 * because SPI_finish would free it).
1671 ************************************************************/
1672 if (SPI_finish() != SPI_OK_FINISH)
1673 elog(ERROR, "SPI_finish() failed");
1675 if (perlret == NULL || !SvOK(perlret))
1677 /* undef result means go ahead with original tuple */
1678 TriggerData *trigdata = ((TriggerData *) fcinfo->context);
1680 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1681 retval = (Datum) trigdata->tg_trigtuple;
1682 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1683 retval = (Datum) trigdata->tg_newtuple;
1684 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
1685 retval = (Datum) trigdata->tg_trigtuple;
1686 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
1687 retval = (Datum) trigdata->tg_trigtuple;
1689 retval = (Datum) 0; /* can this happen? */
1696 tmp = SvPV_nolen(perlret);
1698 if (pg_strcasecmp(tmp, "SKIP") == 0)
1700 else if (pg_strcasecmp(tmp, "MODIFY") == 0)
1702 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1704 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1705 trv = plperl_modify_tuple(hvTD, trigdata,
1706 trigdata->tg_trigtuple);
1707 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1708 trv = plperl_modify_tuple(hvTD, trigdata,
1709 trigdata->tg_newtuple);
1713 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1714 errmsg("ignoring modified row in DELETE trigger")));
1721 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1722 errmsg("result of PL/Perl trigger function must be undef, "
1723 "\"SKIP\", or \"MODIFY\"")));
1726 retval = PointerGetDatum(trv);
1729 /* Restore the previous error callback */
1730 error_context_stack = pl_error_context.previous;
1734 SvREFCNT_dec(perlret);
1740 static plperl_proc_desc *
1741 compile_plperl_function(Oid fn_oid, bool is_trigger)
1744 Form_pg_proc procStruct;
1745 char internal_proname[NAMEDATALEN];
1746 plperl_proc_desc *prodesc = NULL;
1748 plperl_proc_entry *hash_entry;
1750 bool oldcontext = trusted_context;
1751 ErrorContextCallback plperl_error_context;
1753 /* We'll need the pg_proc tuple in any case... */
1754 procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
1755 if (!HeapTupleIsValid(procTup))
1756 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1757 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1759 /* Set a callback for reporting compilation errors */
1760 plperl_error_context.callback = plperl_compile_callback;
1761 plperl_error_context.previous = error_context_stack;
1762 plperl_error_context.arg = NameStr(procStruct->proname);
1763 error_context_stack = &plperl_error_context;
1765 /************************************************************
1766 * Build our internal proc name from the function's Oid
1767 ************************************************************/
1769 sprintf(internal_proname, "__PLPerl_proc_%u", fn_oid);
1771 sprintf(internal_proname, "__PLPerl_proc_%u_trigger", fn_oid);
1773 /************************************************************
1774 * Lookup the internal proc name in the hashtable
1775 ************************************************************/
1776 hash_entry = hash_search(plperl_proc_hash, internal_proname,
1783 prodesc = hash_entry->proc_data;
1785 /************************************************************
1786 * If it's present, must check whether it's still up to date.
1787 * This is needed because CREATE OR REPLACE FUNCTION can modify the
1788 * function's pg_proc entry without changing its OID.
1789 ************************************************************/
1790 uptodate = (prodesc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&
1791 ItemPointerEquals(&prodesc->fn_tid, &procTup->t_self));
1795 hash_search(plperl_proc_hash, internal_proname,
1797 if (prodesc->reference) {
1798 select_perl_context(prodesc->lanpltrusted);
1799 SvREFCNT_dec(prodesc->reference);
1800 restore_context(oldcontext);
1802 free(prodesc->proname);
1808 /************************************************************
1809 * If we haven't found it in the hashtable, we analyze
1810 * the function's arguments and return type and store
1811 * the in-/out-functions in the prodesc block and create
1812 * a new hashtable entry for it.
1814 * Then we load the procedure into the Perl interpreter.
1815 ************************************************************/
1816 if (prodesc == NULL)
1820 Form_pg_language langStruct;
1821 Form_pg_type typeStruct;
1826 /************************************************************
1827 * Allocate a new procedure description block
1828 ************************************************************/
1829 prodesc = (plperl_proc_desc *) malloc(sizeof(plperl_proc_desc));
1830 if (prodesc == NULL)
1832 (errcode(ERRCODE_OUT_OF_MEMORY),
1833 errmsg("out of memory")));
1834 MemSet(prodesc, 0, sizeof(plperl_proc_desc));
1835 prodesc->proname = strdup(NameStr(procStruct->proname));
1836 prodesc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1837 prodesc->fn_tid = procTup->t_self;
1839 /* Remember if function is STABLE/IMMUTABLE */
1840 prodesc->fn_readonly =
1841 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1843 /************************************************************
1844 * Lookup the pg_language tuple by Oid
1845 ************************************************************/
1846 langTup = SearchSysCache1(LANGOID,
1847 ObjectIdGetDatum(procStruct->prolang));
1848 if (!HeapTupleIsValid(langTup))
1850 free(prodesc->proname);
1852 elog(ERROR, "cache lookup failed for language %u",
1853 procStruct->prolang);
1855 langStruct = (Form_pg_language) GETSTRUCT(langTup);
1856 prodesc->lanpltrusted = langStruct->lanpltrusted;
1857 ReleaseSysCache(langTup);
1859 /************************************************************
1860 * Get the required information for input conversion of the
1862 ************************************************************/
1866 SearchSysCache1(TYPEOID,
1867 ObjectIdGetDatum(procStruct->prorettype));
1868 if (!HeapTupleIsValid(typeTup))
1870 free(prodesc->proname);
1872 elog(ERROR, "cache lookup failed for type %u",
1873 procStruct->prorettype);
1875 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1877 /* Disallow pseudotype result, except VOID or RECORD */
1878 if (typeStruct->typtype == TYPTYPE_PSEUDO)
1880 if (procStruct->prorettype == VOIDOID ||
1881 procStruct->prorettype == RECORDOID)
1883 else if (procStruct->prorettype == TRIGGEROID)
1885 free(prodesc->proname);
1888 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1889 errmsg("trigger functions can only be called "
1894 free(prodesc->proname);
1897 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1898 errmsg("PL/Perl functions cannot return type %s",
1899 format_type_be(procStruct->prorettype))));
1903 prodesc->result_oid = procStruct->prorettype;
1904 prodesc->fn_retisset = procStruct->proretset;
1905 prodesc->fn_retistuple = (procStruct->prorettype == RECORDOID ||
1906 typeStruct->typtype == TYPTYPE_COMPOSITE);
1908 prodesc->fn_retisarray =
1909 (typeStruct->typlen == -1 && typeStruct->typelem);
1911 perm_fmgr_info(typeStruct->typinput, &(prodesc->result_in_func));
1912 prodesc->result_typioparam = getTypeIOParam(typeTup);
1914 ReleaseSysCache(typeTup);
1917 /************************************************************
1918 * Get the required information for output conversion
1919 * of all procedure arguments
1920 ************************************************************/
1923 prodesc->nargs = procStruct->pronargs;
1924 for (i = 0; i < prodesc->nargs; i++)
1926 typeTup = SearchSysCache1(TYPEOID,
1927 ObjectIdGetDatum(procStruct->proargtypes.values[i]));
1928 if (!HeapTupleIsValid(typeTup))
1930 free(prodesc->proname);
1932 elog(ERROR, "cache lookup failed for type %u",
1933 procStruct->proargtypes.values[i]);
1935 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1937 /* Disallow pseudotype argument */
1938 if (typeStruct->typtype == TYPTYPE_PSEUDO)
1940 free(prodesc->proname);
1943 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1944 errmsg("PL/Perl functions cannot accept type %s",
1945 format_type_be(procStruct->proargtypes.values[i]))));
1948 if (typeStruct->typtype == TYPTYPE_COMPOSITE)
1949 prodesc->arg_is_rowtype[i] = true;
1952 prodesc->arg_is_rowtype[i] = false;
1953 perm_fmgr_info(typeStruct->typoutput,
1954 &(prodesc->arg_out_func[i]));
1957 ReleaseSysCache(typeTup);
1961 /************************************************************
1962 * create the text of the anonymous subroutine.
1963 * we do not use a named subroutine so that we can call directly
1964 * through the reference.
1965 ************************************************************/
1966 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1967 Anum_pg_proc_prosrc, &isnull);
1969 elog(ERROR, "null prosrc");
1970 proc_source = TextDatumGetCString(prosrcdatum);
1972 /************************************************************
1973 * Create the procedure in the interpreter
1974 ************************************************************/
1976 select_perl_context(prodesc->lanpltrusted);
1978 plperl_create_sub(prodesc, proc_source, fn_oid);
1980 restore_context(oldcontext);
1983 if (!prodesc->reference) /* can this happen? */
1985 free(prodesc->proname);
1987 elog(ERROR, "could not create internal procedure \"%s\"",
1991 hash_entry = hash_search(plperl_proc_hash, internal_proname,
1992 HASH_ENTER, &found);
1993 hash_entry->proc_data = prodesc;
1996 /* restore previous error callback */
1997 error_context_stack = plperl_error_context.previous;
1999 ReleaseSysCache(procTup);
2005 /* Build a hash from all attributes of a given tuple. */
2008 plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
2014 hv_ksplit(hv, tupdesc->natts); /* pre-grow the hash */
2016 for (i = 0; i < tupdesc->natts; i++)
2025 if (tupdesc->attrs[i]->attisdropped)
2028 attname = NameStr(tupdesc->attrs[i]->attname);
2029 attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
2033 /* Store (attname => undef) and move on. */
2034 hv_store_string(hv, attname, newSV(0));
2038 /* XXX should have a way to cache these lookups */
2039 getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
2040 &typoutput, &typisvarlena);
2042 outputstr = OidOutputFunctionCall(typoutput, attr);
2044 hv_store_string(hv, attname, newSVstring(outputstr));
2049 return newRV_noinc((SV *) hv);
2054 check_spi_usage_allowed()
2056 /* see comment in plperl_fini() */
2057 if (plperl_ending) {
2058 /* simple croak as we don't want to involve PostgreSQL code */
2059 croak("SPI functions can not be used in END blocks");
2065 plperl_spi_exec(char *query, int limit)
2070 * Execute the query inside a sub-transaction, so we can cope with errors
2073 MemoryContext oldcontext = CurrentMemoryContext;
2074 ResourceOwner oldowner = CurrentResourceOwner;
2076 check_spi_usage_allowed();
2078 BeginInternalSubTransaction(NULL);
2079 /* Want to run inside function's memory context */
2080 MemoryContextSwitchTo(oldcontext);
2086 spi_rv = SPI_execute(query, current_call_data->prodesc->fn_readonly,
2088 ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
2091 /* Commit the inner transaction, return to outer xact context */
2092 ReleaseCurrentSubTransaction();
2093 MemoryContextSwitchTo(oldcontext);
2094 CurrentResourceOwner = oldowner;
2097 * AtEOSubXact_SPI() should not have popped any SPI context, but just
2098 * in case it did, make sure we remain connected.
2100 SPI_restore_connection();
2106 /* Save error info */
2107 MemoryContextSwitchTo(oldcontext);
2108 edata = CopyErrorData();
2111 /* Abort the inner transaction */
2112 RollbackAndReleaseCurrentSubTransaction();
2113 MemoryContextSwitchTo(oldcontext);
2114 CurrentResourceOwner = oldowner;
2117 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
2118 * have left us in a disconnected state. We need this hack to return
2119 * to connected state.
2121 SPI_restore_connection();
2123 /* Punt the error to Perl */
2124 croak("%s", edata->message);
2126 /* Can't get here, but keep compiler quiet */
2136 plperl_spi_execute_fetch_result(SPITupleTable *tuptable, int processed,
2141 check_spi_usage_allowed();
2145 hv_store_string(result, "status",
2146 newSVstring(SPI_result_code_string(status)));
2147 hv_store_string(result, "processed",
2148 newSViv(processed));
2150 if (status > 0 && tuptable)
2157 av_extend(rows, processed);
2158 for (i = 0; i < processed; i++)
2160 row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc);
2163 hv_store_string(result, "rows",
2164 newRV_noinc((SV *) rows));
2167 SPI_freetuptable(tuptable);
2174 * Note: plperl_return_next is called both in Postgres and Perl contexts.
2175 * We report any errors in Postgres fashion (via ereport). If called in
2176 * Perl context, it is SPI.xs's responsibility to catch the error and
2177 * convert to a Perl error. We assume (perhaps without adequate justification)
2178 * that we need not abort the current transaction if the Perl code traps the
2182 plperl_return_next(SV *sv)
2184 plperl_proc_desc *prodesc;
2185 FunctionCallInfo fcinfo;
2187 MemoryContext old_cxt;
2192 prodesc = current_call_data->prodesc;
2193 fcinfo = current_call_data->fcinfo;
2194 rsi = (ReturnSetInfo *) fcinfo->resultinfo;
2196 if (!prodesc->fn_retisset)
2198 (errcode(ERRCODE_SYNTAX_ERROR),
2199 errmsg("cannot use return_next in a non-SETOF function")));
2201 if (prodesc->fn_retistuple &&
2202 !(SvOK(sv) && SvTYPE(sv) == SVt_RV && SvTYPE(SvRV(sv)) == SVt_PVHV))
2204 (errcode(ERRCODE_DATATYPE_MISMATCH),
2205 errmsg("SETOF-composite-returning PL/Perl function "
2206 "must call return_next with reference to hash")));
2208 if (!current_call_data->ret_tdesc)
2212 Assert(!current_call_data->tuple_store);
2213 Assert(!current_call_data->attinmeta);
2216 * This is the first call to return_next in the current PL/Perl
2217 * function call, so memoize some lookups
2219 if (prodesc->fn_retistuple)
2220 (void) get_call_result_type(fcinfo, NULL, &tupdesc);
2222 tupdesc = rsi->expectedDesc;
2225 * Make sure the tuple_store and ret_tdesc are sufficiently
2228 old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
2230 current_call_data->ret_tdesc = CreateTupleDescCopy(tupdesc);
2231 current_call_data->tuple_store =
2232 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
2234 if (prodesc->fn_retistuple)
2236 current_call_data->attinmeta =
2237 TupleDescGetAttInMetadata(current_call_data->ret_tdesc);
2240 MemoryContextSwitchTo(old_cxt);
2244 * Producing the tuple we want to return requires making plenty of
2245 * palloc() allocations that are not cleaned up. Since this function can
2246 * be called many times before the current memory context is reset, we
2247 * need to do those allocations in a temporary context.
2249 if (!current_call_data->tmp_cxt)
2251 current_call_data->tmp_cxt =
2252 AllocSetContextCreate(rsi->econtext->ecxt_per_tuple_memory,
2253 "PL/Perl return_next temporary cxt",
2254 ALLOCSET_DEFAULT_MINSIZE,
2255 ALLOCSET_DEFAULT_INITSIZE,
2256 ALLOCSET_DEFAULT_MAXSIZE);
2259 old_cxt = MemoryContextSwitchTo(current_call_data->tmp_cxt);
2261 if (prodesc->fn_retistuple)
2265 tuple = plperl_build_tuple_result((HV *) SvRV(sv),
2266 current_call_data->attinmeta);
2267 tuplestore_puttuple(current_call_data->tuple_store, tuple);
2276 if (prodesc->fn_retisarray && SvROK(sv) &&
2277 SvTYPE(SvRV(sv)) == SVt_PVAV)
2279 sv = plperl_convert_to_pg_array(sv);
2282 ret = InputFunctionCall(&prodesc->result_in_func,
2283 sv2text_mbverified(sv),
2284 prodesc->result_typioparam, -1);
2289 ret = InputFunctionCall(&prodesc->result_in_func, NULL,
2290 prodesc->result_typioparam, -1);
2294 tuplestore_putvalues(current_call_data->tuple_store,
2295 current_call_data->ret_tdesc,
2299 MemoryContextSwitchTo(old_cxt);
2300 MemoryContextReset(current_call_data->tmp_cxt);
2305 plperl_spi_query(char *query)
2310 * Execute the query inside a sub-transaction, so we can cope with errors
2313 MemoryContext oldcontext = CurrentMemoryContext;
2314 ResourceOwner oldowner = CurrentResourceOwner;
2316 check_spi_usage_allowed();
2318 BeginInternalSubTransaction(NULL);
2319 /* Want to run inside function's memory context */
2320 MemoryContextSwitchTo(oldcontext);
2327 /* Create a cursor for the query */
2328 plan = SPI_prepare(query, 0, NULL);
2330 elog(ERROR, "SPI_prepare() failed:%s",
2331 SPI_result_code_string(SPI_result));
2333 portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
2336 elog(ERROR, "SPI_cursor_open() failed:%s",
2337 SPI_result_code_string(SPI_result));
2338 cursor = newSVstring(portal->name);
2340 /* Commit the inner transaction, return to outer xact context */
2341 ReleaseCurrentSubTransaction();
2342 MemoryContextSwitchTo(oldcontext);
2343 CurrentResourceOwner = oldowner;
2346 * AtEOSubXact_SPI() should not have popped any SPI context, but just
2347 * in case it did, make sure we remain connected.
2349 SPI_restore_connection();
2355 /* Save error info */
2356 MemoryContextSwitchTo(oldcontext);
2357 edata = CopyErrorData();
2360 /* Abort the inner transaction */
2361 RollbackAndReleaseCurrentSubTransaction();
2362 MemoryContextSwitchTo(oldcontext);
2363 CurrentResourceOwner = oldowner;
2366 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
2367 * have left us in a disconnected state. We need this hack to return
2368 * to connected state.
2370 SPI_restore_connection();
2372 /* Punt the error to Perl */
2373 croak("%s", edata->message);
2375 /* Can't get here, but keep compiler quiet */
2385 plperl_spi_fetchrow(char *cursor)
2390 * Execute the FETCH inside a sub-transaction, so we can cope with errors
2393 MemoryContext oldcontext = CurrentMemoryContext;
2394 ResourceOwner oldowner = CurrentResourceOwner;
2396 check_spi_usage_allowed();
2398 BeginInternalSubTransaction(NULL);
2399 /* Want to run inside function's memory context */
2400 MemoryContextSwitchTo(oldcontext);
2404 Portal p = SPI_cursor_find(cursor);
2412 SPI_cursor_fetch(p, true, 1);
2413 if (SPI_processed == 0)
2415 SPI_cursor_close(p);
2420 row = plperl_hash_from_tuple(SPI_tuptable->vals[0],
2421 SPI_tuptable->tupdesc);
2423 SPI_freetuptable(SPI_tuptable);
2426 /* Commit the inner transaction, return to outer xact context */
2427 ReleaseCurrentSubTransaction();
2428 MemoryContextSwitchTo(oldcontext);
2429 CurrentResourceOwner = oldowner;
2432 * AtEOSubXact_SPI() should not have popped any SPI context, but just
2433 * in case it did, make sure we remain connected.
2435 SPI_restore_connection();
2441 /* Save error info */
2442 MemoryContextSwitchTo(oldcontext);
2443 edata = CopyErrorData();
2446 /* Abort the inner transaction */
2447 RollbackAndReleaseCurrentSubTransaction();
2448 MemoryContextSwitchTo(oldcontext);
2449 CurrentResourceOwner = oldowner;
2452 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
2453 * have left us in a disconnected state. We need this hack to return
2454 * to connected state.
2456 SPI_restore_connection();
2458 /* Punt the error to Perl */
2459 croak("%s", edata->message);
2461 /* Can't get here, but keep compiler quiet */
2470 plperl_spi_cursor_close(char *cursor)
2474 check_spi_usage_allowed();
2476 p = SPI_cursor_find(cursor);
2479 SPI_cursor_close(p);
2483 plperl_spi_prepare(char *query, int argc, SV **argv)
2485 plperl_query_desc *qdesc;
2486 plperl_query_entry *hash_entry;
2491 MemoryContext oldcontext = CurrentMemoryContext;
2492 ResourceOwner oldowner = CurrentResourceOwner;
2494 check_spi_usage_allowed();
2496 BeginInternalSubTransaction(NULL);
2497 MemoryContextSwitchTo(oldcontext);
2499 /************************************************************
2500 * Allocate the new querydesc structure
2501 ************************************************************/
2502 qdesc = (plperl_query_desc *) malloc(sizeof(plperl_query_desc));
2503 MemSet(qdesc, 0, sizeof(plperl_query_desc));
2504 snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
2505 qdesc->nargs = argc;
2506 qdesc->argtypes = (Oid *) malloc(argc * sizeof(Oid));
2507 qdesc->arginfuncs = (FmgrInfo *) malloc(argc * sizeof(FmgrInfo));
2508 qdesc->argtypioparams = (Oid *) malloc(argc * sizeof(Oid));
2512 /************************************************************
2513 * Resolve argument type names and then look them up by oid
2514 * in the system cache, and remember the required information
2515 * for input conversion.
2516 ************************************************************/
2517 for (i = 0; i < argc; i++)
2524 parseTypeString(SvPV_nolen(argv[i]), &typId, &typmod);
2526 getTypeInputInfo(typId, &typInput, &typIOParam);
2528 qdesc->argtypes[i] = typId;
2529 perm_fmgr_info(typInput, &(qdesc->arginfuncs[i]));
2530 qdesc->argtypioparams[i] = typIOParam;
2533 /************************************************************
2534 * Prepare the plan and check for errors
2535 ************************************************************/
2536 plan = SPI_prepare(query, argc, qdesc->argtypes);
2539 elog(ERROR, "SPI_prepare() failed:%s",
2540 SPI_result_code_string(SPI_result));
2542 /************************************************************
2543 * Save the plan into permanent memory (right now it's in the
2544 * SPI procCxt, which will go away at function end).
2545 ************************************************************/
2546 qdesc->plan = SPI_saveplan(plan);
2547 if (qdesc->plan == NULL)
2548 elog(ERROR, "SPI_saveplan() failed: %s",
2549 SPI_result_code_string(SPI_result));
2551 /* Release the procCxt copy to avoid within-function memory leak */
2554 /* Commit the inner transaction, return to outer xact context */
2555 ReleaseCurrentSubTransaction();
2556 MemoryContextSwitchTo(oldcontext);
2557 CurrentResourceOwner = oldowner;
2560 * AtEOSubXact_SPI() should not have popped any SPI context, but just
2561 * in case it did, make sure we remain connected.
2563 SPI_restore_connection();
2569 free(qdesc->argtypes);
2570 free(qdesc->arginfuncs);
2571 free(qdesc->argtypioparams);
2574 /* Save error info */
2575 MemoryContextSwitchTo(oldcontext);
2576 edata = CopyErrorData();
2579 /* Abort the inner transaction */
2580 RollbackAndReleaseCurrentSubTransaction();
2581 MemoryContextSwitchTo(oldcontext);
2582 CurrentResourceOwner = oldowner;
2585 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
2586 * have left us in a disconnected state. We need this hack to return
2587 * to connected state.
2589 SPI_restore_connection();
2591 /* Punt the error to Perl */
2592 croak("%s", edata->message);
2594 /* Can't get here, but keep compiler quiet */
2599 /************************************************************
2600 * Insert a hashtable entry for the plan and return
2601 * the key to the caller.
2602 ************************************************************/
2604 hash_entry = hash_search(plperl_query_hash, qdesc->qname,
2605 HASH_ENTER, &found);
2606 hash_entry->query_data = qdesc;
2608 return newSVstring(qdesc->qname);
2612 plperl_spi_exec_prepared(char *query, HV *attr, int argc, SV **argv)
2621 plperl_query_desc *qdesc;
2622 plperl_query_entry *hash_entry;
2625 * Execute the query inside a sub-transaction, so we can cope with errors
2628 MemoryContext oldcontext = CurrentMemoryContext;
2629 ResourceOwner oldowner = CurrentResourceOwner;
2631 check_spi_usage_allowed();
2633 BeginInternalSubTransaction(NULL);
2634 /* Want to run inside function's memory context */
2635 MemoryContextSwitchTo(oldcontext);
2639 /************************************************************
2640 * Fetch the saved plan descriptor, see if it's o.k.
2641 ************************************************************/
2643 hash_entry = hash_search(plperl_query_hash, query,
2645 if (hash_entry == NULL)
2646 elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
2648 qdesc = hash_entry->query_data;
2651 elog(ERROR, "spi_exec_prepared: panic - plperl_query_hash value vanished");
2653 if (qdesc->nargs != argc)
2654 elog(ERROR, "spi_exec_prepared: expected %d argument(s), %d passed",
2655 qdesc->nargs, argc);
2657 /************************************************************
2658 * Parse eventual attributes
2659 ************************************************************/
2663 sv = hv_fetch_string(attr, "limit");
2664 if (*sv && SvIOK(*sv))
2667 /************************************************************
2669 ************************************************************/
2672 nulls = (char *) palloc(argc);
2673 argvalues = (Datum *) palloc(argc * sizeof(Datum));
2681 for (i = 0; i < argc; i++)
2685 argvalues[i] = InputFunctionCall(&qdesc->arginfuncs[i],
2686 sv2text_mbverified(argv[i]),
2687 qdesc->argtypioparams[i],
2693 argvalues[i] = InputFunctionCall(&qdesc->arginfuncs[i],
2695 qdesc->argtypioparams[i],
2701 /************************************************************
2703 ************************************************************/
2704 spi_rv = SPI_execute_plan(qdesc->plan, argvalues, nulls,
2705 current_call_data->prodesc->fn_readonly, limit);
2706 ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
2714 /* Commit the inner transaction, return to outer xact context */
2715 ReleaseCurrentSubTransaction();
2716 MemoryContextSwitchTo(oldcontext);
2717 CurrentResourceOwner = oldowner;
2720 * AtEOSubXact_SPI() should not have popped any SPI context, but just
2721 * in case it did, make sure we remain connected.
2723 SPI_restore_connection();
2729 /* Save error info */
2730 MemoryContextSwitchTo(oldcontext);
2731 edata = CopyErrorData();
2734 /* Abort the inner transaction */
2735 RollbackAndReleaseCurrentSubTransaction();
2736 MemoryContextSwitchTo(oldcontext);
2737 CurrentResourceOwner = oldowner;
2740 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
2741 * have left us in a disconnected state. We need this hack to return
2742 * to connected state.
2744 SPI_restore_connection();
2746 /* Punt the error to Perl */
2747 croak("%s", edata->message);
2749 /* Can't get here, but keep compiler quiet */
2758 plperl_spi_query_prepared(char *query, int argc, SV **argv)
2763 plperl_query_desc *qdesc;
2764 plperl_query_entry *hash_entry;
2766 Portal portal = NULL;
2769 * Execute the query inside a sub-transaction, so we can cope with errors
2772 MemoryContext oldcontext = CurrentMemoryContext;
2773 ResourceOwner oldowner = CurrentResourceOwner;
2775 check_spi_usage_allowed();
2777 BeginInternalSubTransaction(NULL);
2778 /* Want to run inside function's memory context */
2779 MemoryContextSwitchTo(oldcontext);
2783 /************************************************************
2784 * Fetch the saved plan descriptor, see if it's o.k.
2785 ************************************************************/
2786 hash_entry = hash_search(plperl_query_hash, query,
2788 if (hash_entry == NULL)
2789 elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
2791 qdesc = hash_entry->query_data;
2794 elog(ERROR, "spi_query_prepared: panic - plperl_query_hash value vanished");
2796 if (qdesc->nargs != argc)
2797 elog(ERROR, "spi_query_prepared: expected %d argument(s), %d passed",
2798 qdesc->nargs, argc);
2800 /************************************************************
2802 ************************************************************/
2805 nulls = (char *) palloc(argc);
2806 argvalues = (Datum *) palloc(argc * sizeof(Datum));
2814 for (i = 0; i < argc; i++)
2818 argvalues[i] = InputFunctionCall(&qdesc->arginfuncs[i],
2819 sv2text_mbverified(argv[i]),
2820 qdesc->argtypioparams[i],
2826 argvalues[i] = InputFunctionCall(&qdesc->arginfuncs[i],
2828 qdesc->argtypioparams[i],
2834 /************************************************************
2836 ************************************************************/
2837 portal = SPI_cursor_open(NULL, qdesc->plan, argvalues, nulls,
2838 current_call_data->prodesc->fn_readonly);
2845 elog(ERROR, "SPI_cursor_open() failed:%s",
2846 SPI_result_code_string(SPI_result));
2848 cursor = newSVstring(portal->name);
2850 /* Commit the inner transaction, return to outer xact context */
2851 ReleaseCurrentSubTransaction();
2852 MemoryContextSwitchTo(oldcontext);
2853 CurrentResourceOwner = oldowner;
2856 * AtEOSubXact_SPI() should not have popped any SPI context, but just
2857 * in case it did, make sure we remain connected.
2859 SPI_restore_connection();
2865 /* Save error info */
2866 MemoryContextSwitchTo(oldcontext);
2867 edata = CopyErrorData();
2870 /* Abort the inner transaction */
2871 RollbackAndReleaseCurrentSubTransaction();
2872 MemoryContextSwitchTo(oldcontext);
2873 CurrentResourceOwner = oldowner;
2876 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
2877 * have left us in a disconnected state. We need this hack to return
2878 * to connected state.
2880 SPI_restore_connection();
2882 /* Punt the error to Perl */
2883 croak("%s", edata->message);
2885 /* Can't get here, but keep compiler quiet */
2894 plperl_spi_freeplan(char *query)
2897 plperl_query_desc *qdesc;
2898 plperl_query_entry *hash_entry;
2900 check_spi_usage_allowed();
2902 hash_entry = hash_search(plperl_query_hash, query,
2904 if (hash_entry == NULL)
2905 elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
2907 qdesc = hash_entry->query_data;
2910 elog(ERROR, "spi_exec_freeplan: panic - plperl_query_hash value vanished");
2913 * free all memory before SPI_freeplan, so if it dies, nothing will be
2916 hash_search(plperl_query_hash, query,
2920 free(qdesc->argtypes);
2921 free(qdesc->arginfuncs);
2922 free(qdesc->argtypioparams);
2929 * Create a new SV from a string assumed to be in the current database's
2933 newSVstring(const char *str)
2937 sv = newSVpv(str, 0);
2938 #if PERL_BCDVERSION >= 0x5006000L
2939 if (GetDatabaseEncoding() == PG_UTF8)
2946 * Store an SV into a hash table under a key that is a string assumed to be
2947 * in the current database's encoding.
2950 hv_store_string(HV *hv, const char *key, SV *val)
2952 int32 klen = strlen(key);
2955 * This seems nowhere documented, but under Perl 5.8.0 and up, hv_store()
2956 * recognizes a negative klen parameter as meaning a UTF-8 encoded key. It
2957 * does not appear that hashes track UTF-8-ness of keys at all in Perl
2960 #if PERL_BCDVERSION >= 0x5008000L
2961 if (GetDatabaseEncoding() == PG_UTF8)
2964 return hv_store(hv, key, klen, val, 0);
2968 * Fetch an SV from a hash table under a key that is a string assumed to be
2969 * in the current database's encoding.
2972 hv_fetch_string(HV *hv, const char *key)
2974 int32 klen = strlen(key);
2976 /* See notes in hv_store_string */
2977 #if PERL_BCDVERSION >= 0x5008000L
2978 if (GetDatabaseEncoding() == PG_UTF8)
2981 return hv_fetch(hv, key, klen, 0);
2985 * Provide function name for PL/Perl execution errors
2988 plperl_exec_callback(void *arg)
2990 char *procname = (char *) arg;
2992 errcontext("PL/Perl function \"%s\"", procname);
2996 * Provide function name for PL/Perl compilation errors
2999 plperl_compile_callback(void *arg)
3001 char *procname = (char *) arg;
3003 errcontext("compilation of PL/Perl function \"%s\"", procname);
3007 * Provide error context for the inline handler
3010 plperl_inline_callback(void *arg)
3012 errcontext("PL/Perl anonymous code block");