1 /**********************************************************************
2 * plperl.c - perl as a procedural language for PostgreSQL
6 * This software is copyrighted by Mark Hollomon
7 * but is shameless cribbed from pltcl.c by Jan Weick.
9 * The author hereby grants permission to use, copy, modify,
10 * distribute, and license this software and its documentation
11 * for any purpose, provided that existing copyright notices are
12 * retained in all copies and that this notice is included
13 * verbatim in any distributions. No written agreement, license,
14 * or royalty fee is required for any of the authorized uses.
15 * Modifications to this software may be copyrighted by their
16 * author and need not follow the licensing terms described
17 * here, provided that the new terms are clearly indicated on
18 * the first page of each file where they apply.
20 * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY
21 * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR
22 * CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS
23 * SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN
24 * IF THE AUTHOR HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
27 * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY
28 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
29 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
30 * PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON
31 * AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAVE NO
32 * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
33 * ENHANCEMENTS, OR MODIFICATIONS.
36 * $PostgreSQL: pgsql/src/pl/plperl/plperl.c,v 1.61 2004/11/21 22:13:37 tgl Exp $
38 **********************************************************************/
47 /* postgreSQL stuff */
48 #include "access/heapam.h"
49 #include "catalog/pg_language.h"
50 #include "catalog/pg_proc.h"
51 #include "catalog/pg_type.h"
52 #include "funcapi.h" /* need for SRF support */
53 #include "commands/trigger.h"
54 #include "executor/spi.h"
56 #include "tcop/tcopprot.h"
57 #include "utils/lsyscache.h"
58 #include "utils/syscache.h"
59 #include "utils/typcache.h"
67 /* just in case these symbols aren't provided */
74 /**********************************************************************
75 * The information we cache about loaded procedures
76 **********************************************************************/
77 typedef struct plperl_proc_desc
80 TransactionId fn_xmin;
84 bool fn_retistuple; /* true, if function returns tuple */
85 bool fn_retisset; /* true, if function returns set */
86 Oid ret_oid; /* Oid of returning type */
87 FmgrInfo result_in_func;
88 Oid result_typioparam;
90 FmgrInfo arg_out_func[FUNC_MAX_ARGS];
91 Oid arg_typioparam[FUNC_MAX_ARGS];
92 bool arg_is_rowtype[FUNC_MAX_ARGS];
97 /**********************************************************************
99 **********************************************************************/
100 static int plperl_firstcall = 1;
101 static bool plperl_safe_init_done = false;
102 static PerlInterpreter *plperl_interp = NULL;
103 static HV *plperl_proc_hash = NULL;
104 static AV *g_column_keys = NULL;
105 static SV *srf_perlret = NULL; /* keep returned value */
106 static int g_attr_num = 0;
108 /* this is saved and restored by plperl_call_handler */
109 static plperl_proc_desc *plperl_current_prodesc = NULL;
111 /**********************************************************************
112 * Forward declarations
113 **********************************************************************/
114 static void plperl_init_all(void);
115 static void plperl_init_interp(void);
117 Datum plperl_call_handler(PG_FUNCTION_ARGS);
118 void plperl_init(void);
120 HV *plperl_spi_exec(char *query, int limit);
122 static Datum plperl_func_handler(PG_FUNCTION_ARGS);
124 static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
125 static plperl_proc_desc *compile_plperl_function(Oid fn_oid, bool is_trigger);
127 static SV *plperl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc);
128 static void plperl_init_shared_libs(pTHX);
129 static HV *plperl_spi_execute_fetch_result(SPITupleTable *, int, int);
133 * This routine is a crock, and so is everyplace that calls it. The problem
134 * is that the cached form of plperl functions/queries is allocated permanently
135 * (mostly via malloc()) and never released until backend exit. Subsidiary
136 * data structures such as fmgr info records therefore must live forever
137 * as well. A better implementation would store all this stuff in a per-
138 * function memory context that could be reclaimed at need. In the meantime,
139 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
140 * it might allocate, and whatever the eventual function might allocate using
141 * fn_mcxt, will live forever too.
144 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
146 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
149 /**********************************************************************
150 * plperl_init() - Initialize everything that can be
151 * safely initialized during postmaster
154 * DO NOT make this static --- it has to be callable by preload
155 **********************************************************************/
159 /************************************************************
160 * Do initialization only once
161 ************************************************************/
162 if (!plperl_firstcall)
165 /************************************************************
166 * Free the proc hash table
167 ************************************************************/
168 if (plperl_proc_hash != NULL)
170 hv_undef(plperl_proc_hash);
171 SvREFCNT_dec((SV *) plperl_proc_hash);
172 plperl_proc_hash = NULL;
175 /************************************************************
176 * Destroy the existing Perl interpreter
177 ************************************************************/
178 if (plperl_interp != NULL)
180 perl_destruct(plperl_interp);
181 perl_free(plperl_interp);
182 plperl_interp = NULL;
185 /************************************************************
186 * Now recreate a new Perl interpreter
187 ************************************************************/
188 plperl_init_interp();
190 plperl_firstcall = 0;
193 /**********************************************************************
194 * plperl_init_all() - Initialize all
195 **********************************************************************/
197 plperl_init_all(void)
200 /************************************************************
201 * Execute postmaster-startup safe initialization
202 ************************************************************/
203 if (plperl_firstcall)
206 /************************************************************
207 * Any other initialization that must be done each time a new
208 * backend starts -- currently none
209 ************************************************************/
214 /**********************************************************************
215 * plperl_init_interp() - Create the Perl interpreter
216 **********************************************************************/
218 plperl_init_interp(void)
221 char *embedding[3] = {
225 * no commas between the next lines please. They are supposed to
228 "SPI::bootstrap(); use vars qw(%_SHARED);"
229 "sub ::mkunsafefunc {return eval(qq[ sub { $_[0] $_[1] } ]); }"
232 plperl_interp = perl_alloc();
234 elog(ERROR, "could not allocate perl interpreter");
236 perl_construct(plperl_interp);
237 perl_parse(plperl_interp, plperl_init_shared_libs, 3, embedding, NULL);
238 perl_run(plperl_interp);
240 /************************************************************
241 * Initialize the proc and query hash tables
242 ************************************************************/
243 plperl_proc_hash = newHV();
248 plperl_safe_init(void)
250 static char *safe_module =
251 "require Safe; $Safe::VERSION";
253 static char *safe_ok =
254 "use vars qw($PLContainer); $PLContainer = new Safe('PLPerl');"
255 "$PLContainer->permit_only(':default');"
256 "$PLContainer->permit(qw[:base_math !:base_io sort time]);"
257 "$PLContainer->share(qw[&elog &spi_exec_query &DEBUG &LOG "
258 "&INFO &NOTICE &WARNING &ERROR %SHARED ]);"
259 "sub ::mksafefunc { return $PLContainer->reval(qq[sub { $_[0] $_[1]}]); }"
262 static char *safe_bad =
263 "use vars qw($PLContainer); $PLContainer = new Safe('PLPerl');"
264 "$PLContainer->permit_only(':default');"
265 "$PLContainer->share(qw[&elog &ERROR ]);"
266 "sub ::mksafefunc { return $PLContainer->reval(qq[sub { "
267 "elog(ERROR,'trusted perl functions disabled - "
268 "please upgrade perl Safe module to at least 2.09');}]); }"
275 res = eval_pv(safe_module, FALSE); /* TRUE = croak if failure */
277 safe_version = SvNV(res);
279 eval_pv((safe_version < 2.09 ? safe_bad : safe_ok), FALSE);
281 plperl_safe_init_done = true;
286 * Perl likes to put a newline after its error messages; clean up such
289 strip_trailing_ws(const char *msg)
291 char *res = pstrdup(msg);
292 int len = strlen(res);
294 while (len > 0 && isspace((unsigned char) res[len-1]))
301 plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
305 for (i = 0; i < tupdesc->natts; i++)
309 char *key = SPI_fname(tupdesc, i+1);
310 char *val = SPI_getvalue(tuple, tupdesc, i + 1);
313 value = newSVpv(val, 0);
317 hv_store(hv, key, strlen(key), value, 0);
323 /**********************************************************************
324 * set up arguments for a trigger call
325 **********************************************************************/
327 plperl_trigger_build_args(FunctionCallInfo fcinfo)
340 tdata = (TriggerData *) fcinfo->context;
341 tupdesc = tdata->tg_relation->rd_att;
343 relid = DatumGetCString(
345 oidout, ObjectIdGetDatum(tdata->tg_relation->rd_id)
349 hv_store(hv, "name", 4, newSVpv(tdata->tg_trigger->tgname, 0), 0);
350 hv_store(hv, "relid", 5, newSVpv(relid, 0), 0);
352 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
355 hv_store(hv, "new", 3,
356 newRV((SV *)plperl_hash_from_tuple(tdata->tg_trigtuple,
360 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
363 hv_store(hv, "old", 3,
364 newRV((SV *)plperl_hash_from_tuple(tdata->tg_trigtuple,
368 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
371 hv_store(hv, "old", 3,
372 newRV((SV *)plperl_hash_from_tuple(tdata->tg_trigtuple,
375 hv_store(hv, "new", 3,
376 newRV((SV *)plperl_hash_from_tuple(tdata->tg_newtuple,
384 hv_store(hv, "event", 5, newSVpv(event, 0), 0);
385 hv_store(hv, "argc", 4, newSViv(tdata->tg_trigger->tgnargs), 0);
387 if (tdata->tg_trigger->tgnargs != 0)
390 for (i=0; i < tdata->tg_trigger->tgnargs; i++)
391 av_push(av, newSVpv(tdata->tg_trigger->tgargs[i], 0));
392 hv_store(hv, "args", 4, newRV((SV *)av), 0);
395 hv_store(hv, "relname", 7,
396 newSVpv(SPI_getrelname(tdata->tg_relation), 0), 0);
398 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
400 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
404 hv_store(hv, "when", 4, newSVpv(when, 0), 0);
406 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
408 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
412 hv_store(hv, "level", 5, newSVpv(level, 0), 0);
414 return newRV((SV*)hv);
418 /**********************************************************************
419 * check return value from plperl function
420 **********************************************************************/
422 plperl_is_set(SV *sv)
431 if (SvTYPE(sv) != SVt_RV)
434 if (SvTYPE(SvRV(sv)) == SVt_PVHV)
437 if (SvTYPE(SvRV(sv)) == SVt_PVAV)
439 input_av = (AV *) SvRV(sv);
440 len = av_len(input_av) + 1;
442 for (i = 0; i < len; i++)
444 val = av_fetch(input_av, i, FALSE);
445 if (SvTYPE(*val) == SVt_RV)
459 elog(ERROR, "plperl: check your return value structure");
461 elog(ERROR, "plperl: check your return value structure");
463 return 0; /* for compiler */
466 /**********************************************************************
467 * extract a list of keys from a hash
468 **********************************************************************/
470 plperl_get_keys(HV *hv)
480 while ((val = hv_iternextsv(hv, (char **) &key, &klen)))
481 av_push(ret, newSVpv(key, 0));
487 /**********************************************************************
488 * extract a given key (by index) from a list of keys
489 **********************************************************************/
491 plperl_get_key(AV *keys, int index)
496 len = av_len(keys) + 1;
498 svp = av_fetch(keys, index, FALSE);
501 return SvPV(*svp, PL_na);
504 /**********************************************************************
505 * extract a value for a given key from a hash
507 * return NULL on error or if we got an undef
509 **********************************************************************/
511 plperl_get_elem(HV *hash, char *key)
513 SV **svp = hv_fetch(hash, key, strlen(key), FALSE);
515 elog(ERROR, "plperl: key \"%s\" not found", key);
516 return SvTYPE(*svp) == SVt_NULL ? NULL : SvPV(*svp, PL_na);
519 /**********************************************************************
520 * set up the new tuple returned from a trigger
521 **********************************************************************/
523 plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup, Oid fn_oid)
535 int *volatile modattrs = NULL;
536 Datum *volatile modvalues = NULL;
537 char *volatile modnulls = NULL;
541 tupdesc = tdata->tg_relation->rd_att;
543 svp = hv_fetch(hvTD, "new", 3, FALSE);
544 hvNew = (HV *) SvRV(*svp);
546 if (SvTYPE(hvNew) != SVt_PVHV)
547 elog(ERROR, "plperl: $_TD->{new} is not a hash");
549 plkeys = plperl_get_keys(hvNew);
550 natts = av_len(plkeys) + 1;
551 if (natts != tupdesc->natts)
552 elog(ERROR, "plperl: $_TD->{new} has an incorrect number of keys");
554 modattrs = palloc0(natts * sizeof(int));
555 modvalues = palloc0(natts * sizeof(Datum));
556 modnulls = palloc0(natts * sizeof(char));
558 for (i = 0; i < natts; i++)
564 platt = plperl_get_key(plkeys, i);
566 attn = modattrs[i] = SPI_fnumber(tupdesc, platt);
568 if (attn == SPI_ERROR_NOATTRIBUTE)
569 elog(ERROR, "plperl: invalid attribute \"%s\" in tuple", platt);
572 plval = plperl_get_elem(hvNew, platt);
574 typetup = SearchSysCache(TYPEOID, ObjectIdGetDatum(tupdesc->attrs[atti]->atttypid), 0, 0, 0);
575 typinput = ((Form_pg_type) GETSTRUCT(typetup))->typinput;
576 typelem = ((Form_pg_type) GETSTRUCT(typetup))->typelem;
577 ReleaseSysCache(typetup);
578 fmgr_info(typinput, &finfo);
582 modvalues[i] = FunctionCall3(&finfo,
583 CStringGetDatum(plval),
584 ObjectIdGetDatum(typelem),
585 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
590 modvalues[i] = (Datum) 0;
594 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts, modattrs, modvalues, modnulls);
600 elog(ERROR, "plperl: SPI_modifytuple failed -- error: %d", SPI_result);
605 /**********************************************************************
606 * plperl_call_handler - This is the only visible function
607 * of the PL interpreter. The PostgreSQL
608 * function manager and trigger manager
609 * call this function for execution of
611 **********************************************************************/
612 PG_FUNCTION_INFO_V1(plperl_call_handler);
614 /* keep non-static */
616 plperl_call_handler(PG_FUNCTION_ARGS)
619 plperl_proc_desc *save_prodesc;
622 * Initialize interpreter if first time through
627 * Ensure that static pointers are saved/restored properly
629 save_prodesc = plperl_current_prodesc;
633 /************************************************************
634 * Connect to SPI manager
635 ************************************************************/
636 if (SPI_connect() != SPI_OK_CONNECT)
637 elog(ERROR, "could not connect to SPI manager");
639 /************************************************************
640 * Determine if called as function or trigger and
641 * call appropriate subhandler
642 ************************************************************/
643 if (CALLED_AS_TRIGGER(fcinfo))
644 retval = PointerGetDatum(plperl_trigger_handler(fcinfo));
646 retval = plperl_func_handler(fcinfo);
650 plperl_current_prodesc = save_prodesc;
655 plperl_current_prodesc = save_prodesc;
661 /**********************************************************************
662 * plperl_create_sub() - calls the perl interpreter to
663 * create the anonymous subroutine whose text is in the SV.
664 * Returns the SV containing the RV to the closure.
665 **********************************************************************/
667 plperl_create_sub(char *s, bool trusted)
673 if (trusted && !plperl_safe_init_done)
682 XPUSHs(sv_2mortal(newSVpv("my $_TD=$_[0]; shift;", 0)));
683 XPUSHs(sv_2mortal(newSVpv(s, 0)));
687 * G_KEEPERR seems to be needed here, else we don't recognize compile
688 * errors properly. Perhaps it's because there's another level of
689 * eval inside mksafefunc?
691 count = perl_call_pv((trusted ? "mksafefunc" : "mkunsafefunc"),
692 G_SCALAR | G_EVAL | G_KEEPERR);
700 elog(ERROR, "didn't get a return item from mksafefunc");
709 elog(ERROR, "creation of function failed: %s",
710 strip_trailing_ws(SvPV(ERRSV, PL_na)));
714 * need to make a deep copy of the return. it comes off the stack as a
717 subref = newSVsv(POPs);
726 * subref is our responsibility because it is not mortal
728 SvREFCNT_dec(subref);
729 elog(ERROR, "didn't get a code ref");
739 /**********************************************************************
740 * plperl_init_shared_libs() -
742 * We cannot use the DynaLoader directly to get at the Opcode
743 * module (used by Safe.pm). So, we link Opcode into ourselves
744 * and do the initialization behind perl's back.
746 **********************************************************************/
748 EXTERN_C void boot_DynaLoader(pTHX_ CV *cv);
749 EXTERN_C void boot_SPI(pTHX_ CV *cv);
752 plperl_init_shared_libs(pTHX)
754 char *file = __FILE__;
756 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
757 newXS("SPI::bootstrap", boot_SPI, file);
760 /**********************************************************************
761 * plperl_call_perl_func() - calls a perl function through the RV
762 * stored in the prodesc structure. massages the input parms properly
763 **********************************************************************/
765 plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
776 XPUSHs(sv_2mortal(newSVpv("undef", 0)));
777 for (i = 0; i < desc->nargs; i++)
779 if (fcinfo->argnull[i])
780 XPUSHs(&PL_sv_undef);
781 else if (desc->arg_is_rowtype[i])
787 HeapTupleData tmptup;
790 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
791 /* Extract rowtype info and find a tupdesc */
792 tupType = HeapTupleHeaderGetTypeId(td);
793 tupTypmod = HeapTupleHeaderGetTypMod(td);
794 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
795 /* Build a temporary HeapTuple control structure */
796 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
799 /* plperl_build_tuple_argument better return a mortal SV */
800 hashref = plperl_build_tuple_argument(&tmptup, tupdesc);
807 tmp = DatumGetCString(FunctionCall3(&(desc->arg_out_func[i]),
809 ObjectIdGetDatum(desc->arg_typioparam[i]),
811 XPUSHs(sv_2mortal(newSVpv(tmp, 0)));
817 /* Do NOT use G_KEEPERR here */
818 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
827 elog(ERROR, "didn't get a return item from function");
836 elog(ERROR, "error from function: %s",
837 strip_trailing_ws(SvPV(ERRSV, PL_na)));
840 retval = newSVsv(POPs);
849 /**********************************************************************
850 * plperl_call_perl_trigger_func() - calls a perl function affected by trigger
851 * through the RV stored in the prodesc structure. massages the input parms properly
852 **********************************************************************/
854 plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo, SV *td)
867 tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
868 for (i = 0; i < tg_trigger->tgnargs; i++)
869 XPUSHs(sv_2mortal(newSVpv(tg_trigger->tgargs[i], 0)));
872 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL | G_KEEPERR);
881 elog(ERROR, "didn't get a return item from trigger function");
890 elog(ERROR, "error from trigger function: %s",
891 strip_trailing_ws(SvPV(ERRSV, PL_na)));
894 retval = newSVsv(POPs);
903 /**********************************************************************
904 * plperl_func_handler() - Handler for regular function calls
905 **********************************************************************/
907 plperl_func_handler(PG_FUNCTION_ARGS)
909 plperl_proc_desc *prodesc;
913 /* Find or compile the function */
914 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false);
916 plperl_current_prodesc = prodesc;
918 /************************************************************
919 * Call the Perl function if not returning set
920 ************************************************************/
921 if (!prodesc->fn_retisset)
922 perlret = plperl_call_perl_func(prodesc, fcinfo);
925 if (SRF_IS_FIRSTCALL()) /* call function only once */
926 srf_perlret = plperl_call_perl_func(prodesc, fcinfo);
927 perlret = srf_perlret;
930 if (prodesc->fn_retisset && SRF_IS_FIRSTCALL())
932 if (prodesc->fn_retistuple)
933 g_column_keys = newAV();
934 if (SvTYPE(perlret) != SVt_RV)
935 elog(ERROR, "plperl: set-returning function must return reference");
938 /************************************************************
939 * Disconnect from SPI manager and then create the return
940 * values datum (if the input function does a palloc for it
941 * this must not be allocated in the SPI memory context
942 * because SPI_finish would free it).
943 ************************************************************/
944 if (SPI_finish() != SPI_OK_FINISH)
945 elog(ERROR, "SPI_finish() failed");
947 if (!(perlret && SvOK(perlret) && SvTYPE(perlret) != SVt_NULL))
949 /* return NULL if Perl code returned undef */
950 fcinfo->isnull = true;
953 if (prodesc->fn_retisset && !(perlret && SvTYPE(SvRV(perlret)) == SVt_PVAV))
954 elog(ERROR, "plperl: set-returning function must return reference to array");
956 if (prodesc->fn_retistuple && perlret && SvTYPE(perlret) != SVt_RV)
957 elog(ERROR, "plperl: composite-returning function must return a reference");
959 if (prodesc->fn_retisset && !fcinfo->resultinfo)
961 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
962 errmsg("set-valued function called in context that cannot accept a set")));
964 if (prodesc->fn_retistuple && fcinfo->resultinfo) /* set of tuples */
967 * This branch will be taken when the function call
968 * appears in a context that can return a set of tuples,
969 * even if it only actually returns a single tuple
970 * (e.g. select a from foo() where foo returns a singleton
971 * of some composite type with member a). In this case, the
972 * return value will be a hashref. If a rowset is returned
973 * it will be an arrayref whose members will be hashrefs.
975 * Care is taken in the code only to refer to the appropriate
976 * one of ret_hv and ret_av, only one of which is therefore
977 * valid for any given call.
979 * XXX This code is in dire need of cleanup.
985 FuncCallContext *funcctx;
989 AttInMetadata *attinmeta;
991 char **values = NULL;
992 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
994 isset = plperl_is_set(perlret);
996 if (SvTYPE(SvRV(perlret)) == SVt_PVHV)
997 ret_hv = (HV *) SvRV(perlret);
999 ret_av = (AV *) SvRV(perlret);
1001 if (SRF_IS_FIRSTCALL())
1003 MemoryContext oldcontext;
1006 funcctx = SRF_FIRSTCALL_INIT();
1008 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1010 if (SvTYPE(SvRV(perlret)) == SVt_PVHV)
1013 funcctx->max_calls = hv_iterinit(ret_hv);
1015 funcctx->max_calls = 1;
1020 funcctx->max_calls = av_len(ret_av) + 1;
1022 funcctx->max_calls = 1;
1025 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1027 g_attr_num = tupdesc->natts;
1029 for (i = 0; i < tupdesc->natts; i++)
1030 av_store(g_column_keys, i + 1,
1031 newSVpv(SPI_fname(tupdesc, i+1), 0));
1033 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1034 funcctx->attinmeta = attinmeta;
1035 MemoryContextSwitchTo(oldcontext);
1038 funcctx = SRF_PERCALL_SETUP();
1039 call_cntr = funcctx->call_cntr;
1040 max_calls = funcctx->max_calls;
1041 attinmeta = funcctx->attinmeta;
1042 tupdesc = attinmeta->tupdesc;
1044 if (call_cntr < max_calls)
1057 svp = av_fetch(ret_av, call_cntr, FALSE);
1059 row_hv = (HV *) SvRV(*svp);
1061 values = (char **) palloc(g_attr_num * sizeof(char *));
1063 for (i = 0; i < g_attr_num; i++)
1065 column_key = plperl_get_key(g_column_keys, i + 1);
1066 elem = plperl_get_elem(row_hv, column_key);
1077 values = (char **) palloc(g_attr_num * sizeof(char *));
1078 for (i = 0; i < g_attr_num; i++)
1080 column_key = SPI_fname(tupdesc, i + 1);
1081 elem = plperl_get_elem(ret_hv, column_key);
1088 tuple = BuildTupleFromCStrings(attinmeta, values);
1089 result = HeapTupleGetDatum(tuple);
1090 SRF_RETURN_NEXT(funcctx, result);
1094 SvREFCNT_dec(perlret);
1095 SRF_RETURN_DONE(funcctx);
1098 else if (prodesc->fn_retisset) /* set of non-tuples */
1100 FuncCallContext *funcctx;
1102 if (SRF_IS_FIRSTCALL())
1104 MemoryContext oldcontext;
1106 funcctx = SRF_FIRSTCALL_INIT();
1107 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1109 funcctx->max_calls = av_len((AV *) SvRV(perlret)) + 1;
1112 funcctx = SRF_PERCALL_SETUP();
1114 if (funcctx->call_cntr < funcctx->max_calls)
1120 array = (AV *) SvRV(perlret);
1121 svp = av_fetch(array, funcctx->call_cntr, FALSE);
1123 if (SvTYPE(*svp) != SVt_NULL)
1125 fcinfo->isnull = false;
1126 result = FunctionCall3(&prodesc->result_in_func,
1127 PointerGetDatum(SvPV(*svp, PL_na)),
1128 ObjectIdGetDatum(prodesc->result_typioparam),
1133 fcinfo->isnull = true;
1136 SRF_RETURN_NEXT(funcctx, result);
1141 SvREFCNT_dec(perlret);
1142 SRF_RETURN_DONE(funcctx);
1145 else if (!fcinfo->isnull) /* non-null singleton */
1147 if (prodesc->fn_retistuple) /* singleton perl hash to Datum */
1149 TupleDesc td = lookup_rowtype_tupdesc(prodesc->ret_oid, (int32) -1);
1150 HV *perlhash = (HV *) SvRV(perlret);
1155 AttInMetadata *attinmeta;
1160 (errcode(ERRCODE_SYNTAX_ERROR),
1161 errmsg("no TupleDesc info available")));
1163 values = (char **) palloc(td->natts * sizeof(char *));
1164 for (i = 0; i < td->natts; i++)
1167 key = SPI_fname(td, i + 1);
1168 val = plperl_get_elem(perlhash, key);
1174 attinmeta = TupleDescGetAttInMetadata(td);
1175 tup = BuildTupleFromCStrings(attinmeta, values);
1176 retval = HeapTupleGetDatum(tup);
1179 /* perl string to Datum */
1180 retval = FunctionCall3(&prodesc->result_in_func,
1181 PointerGetDatum(SvPV(perlret, PL_na)),
1182 ObjectIdGetDatum(prodesc->result_typioparam),
1185 else /* null singleton */
1188 SvREFCNT_dec(perlret);
1192 /**********************************************************************
1193 * plperl_trigger_handler() - Handler for trigger function calls
1194 **********************************************************************/
1196 plperl_trigger_handler(PG_FUNCTION_ARGS)
1198 plperl_proc_desc *prodesc;
1205 /* Find or compile the function */
1206 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true);
1208 plperl_current_prodesc = prodesc;
1210 /************************************************************
1211 * Call the Perl function
1212 ************************************************************/
1215 * call perl trigger function and build TD hash
1217 svTD = plperl_trigger_build_args(fcinfo);
1218 perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
1220 hvTD = (HV *) SvRV(svTD); /* convert SV TD structure to Perl Hash
1223 tmp = SvPV(perlret, PL_na);
1225 /************************************************************
1226 * Disconnect from SPI manager and then create the return
1227 * values datum (if the input function does a palloc for it
1228 * this must not be allocated in the SPI memory context
1229 * because SPI_finish would free it).
1230 ************************************************************/
1231 if (SPI_finish() != SPI_OK_FINISH)
1232 elog(ERROR, "plperl: SPI_finish() failed");
1234 if (!(perlret && SvOK(perlret)))
1236 TriggerData *trigdata = ((TriggerData *) fcinfo->context);
1238 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1239 retval = (Datum) trigdata->tg_trigtuple;
1240 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1241 retval = (Datum) trigdata->tg_newtuple;
1242 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
1243 retval = (Datum) trigdata->tg_trigtuple;
1245 retval = (Datum) 0; /* can this happen? */
1249 if (!fcinfo->isnull)
1254 if (strcasecmp(tmp, "SKIP") == 0)
1256 else if (strcasecmp(tmp, "MODIFY") == 0)
1258 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1260 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1261 trv = plperl_modify_tuple(hvTD, trigdata, trigdata->tg_trigtuple, fcinfo->flinfo->fn_oid);
1262 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1263 trv = plperl_modify_tuple(hvTD, trigdata, trigdata->tg_newtuple, fcinfo->flinfo->fn_oid);
1267 elog(WARNING, "plperl: Ignoring modified tuple in DELETE trigger");
1270 else if (strcasecmp(tmp, "OK"))
1273 elog(ERROR, "plperl: Expected return to be undef, 'SKIP' or 'MODIFY'");
1278 elog(ERROR, "plperl: Expected return to be undef, 'SKIP' or 'MODIFY'");
1280 retval = PointerGetDatum(trv);
1286 SvREFCNT_dec(perlret);
1288 fcinfo->isnull = false;
1292 /**********************************************************************
1293 * compile_plperl_function - compile (or hopefully just look up) function
1294 **********************************************************************/
1295 static plperl_proc_desc *
1296 compile_plperl_function(Oid fn_oid, bool is_trigger)
1299 Form_pg_proc procStruct;
1300 char internal_proname[64];
1302 plperl_proc_desc *prodesc = NULL;
1306 /* We'll need the pg_proc tuple in any case... */
1307 procTup = SearchSysCache(PROCOID,
1308 ObjectIdGetDatum(fn_oid),
1310 if (!HeapTupleIsValid(procTup))
1311 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1312 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1314 /************************************************************
1315 * Build our internal proc name from the functions Oid
1316 ************************************************************/
1318 sprintf(internal_proname, "__PLPerl_proc_%u", fn_oid);
1320 sprintf(internal_proname, "__PLPerl_proc_%u_trigger", fn_oid);
1322 proname_len = strlen(internal_proname);
1324 /************************************************************
1325 * Lookup the internal proc name in the hashtable
1326 ************************************************************/
1327 svp = hv_fetch(plperl_proc_hash, internal_proname, proname_len, FALSE);
1332 prodesc = (plperl_proc_desc *) SvIV(*svp);
1334 /************************************************************
1335 * If it's present, must check whether it's still up to date.
1336 * This is needed because CREATE OR REPLACE FUNCTION can modify the
1337 * function's pg_proc entry without changing its OID.
1338 ************************************************************/
1339 uptodate = (prodesc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&
1340 prodesc->fn_cmin == HeapTupleHeaderGetCmin(procTup->t_data));
1344 /* need we delete old entry? */
1349 /************************************************************
1350 * If we haven't found it in the hashtable, we analyze
1351 * the functions arguments and returntype and store
1352 * the in-/out-functions in the prodesc block and create
1353 * a new hashtable entry for it.
1355 * Then we load the procedure into the Perl interpreter.
1356 ************************************************************/
1357 if (prodesc == NULL)
1361 Form_pg_language langStruct;
1362 Form_pg_type typeStruct;
1367 /************************************************************
1368 * Allocate a new procedure description block
1369 ************************************************************/
1370 prodesc = (plperl_proc_desc *) malloc(sizeof(plperl_proc_desc));
1371 if (prodesc == NULL)
1373 (errcode(ERRCODE_OUT_OF_MEMORY),
1374 errmsg("out of memory")));
1375 MemSet(prodesc, 0, sizeof(plperl_proc_desc));
1376 prodesc->proname = strdup(internal_proname);
1377 prodesc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1378 prodesc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1380 /* Remember if function is STABLE/IMMUTABLE */
1381 prodesc->fn_readonly =
1382 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1384 /************************************************************
1385 * Lookup the pg_language tuple by Oid
1386 ************************************************************/
1387 langTup = SearchSysCache(LANGOID,
1388 ObjectIdGetDatum(procStruct->prolang),
1390 if (!HeapTupleIsValid(langTup))
1392 free(prodesc->proname);
1394 elog(ERROR, "cache lookup failed for language %u",
1395 procStruct->prolang);
1397 langStruct = (Form_pg_language) GETSTRUCT(langTup);
1398 prodesc->lanpltrusted = langStruct->lanpltrusted;
1399 ReleaseSysCache(langTup);
1401 /************************************************************
1402 * Get the required information for input conversion of the
1404 ************************************************************/
1407 typeTup = SearchSysCache(TYPEOID,
1408 ObjectIdGetDatum(procStruct->prorettype),
1410 if (!HeapTupleIsValid(typeTup))
1412 free(prodesc->proname);
1414 elog(ERROR, "cache lookup failed for type %u",
1415 procStruct->prorettype);
1417 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1419 /* Disallow pseudotype result, except VOID or RECORD */
1420 if (typeStruct->typtype == 'p')
1422 if (procStruct->prorettype == VOIDOID ||
1423 procStruct->prorettype == RECORDOID)
1425 else if (procStruct->prorettype == TRIGGEROID)
1427 free(prodesc->proname);
1430 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1431 errmsg("trigger functions may only be called as triggers")));
1435 free(prodesc->proname);
1438 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1439 errmsg("plperl functions cannot return type %s",
1440 format_type_be(procStruct->prorettype))));
1444 prodesc->fn_retisset = procStruct->proretset; /* true, if function
1447 if (typeStruct->typtype == 'c' || procStruct->prorettype == RECORDOID)
1449 prodesc->fn_retistuple = true;
1451 procStruct->prorettype == RECORDOID ?
1452 typeStruct->typrelid :
1453 procStruct->prorettype;
1456 perm_fmgr_info(typeStruct->typinput, &(prodesc->result_in_func));
1457 prodesc->result_typioparam = getTypeIOParam(typeTup);
1459 ReleaseSysCache(typeTup);
1462 /************************************************************
1463 * Get the required information for output conversion
1464 * of all procedure arguments
1465 ************************************************************/
1468 prodesc->nargs = procStruct->pronargs;
1469 for (i = 0; i < prodesc->nargs; i++)
1471 typeTup = SearchSysCache(TYPEOID,
1472 ObjectIdGetDatum(procStruct->proargtypes[i]),
1474 if (!HeapTupleIsValid(typeTup))
1476 free(prodesc->proname);
1478 elog(ERROR, "cache lookup failed for type %u",
1479 procStruct->proargtypes[i]);
1481 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1483 /* Disallow pseudotype argument */
1484 if (typeStruct->typtype == 'p')
1486 free(prodesc->proname);
1489 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1490 errmsg("plperl functions cannot take type %s",
1491 format_type_be(procStruct->proargtypes[i]))));
1494 if (typeStruct->typtype == 'c')
1495 prodesc->arg_is_rowtype[i] = true;
1498 prodesc->arg_is_rowtype[i] = false;
1499 perm_fmgr_info(typeStruct->typoutput,
1500 &(prodesc->arg_out_func[i]));
1501 prodesc->arg_typioparam[i] = getTypeIOParam(typeTup);
1504 ReleaseSysCache(typeTup);
1508 /************************************************************
1509 * create the text of the anonymous subroutine.
1510 * we do not use a named subroutine so that we can call directly
1511 * through the reference.
1513 ************************************************************/
1514 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1515 Anum_pg_proc_prosrc, &isnull);
1517 elog(ERROR, "null prosrc");
1518 proc_source = DatumGetCString(DirectFunctionCall1(textout,
1521 /************************************************************
1522 * Create the procedure in the interpreter
1523 ************************************************************/
1524 prodesc->reference = plperl_create_sub(proc_source, prodesc->lanpltrusted);
1526 if (!prodesc->reference)
1528 free(prodesc->proname);
1530 elog(ERROR, "could not create internal procedure \"%s\"",
1534 /************************************************************
1535 * Add the proc description block to the hashtable
1536 ************************************************************/
1537 hv_store(plperl_proc_hash, internal_proname, proname_len,
1538 newSViv((IV) prodesc), 0);
1541 ReleaseSysCache(procTup);
1547 /**********************************************************************
1548 * plperl_build_tuple_argument() - Build a string for a ref to a hash
1549 * from all attributes of a given tuple
1550 **********************************************************************/
1552 plperl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc)
1567 for (i = 0; i < tupdesc->natts; i++)
1569 if (tupdesc->attrs[i]->attisdropped)
1572 attname = tupdesc->attrs[i]->attname.data;
1573 namelen = strlen(attname);
1574 attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1577 /* Store (attname => undef) and move on. */
1578 hv_store(hv, attname, namelen, newSV(0), 0);
1582 /************************************************************
1583 * Lookup the attribute type in the syscache
1584 * for the output function
1585 ************************************************************/
1586 typeTup = SearchSysCache(TYPEOID,
1587 ObjectIdGetDatum(tupdesc->attrs[i]->atttypid),
1589 if (!HeapTupleIsValid(typeTup))
1590 elog(ERROR, "cache lookup failed for type %u",
1591 tupdesc->attrs[i]->atttypid);
1593 typoutput = ((Form_pg_type) GETSTRUCT(typeTup))->typoutput;
1594 typioparam = getTypeIOParam(typeTup);
1595 ReleaseSysCache(typeTup);
1597 /************************************************************
1598 * Append the attribute name and the value to the list.
1599 ************************************************************/
1600 outputstr = DatumGetCString(OidFunctionCall3(typoutput,
1602 ObjectIdGetDatum(typioparam),
1603 Int32GetDatum(tupdesc->attrs[i]->atttypmod)));
1605 hv_store(hv, attname, namelen, newSVpv(outputstr, 0), 0);
1608 return sv_2mortal(newRV((SV *)hv));
1613 * Implementation of spi_exec_query() Perl function
1616 plperl_spi_exec(char *query, int limit)
1621 * Execute the query inside a sub-transaction, so we can cope with
1624 MemoryContext oldcontext = CurrentMemoryContext;
1625 ResourceOwner oldowner = CurrentResourceOwner;
1627 BeginInternalSubTransaction(NULL);
1628 /* Want to run inside function's memory context */
1629 MemoryContextSwitchTo(oldcontext);
1635 spi_rv = SPI_execute(query, plperl_current_prodesc->fn_readonly,
1637 ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
1640 /* Commit the inner transaction, return to outer xact context */
1641 ReleaseCurrentSubTransaction();
1642 MemoryContextSwitchTo(oldcontext);
1643 CurrentResourceOwner = oldowner;
1645 * AtEOSubXact_SPI() should not have popped any SPI context,
1646 * but just in case it did, make sure we remain connected.
1648 SPI_restore_connection();
1654 /* Save error info */
1655 MemoryContextSwitchTo(oldcontext);
1656 edata = CopyErrorData();
1659 /* Abort the inner transaction */
1660 RollbackAndReleaseCurrentSubTransaction();
1661 MemoryContextSwitchTo(oldcontext);
1662 CurrentResourceOwner = oldowner;
1665 * If AtEOSubXact_SPI() popped any SPI context of the subxact,
1666 * it will have left us in a disconnected state. We need this
1667 * hack to return to connected state.
1669 SPI_restore_connection();
1671 /* Punt the error to Perl */
1672 croak("%s", edata->message);
1674 /* Can't get here, but keep compiler quiet */
1683 plperl_spi_execute_fetch_result(SPITupleTable *tuptable, int processed,
1690 hv_store(result, "status", strlen("status"),
1691 newSVpv((char *) SPI_result_code_string(status), 0), 0);
1692 hv_store(result, "processed", strlen("processed"),
1693 newSViv(processed), 0);
1695 if (status == SPI_OK_SELECT)
1702 for (i = 0; i < processed; i++)
1704 row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc);
1705 av_push(rows, newRV_noinc((SV *)row));
1707 hv_store(result, "rows", strlen("rows"),
1708 newRV_noinc((SV *) rows), 0);
1711 SPI_freetuptable(tuptable);