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.56 2004/11/16 22:05:22 tgl Exp $
38 **********************************************************************/
46 /* postgreSQL stuff */
47 #include "access/heapam.h"
48 #include "catalog/pg_language.h"
49 #include "catalog/pg_proc.h"
50 #include "catalog/pg_type.h"
51 #include "funcapi.h" /* need for SRF support */
52 #include "commands/trigger.h"
53 #include "executor/spi.h"
55 #include "tcop/tcopprot.h"
56 #include "utils/lsyscache.h"
57 #include "utils/syscache.h"
58 #include "utils/typcache.h"
66 /* just in case these symbols aren't provided */
73 /**********************************************************************
74 * The information we cache about loaded procedures
75 **********************************************************************/
76 typedef struct plperl_proc_desc
79 TransactionId fn_xmin;
83 bool fn_retistuple; /* true, if function returns tuple */
84 bool fn_retisset; /* true, if function returns set */
85 Oid ret_oid; /* Oid of returning type */
86 FmgrInfo result_in_func;
87 Oid result_typioparam;
89 FmgrInfo arg_out_func[FUNC_MAX_ARGS];
90 Oid arg_typioparam[FUNC_MAX_ARGS];
91 bool arg_is_rowtype[FUNC_MAX_ARGS];
96 /**********************************************************************
98 **********************************************************************/
99 static int plperl_firstcall = 1;
100 static bool plperl_safe_init_done = false;
101 static PerlInterpreter *plperl_interp = NULL;
102 static HV *plperl_proc_hash = NULL;
103 static AV *g_column_keys = NULL;
104 static SV *srf_perlret = NULL; /* keep returned value */
105 static int g_attr_num = 0;
107 /* this is saved and restored by plperl_call_handler */
108 static plperl_proc_desc *plperl_current_prodesc = NULL;
110 /**********************************************************************
111 * Forward declarations
112 **********************************************************************/
113 static void plperl_init_all(void);
114 static void plperl_init_interp(void);
116 Datum plperl_call_handler(PG_FUNCTION_ARGS);
117 void plperl_init(void);
119 static Datum plperl_func_handler(PG_FUNCTION_ARGS);
121 static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
122 static plperl_proc_desc *compile_plperl_function(Oid fn_oid, bool is_trigger);
124 static SV *plperl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc);
125 static void plperl_init_shared_libs(pTHX);
126 static HV *plperl_spi_execute_fetch_result(SPITupleTable *, int, int);
130 * This routine is a crock, and so is everyplace that calls it. The problem
131 * is that the cached form of plperl functions/queries is allocated permanently
132 * (mostly via malloc()) and never released until backend exit. Subsidiary
133 * data structures such as fmgr info records therefore must live forever
134 * as well. A better implementation would store all this stuff in a per-
135 * function memory context that could be reclaimed at need. In the meantime,
136 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
137 * it might allocate, and whatever the eventual function might allocate using
138 * fn_mcxt, will live forever too.
141 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
143 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
146 /**********************************************************************
147 * plperl_init() - Initialize everything that can be
148 * safely initialized during postmaster
151 * DO NOT make this static --- it has to be callable by preload
152 **********************************************************************/
156 /************************************************************
157 * Do initialization only once
158 ************************************************************/
159 if (!plperl_firstcall)
162 /************************************************************
163 * Free the proc hash table
164 ************************************************************/
165 if (plperl_proc_hash != NULL)
167 hv_undef(plperl_proc_hash);
168 SvREFCNT_dec((SV *) plperl_proc_hash);
169 plperl_proc_hash = NULL;
172 /************************************************************
173 * Destroy the existing Perl interpreter
174 ************************************************************/
175 if (plperl_interp != NULL)
177 perl_destruct(plperl_interp);
178 perl_free(plperl_interp);
179 plperl_interp = NULL;
182 /************************************************************
183 * Now recreate a new Perl interpreter
184 ************************************************************/
185 plperl_init_interp();
187 plperl_firstcall = 0;
190 /**********************************************************************
191 * plperl_init_all() - Initialize all
192 **********************************************************************/
194 plperl_init_all(void)
197 /************************************************************
198 * Execute postmaster-startup safe initialization
199 ************************************************************/
200 if (plperl_firstcall)
203 /************************************************************
204 * Any other initialization that must be done each time a new
205 * backend starts -- currently none
206 ************************************************************/
211 /**********************************************************************
212 * plperl_init_interp() - Create the Perl interpreter
213 **********************************************************************/
215 plperl_init_interp(void)
218 char *embedding[3] = {
222 * no commas between the next lines please. They are supposed to
225 "SPI::bootstrap(); use vars qw(%_SHARED);"
226 "sub ::mkunsafefunc {return eval(qq[ sub { $_[0] $_[1] } ]); }"
229 plperl_interp = perl_alloc();
231 elog(ERROR, "could not allocate perl interpreter");
233 perl_construct(plperl_interp);
234 perl_parse(plperl_interp, plperl_init_shared_libs, 3, embedding, NULL);
235 perl_run(plperl_interp);
237 /************************************************************
238 * Initialize the proc and query hash tables
239 ************************************************************/
240 plperl_proc_hash = newHV();
246 plperl_safe_init(void)
248 static char *safe_module =
249 "require Safe; $Safe::VERSION";
251 static char *safe_ok =
252 "use vars qw($PLContainer); $PLContainer = new Safe('PLPerl');"
253 "$PLContainer->permit_only(':default');"
254 "$PLContainer->permit(qw[:base_math !:base_io sort time]);"
255 "$PLContainer->share(qw[&elog &spi_exec_query &DEBUG &LOG "
256 "&INFO &NOTICE &WARNING &ERROR %SHARED ]);"
257 "sub ::mksafefunc { return $PLContainer->reval(qq[sub { $_[0] $_[1]}]); }"
260 static char *safe_bad =
261 "use vars qw($PLContainer); $PLContainer = new Safe('PLPerl');"
262 "$PLContainer->permit_only(':default');"
263 "$PLContainer->share(qw[&elog &ERROR ]);"
264 "sub ::mksafefunc { return $PLContainer->reval(qq[sub { "
265 "elog(ERROR,'trusted perl functions disabled - "
266 "please upgrade perl Safe module to at least 2.09');}]); }"
273 res = eval_pv(safe_module, FALSE); /* TRUE = croak if failure */
275 safe_version = SvNV(res);
277 eval_pv((safe_version < 2.09 ? safe_bad : safe_ok), FALSE);
279 plperl_safe_init_done = true;
284 plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
288 for (i = 0; i < tupdesc->natts; i++)
292 char *key = SPI_fname(tupdesc, i+1);
293 char *val = SPI_getvalue(tuple, tupdesc, i + 1);
296 value = newSVpv(val, 0);
300 hv_store(hv, key, strlen(key), value, 0);
306 /**********************************************************************
307 * set up arguments for a trigger call
308 **********************************************************************/
310 plperl_trigger_build_args(FunctionCallInfo fcinfo)
323 tdata = (TriggerData *) fcinfo->context;
324 tupdesc = tdata->tg_relation->rd_att;
326 relid = DatumGetCString(
328 oidout, ObjectIdGetDatum(tdata->tg_relation->rd_id)
332 hv_store(hv, "name", 4, newSVpv(tdata->tg_trigger->tgname, 0), 0);
333 hv_store(hv, "relid", 5, newSVpv(relid, 0), 0);
335 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
338 hv_store(hv, "new", 3,
339 newRV((SV *)plperl_hash_from_tuple(tdata->tg_trigtuple,
343 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
346 hv_store(hv, "old", 3,
347 newRV((SV *)plperl_hash_from_tuple(tdata->tg_trigtuple,
351 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
354 hv_store(hv, "old", 3,
355 newRV((SV *)plperl_hash_from_tuple(tdata->tg_trigtuple,
358 hv_store(hv, "new", 3,
359 newRV((SV *)plperl_hash_from_tuple(tdata->tg_newtuple,
367 hv_store(hv, "event", 5, newSVpv(event, 0), 0);
368 hv_store(hv, "argc", 4, newSViv(tdata->tg_trigger->tgnargs), 0);
370 if (tdata->tg_trigger->tgnargs != 0)
373 for (i=0; i < tdata->tg_trigger->tgnargs; i++)
374 av_push(av, newSVpv(tdata->tg_trigger->tgargs[i], 0));
375 hv_store(hv, "args", 4, newRV((SV *)av), 0);
378 hv_store(hv, "relname", 7,
379 newSVpv(SPI_getrelname(tdata->tg_relation), 0), 0);
381 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
383 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
387 hv_store(hv, "when", 4, newSVpv(when, 0), 0);
389 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
391 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
395 hv_store(hv, "level", 5, newSVpv(level, 0), 0);
397 return newRV((SV*)hv);
401 /**********************************************************************
402 * check return value from plperl function
403 **********************************************************************/
405 plperl_is_set(SV *sv)
414 if (SvTYPE(sv) != SVt_RV)
417 if (SvTYPE(SvRV(sv)) == SVt_PVHV)
420 if (SvTYPE(SvRV(sv)) == SVt_PVAV)
422 input_av = (AV *) SvRV(sv);
423 len = av_len(input_av) + 1;
425 for (i = 0; i < len; i++)
427 val = av_fetch(input_av, i, FALSE);
428 if (SvTYPE(*val) == SVt_RV)
442 elog(ERROR, "plperl: check your return value structure");
444 elog(ERROR, "plperl: check your return value structure");
446 return 0; /* for compiler */
449 /**********************************************************************
450 * extract a list of keys from a hash
451 **********************************************************************/
453 plperl_get_keys(HV *hv)
463 while ((val = hv_iternextsv(hv, (char **) &key, &klen)))
464 av_push(ret, newSVpv(key, 0));
470 /**********************************************************************
471 * extract a given key (by index) from a list of keys
472 **********************************************************************/
474 plperl_get_key(AV *keys, int index)
479 len = av_len(keys) + 1;
481 svp = av_fetch(keys, index, FALSE);
484 return SvPV(*svp, PL_na);
487 /**********************************************************************
488 * extract a value for a given key from a hash
490 * return NULL on error or if we got an undef
492 **********************************************************************/
494 plperl_get_elem(HV *hash, char *key)
496 SV **svp = hv_fetch(hash, key, strlen(key), FALSE);
499 elog(ERROR, "plperl: key '%s' not found", key);
502 return SvTYPE(*svp) == SVt_NULL ? NULL : SvPV(*svp, PL_na);
505 /**********************************************************************
506 * set up the new tuple returned from a trigger
507 **********************************************************************/
509 plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup, Oid fn_oid)
521 int *volatile modattrs = NULL;
522 Datum *volatile modvalues = NULL;
523 char *volatile modnulls = NULL;
527 tupdesc = tdata->tg_relation->rd_att;
529 svp = hv_fetch(hvTD, "new", 3, FALSE);
530 hvNew = (HV *) SvRV(*svp);
532 if (SvTYPE(hvNew) != SVt_PVHV)
533 elog(ERROR, "plperl: $_TD->{new} is not a hash");
535 plkeys = plperl_get_keys(hvNew);
536 natts = av_len(plkeys) + 1;
537 if (natts != tupdesc->natts)
538 elog(ERROR, "plperl: $_TD->{new} has an incorrect number of keys.");
540 modattrs = palloc0(natts * sizeof(int));
541 modvalues = palloc0(natts * sizeof(Datum));
542 modnulls = palloc0(natts * sizeof(char));
544 for (i = 0; i < natts; i++)
550 platt = plperl_get_key(plkeys, i);
552 attn = modattrs[i] = SPI_fnumber(tupdesc, platt);
554 if (attn == SPI_ERROR_NOATTRIBUTE)
555 elog(ERROR, "plperl: invalid attribute `%s' in tuple.", platt);
558 plval = plperl_get_elem(hvNew, platt);
560 typetup = SearchSysCache(TYPEOID, ObjectIdGetDatum(tupdesc->attrs[atti]->atttypid), 0, 0, 0);
561 typinput = ((Form_pg_type) GETSTRUCT(typetup))->typinput;
562 typelem = ((Form_pg_type) GETSTRUCT(typetup))->typelem;
563 ReleaseSysCache(typetup);
564 fmgr_info(typinput, &finfo);
568 modvalues[i] = FunctionCall3(&finfo,
569 CStringGetDatum(plval),
570 ObjectIdGetDatum(typelem),
571 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
576 modvalues[i] = (Datum) 0;
580 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts, modattrs, modvalues, modnulls);
586 elog(ERROR, "plperl: SPI_modifytuple failed -- error: %d", SPI_result);
591 /**********************************************************************
592 * plperl_call_handler - This is the only visible function
593 * of the PL interpreter. The PostgreSQL
594 * function manager and trigger manager
595 * call this function for execution of
597 **********************************************************************/
598 PG_FUNCTION_INFO_V1(plperl_call_handler);
600 /* keep non-static */
602 plperl_call_handler(PG_FUNCTION_ARGS)
605 plperl_proc_desc *save_prodesc;
608 * Initialize interpreter if first time through
613 * Ensure that static pointers are saved/restored properly
615 save_prodesc = plperl_current_prodesc;
619 /************************************************************
620 * Connect to SPI manager
621 ************************************************************/
622 if (SPI_connect() != SPI_OK_CONNECT)
623 elog(ERROR, "could not connect to SPI manager");
625 /************************************************************
626 * Determine if called as function or trigger and
627 * call appropriate subhandler
628 ************************************************************/
629 if (CALLED_AS_TRIGGER(fcinfo))
630 retval = PointerGetDatum(plperl_trigger_handler(fcinfo));
632 retval = plperl_func_handler(fcinfo);
636 plperl_current_prodesc = save_prodesc;
641 plperl_current_prodesc = save_prodesc;
647 /**********************************************************************
648 * plperl_create_sub() - calls the perl interpreter to
649 * create the anonymous subroutine whose text is in the SV.
650 * Returns the SV containing the RV to the closure.
651 **********************************************************************/
653 plperl_create_sub(char *s, bool trusted)
659 if (trusted && !plperl_safe_init_done)
665 XPUSHs(sv_2mortal(newSVpv("my $_TD=$_[0]; shift;", 0)));
666 XPUSHs(sv_2mortal(newSVpv(s, 0)));
670 * G_KEEPERR seems to be needed here, else we don't recognize compile
671 * errors properly. Perhaps it's because there's another level of
672 * eval inside mksafefunc?
674 count = perl_call_pv((trusted ? "mksafefunc" : "mkunsafefunc"),
675 G_SCALAR | G_EVAL | G_KEEPERR);
683 elog(ERROR, "didn't get a return item from mksafefunc");
692 elog(ERROR, "creation of function failed: %s", SvPV(ERRSV, PL_na));
696 * need to make a deep copy of the return. it comes off the stack as a
699 subref = newSVsv(POPs);
708 * subref is our responsibility because it is not mortal
710 SvREFCNT_dec(subref);
711 elog(ERROR, "didn't get a code ref");
721 /**********************************************************************
722 * plperl_init_shared_libs() -
724 * We cannot use the DynaLoader directly to get at the Opcode
725 * module (used by Safe.pm). So, we link Opcode into ourselves
726 * and do the initialization behind perl's back.
728 **********************************************************************/
730 EXTERN_C void boot_DynaLoader(pTHX_ CV *cv);
731 EXTERN_C void boot_SPI(pTHX_ CV *cv);
734 plperl_init_shared_libs(pTHX)
736 char *file = __FILE__;
738 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
739 newXS("SPI::bootstrap", boot_SPI, file);
742 /**********************************************************************
743 * plperl_call_perl_func() - calls a perl function through the RV
744 * stored in the prodesc structure. massages the input parms properly
745 **********************************************************************/
747 plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
758 XPUSHs(sv_2mortal(newSVpv("undef", 0)));
759 for (i = 0; i < desc->nargs; i++)
761 if (desc->arg_is_rowtype[i])
763 if (fcinfo->argnull[i])
764 XPUSHs(&PL_sv_undef);
771 HeapTupleData tmptup;
774 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
775 /* Extract rowtype info and find a tupdesc */
776 tupType = HeapTupleHeaderGetTypeId(td);
777 tupTypmod = HeapTupleHeaderGetTypMod(td);
778 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
779 /* Build a temporary HeapTuple control structure */
780 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
784 * plperl_build_tuple_argument better return a mortal SV.
786 hashref = plperl_build_tuple_argument(&tmptup, tupdesc);
792 if (fcinfo->argnull[i])
793 XPUSHs(&PL_sv_undef);
798 tmp = DatumGetCString(FunctionCall3(&(desc->arg_out_func[i]),
800 ObjectIdGetDatum(desc->arg_typioparam[i]),
802 XPUSHs(sv_2mortal(newSVpv(tmp, 0)));
809 /* Do NOT use G_KEEPERR here */
810 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
819 elog(ERROR, "didn't get a return item from function");
828 elog(ERROR, "error from function: %s", SvPV(ERRSV, PL_na));
831 retval = newSVsv(POPs);
840 /**********************************************************************
841 * plperl_call_perl_trigger_func() - calls a perl function affected by trigger
842 * through the RV stored in the prodesc structure. massages the input parms properly
843 **********************************************************************/
845 plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo, SV *td)
857 for (i = 0; i < ((TriggerData *) fcinfo->context)->tg_trigger->tgnargs; i++)
858 XPUSHs(sv_2mortal(newSVpv(((TriggerData *) fcinfo->context)->tg_trigger->tgargs[i], 0)));
861 count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL | G_KEEPERR);
870 elog(ERROR, "plperl: didn't get a return item from function");
879 elog(ERROR, "plperl: error from function: %s", SvPV(ERRSV, PL_na));
882 retval = newSVsv(POPs);
891 /**********************************************************************
892 * plperl_func_handler() - Handler for regular function calls
893 **********************************************************************/
895 plperl_func_handler(PG_FUNCTION_ARGS)
897 plperl_proc_desc *prodesc;
901 /* Find or compile the function */
902 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false);
904 plperl_current_prodesc = prodesc;
906 /************************************************************
907 * Call the Perl function if not returning set
908 ************************************************************/
909 if (!prodesc->fn_retisset)
910 perlret = plperl_call_perl_func(prodesc, fcinfo);
913 if (SRF_IS_FIRSTCALL()) /* call function only once */
914 srf_perlret = plperl_call_perl_func(prodesc, fcinfo);
915 perlret = srf_perlret;
918 if (prodesc->fn_retisset && SRF_IS_FIRSTCALL())
920 if (prodesc->fn_retistuple)
921 g_column_keys = newAV();
922 if (SvTYPE(perlret) != SVt_RV)
923 elog(ERROR, "plperl: set-returning function must return reference");
926 /************************************************************
927 * Disconnect from SPI manager and then create the return
928 * values datum (if the input function does a palloc for it
929 * this must not be allocated in the SPI memory context
930 * because SPI_finish would free it).
931 ************************************************************/
932 if (SPI_finish() != SPI_OK_FINISH)
933 elog(ERROR, "SPI_finish() failed");
935 if (!(perlret && SvOK(perlret) && SvTYPE(perlret) != SVt_NULL))
937 /* return NULL if Perl code returned undef */
939 fcinfo->isnull = true;
942 if (prodesc->fn_retisset && !(perlret && SvTYPE(SvRV(perlret)) == SVt_PVAV))
943 elog(ERROR, "plperl: set-returning function must return reference to array");
945 if (prodesc->fn_retistuple && perlret && SvTYPE(perlret) != SVt_RV)
946 elog(ERROR, "plperl: composite-returning function must return a reference");
948 if (prodesc->fn_retistuple && fcinfo->resultinfo) /* set of tuples */
954 FuncCallContext *funcctx;
958 TupleTableSlot *slot;
959 AttInMetadata *attinmeta;
961 char **values = NULL;
962 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
964 if (prodesc->fn_retisset && !rsinfo)
966 (errcode(ERRCODE_SYNTAX_ERROR),
967 errmsg("returning a composite type is not allowed in this context"),
968 errhint("This function is intended for use in the FROM clause.")));
971 isset = plperl_is_set(perlret);
973 if (SvTYPE(SvRV(perlret)) == SVt_PVHV)
974 ret_hv = (HV *) SvRV(perlret);
976 ret_av = (AV *) SvRV(perlret);
978 if (SRF_IS_FIRSTCALL())
980 MemoryContext oldcontext;
983 funcctx = SRF_FIRSTCALL_INIT();
985 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
987 if (SvTYPE(SvRV(perlret)) == SVt_PVHV)
990 funcctx->max_calls = hv_iterinit(ret_hv);
992 funcctx->max_calls = 1;
997 funcctx->max_calls = av_len(ret_av) + 1;
999 funcctx->max_calls = 1;
1002 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1004 g_attr_num = tupdesc->natts;
1006 for (i = 0; i < tupdesc->natts; i++)
1007 av_store(g_column_keys, i + 1,
1008 newSVpv(SPI_fname(tupdesc, i+1), 0));
1010 slot = TupleDescGetSlot(tupdesc);
1011 funcctx->slot = slot;
1012 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1013 funcctx->attinmeta = attinmeta;
1014 MemoryContextSwitchTo(oldcontext);
1017 funcctx = SRF_PERCALL_SETUP();
1018 call_cntr = funcctx->call_cntr;
1019 max_calls = funcctx->max_calls;
1020 slot = funcctx->slot;
1021 attinmeta = funcctx->attinmeta;
1023 if (call_cntr < max_calls)
1036 svp = av_fetch(ret_av, call_cntr, FALSE);
1038 row_hv = (HV *) SvRV(*svp);
1040 values = (char **) palloc(g_attr_num * sizeof(char *));
1042 for (i = 0; i < g_attr_num; i++)
1044 column_key = plperl_get_key(g_column_keys, i + 1);
1045 elem = plperl_get_elem(row_hv, column_key);
1056 values = (char **) palloc(g_attr_num * sizeof(char *));
1057 for (i = 0; i < g_attr_num; i++)
1059 column_key = SPI_fname(tupdesc, i + 1);
1060 elem = plperl_get_elem(ret_hv, column_key);
1067 tuple = BuildTupleFromCStrings(attinmeta, values);
1068 result = TupleGetDatum(slot, tuple);
1069 SRF_RETURN_NEXT(funcctx, result);
1073 SvREFCNT_dec(perlret);
1074 SRF_RETURN_DONE(funcctx);
1077 else if (prodesc->fn_retisset) /* set of non-tuples */
1079 FuncCallContext *funcctx;
1081 if (SRF_IS_FIRSTCALL())
1083 MemoryContext oldcontext;
1085 funcctx = SRF_FIRSTCALL_INIT();
1086 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1088 funcctx->max_calls = av_len((AV *) SvRV(perlret)) + 1;
1091 funcctx = SRF_PERCALL_SETUP();
1093 if (funcctx->call_cntr < funcctx->max_calls)
1099 array = (AV *) SvRV(perlret);
1100 svp = av_fetch(array, funcctx->call_cntr, FALSE);
1102 if (SvTYPE(*svp) != SVt_NULL)
1103 result = FunctionCall3(&prodesc->result_in_func,
1104 PointerGetDatum(SvPV(*svp, PL_na)),
1105 ObjectIdGetDatum(prodesc->result_typioparam),
1109 fcinfo->isnull = true;
1112 SRF_RETURN_NEXT(funcctx, result);
1113 fcinfo->isnull = false;
1118 SvREFCNT_dec(perlret);
1119 SRF_RETURN_DONE(funcctx);
1122 else if (!fcinfo->isnull) /* non-null singleton */
1126 if (prodesc->fn_retistuple) /* singleton perl hash to Datum */
1128 TupleDesc td = lookup_rowtype_tupdesc(prodesc->ret_oid, (int32) -1);
1129 HV *perlhash = (HV *) SvRV(perlret);
1134 AttInMetadata *attinmeta;
1139 (errcode(ERRCODE_SYNTAX_ERROR),
1140 errmsg("no TupleDesc info available")));
1142 values = (char **) palloc(td->natts * sizeof(char *));
1143 for (i = 0; i < td->natts; i++)
1146 key = SPI_fname(td, i + 1);
1147 val = plperl_get_elem(perlhash, key);
1153 attinmeta = TupleDescGetAttInMetadata(td);
1154 tup = BuildTupleFromCStrings(attinmeta, values);
1155 retval = HeapTupleGetDatum(tup);
1159 /* perl string to Datum */
1160 retval = FunctionCall3(&prodesc->result_in_func,
1161 PointerGetDatum(SvPV(perlret, PL_na)),
1162 ObjectIdGetDatum(prodesc->result_typioparam),
1167 SvREFCNT_dec(perlret);
1171 /**********************************************************************
1172 * plperl_trigger_handler() - Handler for trigger function calls
1173 **********************************************************************/
1175 plperl_trigger_handler(PG_FUNCTION_ARGS)
1177 plperl_proc_desc *prodesc;
1184 /* Find or compile the function */
1185 prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true);
1187 plperl_current_prodesc = prodesc;
1189 /************************************************************
1190 * Call the Perl function
1191 ************************************************************/
1194 * call perl trigger function and build TD hash
1196 svTD = plperl_trigger_build_args(fcinfo);
1197 perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
1199 hvTD = (HV *) SvRV(svTD); /* convert SV TD structure to Perl Hash
1202 tmp = SvPV(perlret, PL_na);
1204 /************************************************************
1205 * Disconnect from SPI manager and then create the return
1206 * values datum (if the input function does a palloc for it
1207 * this must not be allocated in the SPI memory context
1208 * because SPI_finish would free it).
1209 ************************************************************/
1210 if (SPI_finish() != SPI_OK_FINISH)
1211 elog(ERROR, "plperl: SPI_finish() failed");
1213 if (!(perlret && SvOK(perlret)))
1215 TriggerData *trigdata = ((TriggerData *) fcinfo->context);
1217 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1218 retval = (Datum) trigdata->tg_trigtuple;
1219 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1220 retval = (Datum) trigdata->tg_newtuple;
1221 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
1222 retval = (Datum) trigdata->tg_trigtuple;
1226 if (!fcinfo->isnull)
1231 if (strcasecmp(tmp, "SKIP") == 0)
1233 else if (strcasecmp(tmp, "MODIFY") == 0)
1235 TriggerData *trigdata = (TriggerData *) fcinfo->context;
1237 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1238 trv = plperl_modify_tuple(hvTD, trigdata, trigdata->tg_trigtuple, fcinfo->flinfo->fn_oid);
1239 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1240 trv = plperl_modify_tuple(hvTD, trigdata, trigdata->tg_newtuple, fcinfo->flinfo->fn_oid);
1244 elog(WARNING, "plperl: Ignoring modified tuple in DELETE trigger");
1247 else if (strcasecmp(tmp, "OK"))
1250 elog(ERROR, "plperl: Expected return to be undef, 'SKIP' or 'MODIFY'");
1255 elog(ERROR, "plperl: Expected return to be undef, 'SKIP' or 'MODIFY'");
1257 retval = PointerGetDatum(trv);
1261 SvREFCNT_dec(perlret);
1263 fcinfo->isnull = false;
1267 /**********************************************************************
1268 * compile_plperl_function - compile (or hopefully just look up) function
1269 **********************************************************************/
1270 static plperl_proc_desc *
1271 compile_plperl_function(Oid fn_oid, bool is_trigger)
1274 Form_pg_proc procStruct;
1275 char internal_proname[64];
1277 plperl_proc_desc *prodesc = NULL;
1281 /* We'll need the pg_proc tuple in any case... */
1282 procTup = SearchSysCache(PROCOID,
1283 ObjectIdGetDatum(fn_oid),
1285 if (!HeapTupleIsValid(procTup))
1286 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1287 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1289 /************************************************************
1290 * Build our internal proc name from the functions Oid
1291 ************************************************************/
1293 sprintf(internal_proname, "__PLPerl_proc_%u", fn_oid);
1295 sprintf(internal_proname, "__PLPerl_proc_%u_trigger", fn_oid);
1297 proname_len = strlen(internal_proname);
1299 /************************************************************
1300 * Lookup the internal proc name in the hashtable
1301 ************************************************************/
1302 svp = hv_fetch(plperl_proc_hash, internal_proname, proname_len, FALSE);
1307 prodesc = (plperl_proc_desc *) SvIV(*svp);
1309 /************************************************************
1310 * If it's present, must check whether it's still up to date.
1311 * This is needed because CREATE OR REPLACE FUNCTION can modify the
1312 * function's pg_proc entry without changing its OID.
1313 ************************************************************/
1314 uptodate = (prodesc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&
1315 prodesc->fn_cmin == HeapTupleHeaderGetCmin(procTup->t_data));
1319 /* need we delete old entry? */
1324 /************************************************************
1325 * If we haven't found it in the hashtable, we analyze
1326 * the functions arguments and returntype and store
1327 * the in-/out-functions in the prodesc block and create
1328 * a new hashtable entry for it.
1330 * Then we load the procedure into the Perl interpreter.
1331 ************************************************************/
1332 if (prodesc == NULL)
1336 Form_pg_language langStruct;
1337 Form_pg_type typeStruct;
1342 /************************************************************
1343 * Allocate a new procedure description block
1344 ************************************************************/
1345 prodesc = (plperl_proc_desc *) malloc(sizeof(plperl_proc_desc));
1346 if (prodesc == NULL)
1348 (errcode(ERRCODE_OUT_OF_MEMORY),
1349 errmsg("out of memory")));
1350 MemSet(prodesc, 0, sizeof(plperl_proc_desc));
1351 prodesc->proname = strdup(internal_proname);
1352 prodesc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1353 prodesc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1355 /* Remember if function is STABLE/IMMUTABLE */
1356 prodesc->fn_readonly =
1357 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1359 /************************************************************
1360 * Lookup the pg_language tuple by Oid
1361 ************************************************************/
1362 langTup = SearchSysCache(LANGOID,
1363 ObjectIdGetDatum(procStruct->prolang),
1365 if (!HeapTupleIsValid(langTup))
1367 free(prodesc->proname);
1369 elog(ERROR, "cache lookup failed for language %u",
1370 procStruct->prolang);
1372 langStruct = (Form_pg_language) GETSTRUCT(langTup);
1373 prodesc->lanpltrusted = langStruct->lanpltrusted;
1374 ReleaseSysCache(langTup);
1376 /************************************************************
1377 * Get the required information for input conversion of the
1379 ************************************************************/
1382 typeTup = SearchSysCache(TYPEOID,
1383 ObjectIdGetDatum(procStruct->prorettype),
1385 if (!HeapTupleIsValid(typeTup))
1387 free(prodesc->proname);
1389 elog(ERROR, "cache lookup failed for type %u",
1390 procStruct->prorettype);
1392 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1394 /* Disallow pseudotype result, except VOID or RECORD */
1395 if (typeStruct->typtype == 'p')
1397 if (procStruct->prorettype == VOIDOID ||
1398 procStruct->prorettype == RECORDOID)
1400 else if (procStruct->prorettype == TRIGGEROID)
1402 free(prodesc->proname);
1405 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1406 errmsg("trigger functions may only be called as triggers")));
1410 free(prodesc->proname);
1413 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1414 errmsg("plperl functions cannot return type %s",
1415 format_type_be(procStruct->prorettype))));
1419 prodesc->fn_retisset = procStruct->proretset; /* true, if function
1422 if (typeStruct->typtype == 'c' || procStruct->prorettype == RECORDOID)
1424 prodesc->fn_retistuple = true;
1426 procStruct->prorettype == RECORDOID ?
1427 typeStruct->typrelid :
1428 procStruct->prorettype;
1431 perm_fmgr_info(typeStruct->typinput, &(prodesc->result_in_func));
1432 prodesc->result_typioparam = getTypeIOParam(typeTup);
1434 ReleaseSysCache(typeTup);
1437 /************************************************************
1438 * Get the required information for output conversion
1439 * of all procedure arguments
1440 ************************************************************/
1443 prodesc->nargs = procStruct->pronargs;
1444 for (i = 0; i < prodesc->nargs; i++)
1446 typeTup = SearchSysCache(TYPEOID,
1447 ObjectIdGetDatum(procStruct->proargtypes[i]),
1449 if (!HeapTupleIsValid(typeTup))
1451 free(prodesc->proname);
1453 elog(ERROR, "cache lookup failed for type %u",
1454 procStruct->proargtypes[i]);
1456 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1458 /* Disallow pseudotype argument */
1459 if (typeStruct->typtype == 'p')
1461 free(prodesc->proname);
1464 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1465 errmsg("plperl functions cannot take type %s",
1466 format_type_be(procStruct->proargtypes[i]))));
1469 if (typeStruct->typtype == 'c')
1470 prodesc->arg_is_rowtype[i] = true;
1473 prodesc->arg_is_rowtype[i] = false;
1474 perm_fmgr_info(typeStruct->typoutput,
1475 &(prodesc->arg_out_func[i]));
1476 prodesc->arg_typioparam[i] = getTypeIOParam(typeTup);
1479 ReleaseSysCache(typeTup);
1483 /************************************************************
1484 * create the text of the anonymous subroutine.
1485 * we do not use a named subroutine so that we can call directly
1486 * through the reference.
1488 ************************************************************/
1489 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1490 Anum_pg_proc_prosrc, &isnull);
1492 elog(ERROR, "null prosrc");
1493 proc_source = DatumGetCString(DirectFunctionCall1(textout,
1496 /************************************************************
1497 * Create the procedure in the interpreter
1498 ************************************************************/
1499 prodesc->reference = plperl_create_sub(proc_source, prodesc->lanpltrusted);
1501 if (!prodesc->reference)
1503 free(prodesc->proname);
1505 elog(ERROR, "could not create internal procedure \"%s\"",
1509 /************************************************************
1510 * Add the proc description block to the hashtable
1511 ************************************************************/
1512 hv_store(plperl_proc_hash, internal_proname, proname_len,
1513 newSViv((IV) prodesc), 0);
1516 ReleaseSysCache(procTup);
1522 /**********************************************************************
1523 * plperl_build_tuple_argument() - Build a string for a ref to a hash
1524 * from all attributes of a given tuple
1525 **********************************************************************/
1527 plperl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc)
1542 for (i = 0; i < tupdesc->natts; i++)
1544 if (tupdesc->attrs[i]->attisdropped)
1547 attname = tupdesc->attrs[i]->attname.data;
1548 namelen = strlen(attname);
1549 attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1552 /* Store (attname => undef) and move on. */
1553 hv_store(hv, attname, namelen, newSV(0), 0);
1557 /************************************************************
1558 * Lookup the attribute type in the syscache
1559 * for the output function
1560 ************************************************************/
1561 typeTup = SearchSysCache(TYPEOID,
1562 ObjectIdGetDatum(tupdesc->attrs[i]->atttypid),
1564 if (!HeapTupleIsValid(typeTup))
1565 elog(ERROR, "cache lookup failed for type %u",
1566 tupdesc->attrs[i]->atttypid);
1568 typoutput = ((Form_pg_type) GETSTRUCT(typeTup))->typoutput;
1569 typioparam = getTypeIOParam(typeTup);
1570 ReleaseSysCache(typeTup);
1572 /************************************************************
1573 * Append the attribute name and the value to the list.
1574 ************************************************************/
1575 outputstr = DatumGetCString(OidFunctionCall3(typoutput,
1577 ObjectIdGetDatum(typioparam),
1578 Int32GetDatum(tupdesc->attrs[i]->atttypmod)));
1580 hv_store(hv, attname, namelen, newSVpv(outputstr, 0), 0);
1583 return sv_2mortal(newRV((SV *)hv));
1588 plperl_spi_exec(char *query, int limit)
1593 spi_rv = SPI_execute(query, plperl_current_prodesc->fn_readonly, limit);
1594 ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed, spi_rv);
1600 plperl_spi_execute_fetch_result(SPITupleTable *tuptable, int processed, int status)
1606 hv_store(result, "status", strlen("status"),
1607 newSVpv((char *) SPI_result_code_string(status), 0), 0);
1608 hv_store(result, "processed", strlen("processed"),
1609 newSViv(processed), 0);
1611 if (status == SPI_OK_SELECT)
1620 for (i = 0; i < processed; i++)
1622 row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc);
1623 av_push(rows, newRV_noinc((SV *)row));
1625 hv_store(result, "rows", strlen("rows"),
1626 newRV_noinc((SV *) rows), 0);
1630 SPI_freetuptable(tuptable);