1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * This software is copyright by Andrew Bosma
5 * but is really shameless cribbed from pltcl.c by Jan Weick, and
6 * plperl.c by Mark Hollomon.
8 * The author hereby grants permission to use, copy, modify,
9 * distribute, and license this software and its documentation for any
10 * purpose, provided that existing copyright notices are retained in
11 * all copies and that this notice is included verbatim in any
12 * distributions. No written agreement, license, or royalty fee is
13 * required for any of the authorized uses. Modifications to this
14 * software may be copyrighted by their author and need not follow the
15 * licensing terms described here, provided that the new terms are
16 * clearly indicated on the first page of each file where they apply.
18 * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY
19 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
20 * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
21 * DERIVATIVES THEREOF, EVEN IF THE AUTHOR HAVE BEEN ADVISED OF THE
22 * POSSIBILITY OF SUCH DAMAGE.
24 * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
25 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
27 * NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
28 * AND THE AUTHOR AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
29 * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
32 * $Header: /cvsroot/pgsql/src/pl/plpython/plpython.c,v 1.27 2002/11/22 16:25:30 tgl Exp $
34 *********************************************************************
52 #include "access/heapam.h"
53 #include "catalog/pg_proc.h"
54 #include "catalog/pg_type.h"
55 #include "commands/trigger.h"
56 #include "executor/spi.h"
58 #include "nodes/makefuncs.h"
59 #include "parser/parse_type.h"
60 #include "tcop/tcopprot.h"
61 #include "utils/syscache.h"
66 /* convert Postgresql Datum or tuple into a PyObject.
67 * input to Python. Tuples are converted to dictionary
71 typedef PyObject *(*PLyDatumToObFunc) (const char *);
73 typedef struct PLyDatumToOb
75 PLyDatumToObFunc func;
81 typedef struct PLyTupleToOb
87 typedef union PLyTypeInput
93 /* convert PyObject to a Postgresql Datum or tuple.
96 typedef struct PLyObToDatum
103 typedef struct PLyObToTuple
109 typedef union PLyTypeOutput
115 /* all we need to move Postgresql data to Python objects,
118 typedef struct PLyTypeInfo
126 /* cached procedure data
128 typedef struct PLyProcedure
131 TransactionId fn_xmin;
133 PLyTypeInfo result; /* also used to store info for trigger
135 PLyTypeInfo args[FUNC_MAX_ARGS];
137 PyObject *interp; /* restricted interpreter instance */
138 PyObject *reval; /* interpreter return */
139 PyObject *code; /* compiled procedure code */
140 PyObject *statics; /* data saved across calls, local scope */
141 PyObject *globals; /* data saved across calls, global score */
142 PyObject *me; /* PyCObject containing pointer to this
149 typedef struct PLyPlanObject
152 void *plan; /* return of an SPI_saveplan */
159 typedef struct PLyResultObject
162 /* HeapTuple *tuples; */
163 PyObject *nrows; /* number of rows returned by query */
164 PyObject *rows; /* data rows, or None if no data returned */
165 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
169 /* function declarations
172 /* the only exported function, with the magic telling Postgresql
173 * what function call interface it implements.
175 Datum plpython_call_handler(PG_FUNCTION_ARGS);
177 PG_FUNCTION_INFO_V1(plpython_call_handler);
179 /* most of the remaining of the declarations, all static
182 /* these should only be called once at the first call
183 * of plpython_call_handler. initialize the python interpreter
186 static void PLy_init_all(void);
187 static void PLy_init_interp(void);
188 static void PLy_init_safe_interp(void);
189 static void PLy_init_plpy(void);
191 /* Helper functions used during initialization */
192 static int populate_methods(PyObject * klass, PyMethodDef * methods);
193 static PyObject *build_tuple(char *string_list[], int len);
195 /* error handler. collects the current Python exception, if any,
196 * and appends it to the error and sends it to elog
198 static void PLy_elog(int, const char *,...);
200 /* call PyErr_SetString with a vprint interface
203 PLy_exception_set(PyObject *, const char *,...)
204 __attribute__((format(printf, 2, 3)));
206 /* Get the innermost python procedure called from the backend.
208 static char *PLy_procedure_name(PLyProcedure *);
210 /* some utility functions
212 static void *PLy_malloc(size_t);
213 static void *PLy_realloc(void *, size_t);
214 static void PLy_free(void *);
216 /* sub handlers for functions and triggers
218 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
219 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
221 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
222 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
224 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
225 TriggerData *, HeapTuple);
227 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
229 /* returns a cached PLyProcedure, or creates, stores and returns
230 * a new PLyProcedure.
232 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo, bool);
234 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
236 HeapTuple procTup, char *key);
238 static void PLy_procedure_compile(PLyProcedure *, const char *);
239 static char *PLy_procedure_munge_source(const char *, const char *);
240 static void PLy_procedure_delete(PLyProcedure *);
242 static void PLy_typeinfo_init(PLyTypeInfo *);
243 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
244 static void PLy_output_datum_func(PLyTypeInfo *, Form_pg_type);
245 static void PLy_output_datum_func2(PLyObToDatum *, Form_pg_type);
246 static void PLy_input_datum_func(PLyTypeInfo *, Form_pg_type);
247 static void PLy_input_datum_func2(PLyDatumToOb *, Form_pg_type);
248 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
249 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
253 static PyObject *PLy_r_open(PyObject * self, PyObject * args);
255 /* conversion functions
257 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
258 static PyObject *PLyBool_FromString(const char *);
259 static PyObject *PLyFloat_FromString(const char *);
260 static PyObject *PLyInt_FromString(const char *);
261 static PyObject *PLyLong_FromString(const char *);
262 static PyObject *PLyString_FromString(const char *);
267 static int PLy_first_call = 1;
268 static volatile int PLy_call_level = 0;
271 * Last function called by postgres backend
273 static PLyProcedure *PLy_last_procedure = NULL;
275 /* this gets modified in plpython_call_handler and PLy_elog.
276 * test it any old where, but do NOT modify it anywhere except
277 * those two functions
279 static volatile int PLy_restart_in_progress = 0;
281 static PyObject *PLy_interp_globals = NULL;
282 static PyObject *PLy_interp_safe = NULL;
283 static PyObject *PLy_interp_safe_globals = NULL;
284 static PyObject *PLy_importable_modules = NULL;
285 static PyObject *PLy_ok_posix_names = NULL;
286 static PyObject *PLy_ok_sys_names = NULL;
287 static PyObject *PLy_procedure_cache = NULL;
289 static char *PLy_importable_modules_list[] = {
317 static char *PLy_ok_posix_names_list[] = {
321 static char *PLy_ok_sys_names_list[] = {
324 "getdefaultencoding",
336 static PyObject *PLy_exc_error = NULL;
337 static PyObject *PLy_exc_fatal = NULL;
338 static PyObject *PLy_exc_spi_error = NULL;
340 /* some globals for the python module
342 static char PLy_plan_doc[] = {
343 "Store a PostgreSQL plan"
346 static char PLy_result_doc[] = {
347 "Results of a PostgreSQL query"
352 volatile int exc_save_calls = 0;
353 volatile int exc_restore_calls = 0;
354 volatile int func_enter_calls = 0;
355 volatile int func_leave_calls = 0;
359 * the function definitions
363 * This routine is a crock, and so is everyplace that calls it. The problem
364 * is that the cached form of plpython functions/queries is allocated permanently
365 * (mostly via malloc()) and never released until backend exit. Subsidiary
366 * data structures such as fmgr info records therefore must live forever
367 * as well. A better implementation would store all this stuff in a per-
368 * function memory context that could be reclaimed at need. In the meantime,
369 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
370 * it might allocate, and whatever the eventual function might allocate using
371 * fn_mcxt, will live forever too.
374 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
376 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
380 plpython_call_handler(PG_FUNCTION_ARGS)
384 volatile bool is_trigger;
385 PLyProcedure *volatile proc = NULL;
392 if (SPI_connect() != SPI_OK_CONNECT)
393 elog(ERROR, "plpython: Unable to connect to SPI manager");
396 is_trigger = CALLED_AS_TRIGGER(fcinfo);
403 if (PLy_call_level == 0)
405 PLy_restart_in_progress = 0;
409 PLy_restart_in_progress += 1;
418 * elog(DEBUG3, "PLy_restart_in_progress is %d",
419 * PLy_restart_in_progress);
422 proc = PLy_procedure_get(fcinfo, is_trigger);
426 HeapTuple trv = PLy_trigger_handler(fcinfo, proc);
428 retval = PointerGetDatum(trv);
431 retval = PLy_function_handler(fcinfo, proc);
442 /* trigger and function sub handlers
444 * the python function is expected to return Py_None if the tuple is
445 * acceptable and unmodified. Otherwise it should return a PyString
446 * object who's value is SKIP, or MODIFY. SKIP means don't perform
447 * this action. MODIFY means the tuple has been modified, so update
448 * tuple and perform action. SKIP and MODIFY assume the trigger fires
449 * BEFORE the event and is ROW level. postgres expects the function
450 * to take no arguments and return an argument of type trigger.
453 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
457 PyObject *volatile plargs = NULL;
458 PyObject *volatile plrv = NULL;
473 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
474 plrv = PLy_procedure_call(proc, "TD", plargs);
477 * Disconnect from SPI manager
479 if (SPI_finish() != SPI_OK_FINISH)
480 elog(ERROR, "plpython: SPI_finish failed");
483 elog(FATAL, "Aiieee, PLy_procedure_call returned NULL");
485 if (PLy_restart_in_progress)
486 elog(FATAL, "Aiieee, restart in progress not expected");
489 * return of None means we're happy with the tuple
495 if (!PyString_Check(plrv))
496 elog(ERROR, "plpython: Expected trigger to return None or a String");
498 srv = PyString_AsString(plrv);
499 if (strcasecmp(srv, "SKIP") == 0)
501 else if (strcasecmp(srv, "MODIFY") == 0)
503 TriggerData *tdata = (TriggerData *) fcinfo->context;
505 if ((TRIGGER_FIRED_BY_INSERT(tdata->tg_event)) ||
506 (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event)))
507 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
509 elog(WARNING, "plpython: Ignoring modified tuple in DELETE trigger");
511 else if (strcasecmp(srv, "OK"))
514 * hmmm, perhaps they only read the pltcl page, not a
515 * surprising thing since i've written no documentation, so
516 * accept a belated OK
518 elog(ERROR, "plpython: Expected return to be 'SKIP' or 'MODIFY'");
531 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
535 PyObject *volatile plntup;
536 PyObject *volatile plkeys;
537 PyObject *volatile platt;
538 PyObject *volatile plval;
539 PyObject *volatile plstr;
546 int *volatile modattrs;
547 Datum *volatile modvalues;
548 char *volatile modnulls;
551 plntup = plkeys = platt = plval = plstr = NULL;
579 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
580 elog(ERROR, "plpython: TD[\"new\"] deleted, unable to modify tuple");
581 if (!PyDict_Check(plntup))
582 elog(ERROR, "plpython: TD[\"new\"] is not a dictionary object");
585 plkeys = PyDict_Keys(plntup);
586 natts = PyList_Size(plkeys);
588 if (natts != proc->result.out.r.natts)
589 elog(ERROR, "plpython: TD[\"new\"] has an incorrect number of keys.");
591 modattrs = palloc(natts * sizeof(int));
592 modvalues = palloc(natts * sizeof(Datum));
593 for (i = 0; i < natts; i++)
596 modvalues[i] = (Datum) NULL;
598 modnulls = palloc(natts + 1);
599 memset(modnulls, 'n', natts);
600 modnulls[natts] = '\0';
602 tupdesc = tdata->tg_relation->rd_att;
604 for (j = 0; j < natts; j++)
608 platt = PyList_GetItem(plkeys, j);
609 if (!PyString_Check(platt))
610 elog(ERROR, "plpython: attribute is not a string");
611 attn = modattrs[j] = SPI_fnumber(tupdesc, PyString_AsString(platt));
613 if (attn == SPI_ERROR_NOATTRIBUTE)
614 elog(ERROR, "plpython: invalid attribute `%s' in tuple.",
615 PyString_AsString(platt));
618 plval = PyDict_GetItem(plntup, platt);
620 elog(FATAL, "plpython: interpreter is probably corrupted");
624 if (plval != Py_None)
626 plstr = PyObject_Str(plval);
627 src = PyString_AsString(plstr);
629 modvalues[j] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
630 CStringGetDatum(src),
631 ObjectIdGetDatum(proc->result.out.r.atts[atti].typelem),
632 Int32GetDatum(tupdesc->attrs[j]->atttypmod));
642 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts, modattrs,
643 modvalues, modnulls);
646 * FIXME -- these leak if not explicity pfree'd by other elog calls,
654 elog(ERROR, "plpython: SPI_modifytuple failed -- error %d", SPI_result);
665 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
677 PyObject *volatile pltdata = NULL;
692 tdata = (TriggerData *) fcinfo->context;
694 pltdata = PyDict_New();
696 PLy_elog(ERROR, "Unable to build arguments for trigger procedure");
698 pltname = PyString_FromString(tdata->tg_trigger->tgname);
699 PyDict_SetItemString(pltdata, "name", pltname);
702 stroid = DatumGetCString(DirectFunctionCall1(oidout,
703 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
704 pltrelid = PyString_FromString(stroid);
705 PyDict_SetItemString(pltdata, "relid", pltrelid);
711 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
712 pltwhen = PyString_FromString("BEFORE");
713 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
714 pltwhen = PyString_FromString("AFTER");
716 pltwhen = PyString_FromString("UNKNOWN");
717 PyDict_SetItemString(pltdata, "when", pltwhen);
720 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
721 pltlevel = PyString_FromString("ROW");
722 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
723 pltlevel = PyString_FromString("STATEMENT");
725 pltlevel = PyString_FromString("UNKNOWN");
726 PyDict_SetItemString(pltdata, "level", pltlevel);
729 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
731 pltevent = PyString_FromString("INSERT");
732 PyDict_SetItemString(pltdata, "old", Py_None);
733 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
734 tdata->tg_relation->rd_att);
735 PyDict_SetItemString(pltdata, "new", pytnew);
737 *rv = tdata->tg_trigtuple;
739 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
741 pltevent = PyString_FromString("DELETE");
742 PyDict_SetItemString(pltdata, "new", Py_None);
743 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
744 tdata->tg_relation->rd_att);
745 PyDict_SetItemString(pltdata, "old", pytold);
747 *rv = tdata->tg_trigtuple;
749 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
751 pltevent = PyString_FromString("UPDATE");
752 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
753 tdata->tg_relation->rd_att);
754 PyDict_SetItemString(pltdata, "new", pytnew);
756 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
757 tdata->tg_relation->rd_att);
758 PyDict_SetItemString(pltdata, "old", pytold);
760 *rv = tdata->tg_newtuple;
764 pltevent = PyString_FromString("UNKNOWN");
765 PyDict_SetItemString(pltdata, "old", Py_None);
766 PyDict_SetItemString(pltdata, "new", Py_None);
767 *rv = tdata->tg_trigtuple;
769 PyDict_SetItemString(pltdata, "event", pltevent);
772 if (tdata->tg_trigger->tgnargs)
780 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
781 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
783 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
786 * stolen, don't Py_DECREF
788 PyList_SetItem(pltargs, i, pltarg);
796 PyDict_SetItemString(pltdata, "args", pltargs);
806 /* function handler and friends
809 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
813 PyObject *volatile plargs = NULL;
814 PyObject *volatile plrv = NULL;
815 PyObject *volatile plrv_so = NULL;
821 * setup to catch elog in while building function arguments, and
822 * DECREF the plargs if the function call fails
836 plargs = PLy_function_build_args(fcinfo, proc);
837 plrv = PLy_procedure_call(proc, "args", plargs);
840 * Disconnect from SPI manager and then create the return values datum
841 * (if the input function does a palloc for it this must not be
842 * allocated in the SPI memory context because SPI_finish would free
845 if (SPI_finish() != SPI_OK_FINISH)
846 elog(ERROR, "plpython: SPI_finish failed");
850 elog(FATAL, "Aiieee, PLy_procedure_call returned NULL");
852 if (!PLy_restart_in_progress)
853 PLy_elog(ERROR, "plpython: Function \"%s\" failed.", proc->proname);
856 * FIXME is this dead code? i'm pretty sure it is for unnested
857 * calls, but not for nested calls
864 * convert the python PyObject to a postgresql Datum FIXME returning a
865 * NULL, ie PG_RETURN_NULL() blows the backend to small messy bits...
866 * it this a bug or expected? so just call with the string value of
872 fcinfo->isnull = true;
877 fcinfo->isnull = false;
878 plrv_so = PyObject_Str(plrv);
879 plrv_sc = PyString_AsString(plrv_so);
880 rv = FunctionCall3(&proc->result.out.d.typfunc,
881 PointerGetDatum(plrv_sc),
882 ObjectIdGetDatum(proc->result.out.d.typelem),
896 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
899 PLyProcedure *current;
903 current = PLy_last_procedure;
904 PLy_last_procedure = proc;
905 PyDict_SetItemString(proc->globals, kargs, vargs);
906 rv = PyObject_CallFunction(proc->reval, "O", proc->code);
907 PLy_last_procedure = current;
909 if ((rv == NULL) || (PyErr_Occurred()))
912 if (!PLy_restart_in_progress)
913 PLy_elog(ERROR, "Call of function `%s' failed.", proc->proname);
921 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
924 PyObject *volatile arg = NULL;
925 PyObject *volatile args = NULL;
931 * FIXME -- if the setjmp setup is expensive, add the arg and args
932 * field to the procedure struct and cleanup at the start of the next
945 args = PyList_New(proc->nargs);
946 for (i = 0; i < proc->nargs; i++)
948 if (proc->args[i].is_rel == 1)
950 TupleTableSlot *slot = (TupleTableSlot *) fcinfo->arg[i];
952 arg = PLyDict_FromTuple(&(proc->args[i]), slot->val,
953 slot->ttc_tupleDescriptor);
957 if (!fcinfo->argnull[i])
962 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
964 ObjectIdGetDatum(proc->args[i].in.d.typelem),
966 ct = DatumGetCString(dt);
967 arg = (proc->args[i].in.d.func) (ct);
981 * FIXME -- error check this
983 PyList_SetItem(args, i, arg);
992 /* PLyProcedure functions
994 static PLyProcedure *
995 PLy_procedure_get(FunctionCallInfo fcinfo, bool is_trigger)
1001 PLyProcedure *proc = NULL;
1006 fn_oid = fcinfo->flinfo->fn_oid;
1007 procTup = SearchSysCache(PROCOID,
1008 ObjectIdGetDatum(fn_oid),
1010 if (!HeapTupleIsValid(procTup))
1011 elog(ERROR, "plpython: cache lookup for procedure %u failed", fn_oid);
1013 rv = snprintf(key, sizeof(key), "%u%s",
1015 is_trigger ? "_trigger" : "");
1016 if ((rv >= sizeof(key)) || (rv < 0))
1017 elog(FATAL, "plpython: Buffer overrun in %s:%d", __FILE__, __LINE__);
1019 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
1024 if (!PyCObject_Check(plproc))
1025 elog(FATAL, "plpython: Expected a PyCObject, didn't get one");
1029 proc = PyCObject_AsVoidPtr(plproc);
1030 if (proc->me != plproc)
1031 elog(FATAL, "plpython: Aiieee, proc->me != plproc");
1032 /* did we find an up-to-date cache entry? */
1033 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
1034 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
1042 proc = PLy_procedure_create(fcinfo, is_trigger, procTup, key);
1044 ReleaseSysCache(procTup);
1049 static PLyProcedure *
1050 PLy_procedure_create(FunctionCallInfo fcinfo, bool is_trigger,
1051 HeapTuple procTup, char *key)
1056 Form_pg_proc procStruct;
1057 PLyProcedure *volatile proc;
1058 char *volatile procSource = NULL;
1065 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1067 rv = snprintf(procName, sizeof(procName),
1068 "__plpython_procedure_%s_%u%s",
1069 NameStr(procStruct->proname),
1070 fcinfo->flinfo->fn_oid,
1071 is_trigger ? "_trigger" : "");
1072 if ((rv >= sizeof(procName)) || (rv < 0))
1073 elog(FATAL, "plpython: Procedure name would overrun buffer");
1075 proc = PLy_malloc(sizeof(PLyProcedure));
1076 proc->proname = PLy_malloc(strlen(procName) + 1);
1077 strcpy(proc->proname, procName);
1078 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1079 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1080 PLy_typeinfo_init(&proc->result);
1081 for (i = 0; i < FUNC_MAX_ARGS; i++)
1082 PLy_typeinfo_init(&proc->args[i]);
1084 proc->code = proc->interp = proc->reval = proc->statics = NULL;
1085 proc->globals = proc->me = NULL;
1091 PLy_procedure_delete(proc);
1098 * get information required for output conversion of the return value,
1099 * but only if this isn't a trigger.
1103 HeapTuple rvTypeTup;
1104 Form_pg_type rvTypeStruct;
1107 rvDatum = ObjectIdGetDatum(procStruct->prorettype);
1108 rvTypeTup = SearchSysCache(TYPEOID, rvDatum, 0, 0, 0);
1109 if (!HeapTupleIsValid(rvTypeTup))
1110 elog(ERROR, "plpython: cache lookup for type \"%u\" failed",
1111 procStruct->prorettype);
1113 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1114 if (rvTypeStruct->typrelid == InvalidOid)
1115 PLy_output_datum_func(&proc->result, rvTypeStruct);
1117 elog(ERROR, "plpython: tuple return types not supported, yet");
1119 ReleaseSysCache(rvTypeTup);
1124 * input/output conversion for trigger tuples. use the result
1125 * TypeInfo variable to store the tuple conversion info.
1127 TriggerData *tdata = (TriggerData *) fcinfo->context;
1129 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1130 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1134 * now get information required for input conversion of the procedures
1137 proc->nargs = fcinfo->nargs;
1138 for (i = 0; i < fcinfo->nargs; i++)
1140 HeapTuple argTypeTup;
1141 Form_pg_type argTypeStruct;
1144 argDatum = ObjectIdGetDatum(procStruct->proargtypes[i]);
1145 argTypeTup = SearchSysCache(TYPEOID, argDatum, 0, 0, 0);
1146 if (!HeapTupleIsValid(argTypeTup))
1147 elog(ERROR, "plpython: cache lookup for type \"%u\" failed",
1148 procStruct->proargtypes[i]);
1149 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1151 if (argTypeStruct->typrelid == InvalidOid)
1152 PLy_input_datum_func(&(proc->args[i]), argTypeStruct);
1155 TupleTableSlot *slot = (TupleTableSlot *) fcinfo->arg[i];
1157 PLy_input_tuple_funcs(&(proc->args[i]),
1158 slot->ttc_tupleDescriptor);
1161 ReleaseSysCache(argTypeTup);
1166 * get the text of the function.
1168 procDatum = DirectFunctionCall1(textout,
1169 PointerGetDatum(&procStruct->prosrc));
1170 procSource = DatumGetCString(procDatum);
1172 PLy_procedure_compile(proc, procSource);
1176 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1177 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1185 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1194 * get an instance of rexec.RExec for the function
1196 proc->interp = PyObject_CallMethod(PLy_interp_safe, "RExec", NULL);
1197 if ((proc->interp == NULL) || (PyErr_Occurred()))
1198 PLy_elog(ERROR, "Unable to create rexec.RExec instance");
1200 proc->reval = PyObject_GetAttrString(proc->interp, "r_eval");
1201 if ((proc->reval == NULL) || (PyErr_Occurred()))
1202 PLy_elog(ERROR, "Unable to get method `r_eval' from rexec.RExec");
1205 * add a __main__ module to the function's interpreter
1207 module = PyObject_CallMethod(proc->interp, "add_module", "s", "__main__");
1208 if ((module == NULL) || (PyErr_Occurred()))
1209 PLy_elog(ERROR, "Unable to get module `__main__' from rexec.RExec");
1212 * add plpy module to the interpreters main dictionary
1214 proc->globals = PyModule_GetDict(module);
1215 if ((proc->globals == NULL) || (PyErr_Occurred()))
1216 PLy_elog(ERROR, "Unable to get `__main__.__dict__' from rexec.RExec");
1219 * why the hell won't r_import or r_exec('import plpy') work?
1221 module = PyDict_GetItemString(PLy_interp_globals, "plpy");
1222 if ((module == NULL) || (PyErr_Occurred()))
1223 PLy_elog(ERROR, "Unable to get `plpy'");
1225 PyDict_SetItemString(proc->globals, "plpy", module);
1228 * SD is private preserved data between calls GD is global data shared
1231 proc->statics = PyDict_New();
1232 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1233 PyDict_SetItemString(proc->globals, "GD", PLy_interp_safe_globals);
1236 * insert the function code into the interpreter
1238 msrc = PLy_procedure_munge_source(proc->proname, src);
1239 crv = PyObject_CallMethod(proc->interp, "r_exec", "s", msrc);
1242 if ((crv != NULL) && (!PyErr_Occurred()))
1250 * compile a call to the function
1252 clen = snprintf(call, sizeof(call), "%s()", proc->proname);
1253 if ((clen < 0) || (clen >= sizeof(call)))
1254 elog(ERROR, "plpython: string would overflow buffer.");
1255 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1256 if ((proc->code != NULL) && (!PyErr_Occurred()))
1262 PLy_elog(ERROR, "Unable to compile function %s", proc->proname);
1266 PLy_procedure_munge_source(const char *name, const char *src)
1277 * room for function source and the def statement
1279 mlen = (strlen(src) * 2) + strlen(name) + 16;
1281 mrc = PLy_malloc(mlen);
1282 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1283 if ((plen < 0) || (plen >= mlen))
1284 elog(FATAL, "Aiieee, impossible buffer overrun (or snprintf failure)");
1303 if (mp > (mrc + mlen))
1304 elog(FATAL, "plpython: Buffer overrun in PLy_munge_source");
1310 PLy_procedure_delete(PLyProcedure * proc)
1316 Py_XDECREF(proc->code);
1317 Py_XDECREF(proc->interp);
1318 Py_XDECREF(proc->reval);
1319 Py_XDECREF(proc->statics);
1320 Py_XDECREF(proc->globals);
1321 Py_XDECREF(proc->me);
1323 PLy_free(proc->proname);
1324 for (i = 0; i < proc->nargs; i++)
1325 if (proc->args[i].is_rel == 1)
1327 if (proc->args[i].in.r.atts)
1328 PLy_free(proc->args[i].in.r.atts);
1329 if (proc->args[i].out.r.atts)
1330 PLy_free(proc->args[i].out.r.atts);
1336 /* conversion functions. remember output from python is
1337 * input to postgresql, and vis versa.
1340 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1347 if (arg->is_rel == 0)
1348 elog(FATAL, "plpython: PLyTypeInfo struct is initialized for a Datum");
1351 arg->in.r.natts = desc->natts;
1352 arg->in.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1354 for (i = 0; i < desc->natts; i++)
1357 Form_pg_type typeStruct;
1359 datum = ObjectIdGetDatum(desc->attrs[i]->atttypid);
1360 typeTup = SearchSysCache(TYPEOID, datum, 0, 0, 0);
1361 if (!HeapTupleIsValid(typeTup))
1363 char *attname = NameStr(desc->attrs[i]->attname);
1365 elog(ERROR, "plpython: Cache lookup for attribute `%s' type `%u' failed",
1366 attname, desc->attrs[i]->atttypid);
1369 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1371 PLy_input_datum_func2(&(arg->in.r.atts[i]), typeStruct);
1373 ReleaseSysCache(typeTup);
1378 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1385 if (arg->is_rel == 0)
1386 elog(FATAL, "plpython: PLyTypeInfo struct is initialized for a Datum");
1389 arg->out.r.natts = desc->natts;
1390 arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1392 for (i = 0; i < desc->natts; i++)
1395 Form_pg_type typeStruct;
1397 datum = ObjectIdGetDatum(desc->attrs[i]->atttypid);
1398 typeTup = SearchSysCache(TYPEOID, datum, 0, 0, 0);
1399 if (!HeapTupleIsValid(typeTup))
1401 char *attname = NameStr(desc->attrs[i]->attname);
1403 elog(ERROR, "plpython: Cache lookup for attribute `%s' type `%u' failed",
1404 attname, desc->attrs[i]->atttypid);
1407 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1409 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeStruct);
1411 ReleaseSysCache(typeTup);
1416 PLy_output_datum_func(PLyTypeInfo * arg, Form_pg_type typeStruct)
1420 if (arg->is_rel == 1)
1421 elog(FATAL, "plpython: PLyTypeInfo struct is initialized for a Tuple");
1423 PLy_output_datum_func2(&(arg->out.d), typeStruct);
1427 PLy_output_datum_func2(PLyObToDatum * arg, Form_pg_type typeStruct)
1431 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1432 arg->typelem = typeStruct->typelem;
1433 arg->typbyval = typeStruct->typbyval;
1437 PLy_input_datum_func(PLyTypeInfo * arg, Form_pg_type typeStruct)
1441 if (arg->is_rel == 1)
1442 elog(FATAL, "plpython: PLyTypeInfo struct is initialized for Tuple");
1444 PLy_input_datum_func2(&(arg->in.d), typeStruct);
1448 PLy_input_datum_func2(PLyDatumToOb * arg, Form_pg_type typeStruct)
1452 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1453 arg->typelem = typeStruct->typelem;
1454 arg->typbyval = typeStruct->typbyval;
1457 * hmmm, wierd. means this arg will always be converted to a python
1460 if (!OidIsValid(typeStruct->typoutput))
1462 elog(ERROR, "plpython: (FIXME) typeStruct->typoutput is invalid");
1468 type = NameStr(typeStruct->typname);
1473 if (strcasecmp("bool", type))
1475 arg->func = PLyBool_FromString;
1482 if ((strncasecmp("float", type, 5) == 0) &&
1483 ((type[5] == '8') || (type[5] == '4')))
1485 arg->func = PLyFloat_FromString;
1492 if ((strncasecmp("int", type, 3) == 0) &&
1493 ((type[3] == '4') || (type[3] == '2')) &&
1496 arg->func = PLyInt_FromString;
1499 else if (strcasecmp("int8", type) == 0)
1500 arg->func = PLyLong_FromString;
1505 if (strcasecmp("numeric", type) == 0)
1507 arg->func = PLyFloat_FromString;
1515 arg->func = PLyString_FromString;
1519 PLy_typeinfo_init(PLyTypeInfo * arg)
1522 arg->in.r.natts = arg->out.r.natts = 0;
1523 arg->in.r.atts = NULL;
1524 arg->out.r.atts = NULL;
1528 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1530 if (arg->is_rel == 1)
1533 PLy_free(arg->in.r.atts);
1534 if (arg->out.r.atts)
1535 PLy_free(arg->out.r.atts);
1539 /* assumes that a bool is always returned as a 't' or 'f'
1542 PLyBool_FromString(const char *src)
1547 return PyInt_FromLong(1);
1548 return PyInt_FromLong(0);
1552 PLyFloat_FromString(const char *src)
1560 v = strtod(src, &eptr);
1561 if ((*eptr != '\0') || (errno))
1563 return PyFloat_FromDouble(v);
1567 PLyInt_FromString(const char *src)
1575 v = strtol(src, &eptr, 0);
1576 if ((*eptr != '\0') || (errno))
1578 return PyInt_FromLong(v);
1582 PLyLong_FromString(const char *src)
1584 return PyLong_FromString((char *) src, NULL, 0);
1588 PLyString_FromString(const char *src)
1590 return PyString_FromString(src);
1594 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1597 PyObject *volatile dict;
1602 if (info->is_rel != 1)
1603 elog(FATAL, "plpython: PLyTypeInfo structure describes a datum.");
1605 dict = PyDict_New();
1607 PLy_elog(ERROR, "Unable to create tuple dictionary.");
1618 for (i = 0; i < info->in.r.natts; i++)
1627 key = NameStr(desc->attrs[i]->attname);
1628 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1630 if ((is_null) || (info->in.r.atts[i].func == NULL))
1631 PyDict_SetItemString(dict, key, Py_None);
1634 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1636 ObjectIdGetDatum(info->in.r.atts[i].typelem),
1637 Int32GetDatum(desc->attrs[i]->atttypmod));
1638 vsrc = DatumGetCString(vdat);
1641 * no exceptions allowed
1643 value = info->in.r.atts[i].func(vsrc);
1645 PyDict_SetItemString(dict, key, value);
1655 /* initialization, some python variables function declared here
1658 /* interface to postgresql elog
1660 static PyObject *PLy_debug(PyObject *, PyObject *);
1661 static PyObject *PLy_log(PyObject *, PyObject *);
1662 static PyObject *PLy_info(PyObject *, PyObject *);
1663 static PyObject *PLy_notice(PyObject *, PyObject *);
1664 static PyObject *PLy_warning(PyObject *, PyObject *);
1665 static PyObject *PLy_error(PyObject *, PyObject *);
1666 static PyObject *PLy_fatal(PyObject *, PyObject *);
1668 /* PLyPlanObject, PLyResultObject and SPI interface
1670 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1671 static PyObject *PLy_plan_new(void);
1672 static void PLy_plan_dealloc(PyObject *);
1673 static PyObject *PLy_plan_getattr(PyObject *, char *);
1674 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1676 static PyObject *PLy_result_new(void);
1677 static void PLy_result_dealloc(PyObject *);
1678 static PyObject *PLy_result_getattr(PyObject *, char *);
1681 /* Appear to be unused */
1682 static PyObject *PLy_result_fetch(PyObject *, PyObject *);
1683 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1684 static PyObject *PLy_result_status(PyObject *, PyObject *);
1686 static int PLy_result_length(PyObject *);
1687 static PyObject *PLy_result_item(PyObject *, int);
1688 static PyObject *PLy_result_slice(PyObject *, int, int);
1689 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1690 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1693 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1694 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1695 static const char *PLy_spi_error_string(int);
1696 static PyObject *PLy_spi_execute_query(char *query, int limit);
1697 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, int);
1698 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1701 static PyTypeObject PLy_PlanType = {
1702 PyObject_HEAD_INIT(NULL)
1704 "PLyPlan", /* tp_name */
1705 sizeof(PLyPlanObject), /* tp_size */
1706 0, /* tp_itemsize */
1711 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1713 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1717 0, /* tp_as_number */
1718 0, /* tp_as_sequence */
1719 0, /* tp_as_mapping */
1723 0, /* tp_getattro */
1724 0, /* tp_setattro */
1725 0, /* tp_as_buffer */
1727 PLy_plan_doc, /* tp_doc */
1730 static PyMethodDef PLy_plan_methods[] = {
1731 {"status", (PyCFunction) PLy_plan_status, METH_VARARGS, NULL},
1732 {NULL, NULL, 0, NULL}
1736 static PySequenceMethods PLy_result_as_sequence = {
1737 (inquiry) PLy_result_length, /* sq_length */
1738 (binaryfunc) 0, /* sq_concat */
1739 (intargfunc) 0, /* sq_repeat */
1740 (intargfunc) PLy_result_item, /* sq_item */
1741 (intintargfunc) PLy_result_slice, /* sq_slice */
1742 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1743 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1746 static PyTypeObject PLy_ResultType = {
1747 PyObject_HEAD_INIT(NULL)
1749 "PLyResult", /* tp_name */
1750 sizeof(PLyResultObject), /* tp_size */
1751 0, /* tp_itemsize */
1756 (destructor) PLy_result_dealloc, /* tp_dealloc */
1758 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1762 0, /* tp_as_number */
1763 &PLy_result_as_sequence, /* tp_as_sequence */
1764 0, /* tp_as_mapping */
1768 0, /* tp_getattro */
1769 0, /* tp_setattro */
1770 0, /* tp_as_buffer */
1772 PLy_result_doc, /* tp_doc */
1776 /* Appear to be unused */
1777 static PyMethodDef PLy_result_methods[] = {
1778 {"fetch", (PyCFunction) PLy_result_fetch, METH_VARARGS, NULL,},
1779 {"nrows", (PyCFunction) PLy_result_nrows, METH_VARARGS, NULL},
1780 {"status", (PyCFunction) PLy_result_status, METH_VARARGS, NULL},
1781 {NULL, NULL, 0, NULL}
1785 static PyMethodDef PLy_methods[] = {
1789 {"debug", PLy_debug, METH_VARARGS, NULL},
1790 {"log", PLy_log, METH_VARARGS, NULL},
1791 {"info", PLy_info, METH_VARARGS, NULL},
1792 {"notice", PLy_notice, METH_VARARGS, NULL},
1793 {"warning", PLy_warning, METH_VARARGS, NULL},
1794 {"error", PLy_error, METH_VARARGS, NULL},
1795 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1798 * create a stored plan
1800 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1803 * execute a plan or query
1805 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1807 {NULL, NULL, 0, NULL}
1811 /* plan object methods
1820 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1828 return (PyObject *) ob;
1833 PLy_plan_dealloc(PyObject * arg)
1835 PLyPlanObject *ob = (PLyPlanObject *) arg;
1840 SPI_freeplan(ob->plan);
1842 PLy_free(ob->types);
1847 for (i = 0; i < ob->nargs; i++)
1848 PLy_typeinfo_dealloc(&ob->args[i]);
1859 PLy_plan_getattr(PyObject * self, char *name)
1861 return Py_FindMethod(PLy_plan_methods, self, name);
1865 PLy_plan_status(PyObject * self, PyObject * args)
1867 if (PyArg_ParseTuple(args, ""))
1871 /* return PyInt_FromLong(self->status); */
1873 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1879 /* result object methods
1883 PLy_result_new(void)
1885 PLyResultObject *ob;
1889 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1892 /* ob->tuples = NULL; */
1895 ob->status = Py_None;
1896 ob->nrows = PyInt_FromLong(-1);
1897 ob->rows = PyList_New(0);
1899 return (PyObject *) ob;
1903 PLy_result_dealloc(PyObject * arg)
1905 PLyResultObject *ob = (PLyResultObject *) arg;
1909 Py_XDECREF(ob->nrows);
1910 Py_XDECREF(ob->rows);
1911 Py_XDECREF(ob->status);
1917 PLy_result_getattr(PyObject * self, char *attr)
1923 /* Appear to be unused */
1925 PLy_result_fetch(PyObject * self, PyObject * args)
1931 PLy_result_nrows(PyObject * self, PyObject * args)
1933 PLyResultObject *ob = (PLyResultObject *) self;
1935 Py_INCREF(ob->nrows);
1940 PLy_result_status(PyObject * self, PyObject * args)
1942 PLyResultObject *ob = (PLyResultObject *) self;
1944 Py_INCREF(ob->status);
1949 PLy_result_length(PyObject * arg)
1951 PLyResultObject *ob = (PLyResultObject *) arg;
1953 return PyList_Size(ob->rows);
1957 PLy_result_item(PyObject * arg, int idx)
1960 PLyResultObject *ob = (PLyResultObject *) arg;
1962 rv = PyList_GetItem(ob->rows, idx);
1969 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1972 PLyResultObject *ob = (PLyResultObject *) arg;
1975 rv = PyList_SetItem(ob->rows, idx, item);
1980 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1983 PLyResultObject *ob = (PLyResultObject *) arg;
1985 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1993 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1996 PLyResultObject *ob = (PLyResultObject *) arg;
1998 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
2005 PLy_spi_prepare(PyObject * self, PyObject * args)
2008 PLyPlanObject *plan;
2009 PyObject *list = NULL;
2010 PyObject *volatile optr = NULL;
2016 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
2018 PyErr_SetString(PLy_exc_spi_error,
2019 "Invalid arguments for plpy.prepare()");
2023 if ((list) && (!PySequence_Check(list)))
2025 PyErr_SetString(PLy_exc_spi_error,
2026 "Second argument in plpy.prepare() must be a sequence");
2031 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
2040 if (!PyErr_Occurred())
2041 PyErr_SetString(PLy_exc_spi_error,
2042 "Unknown error in PLy_spi_prepare.");
2043 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2052 nargs = PySequence_Length(list);
2055 plan->nargs = nargs;
2056 plan->types = PLy_malloc(sizeof(Oid) * nargs);
2057 plan->values = PLy_malloc(sizeof(Datum) * nargs);
2058 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
2061 * the other loop might throw an exception, if PLyTypeInfo
2062 * member isn't properly initialized the Py_DECREF(plan) will
2065 for (i = 0; i < nargs; i++)
2067 PLy_typeinfo_init(&plan->args[i]);
2068 plan->values[i] = (Datum) NULL;
2071 for (i = 0; i < nargs; i++)
2075 Form_pg_type typeStruct;
2077 optr = PySequence_GetItem(list, i);
2078 if (!PyString_Check(optr))
2080 PyErr_SetString(PLy_exc_spi_error,
2081 "Type names must be strings.");
2084 sptr = PyString_AsString(optr);
2085 /* XXX should extend this to allow qualified type names */
2086 typeTup = typenameType(makeTypeName(sptr));
2088 optr = NULL; /* this is important */
2090 plan->types[i] = HeapTupleGetOid(typeTup);
2091 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2092 if (typeStruct->typrelid == InvalidOid)
2093 PLy_output_datum_func(&plan->args[i], typeStruct);
2096 PyErr_SetString(PLy_exc_spi_error,
2097 "tuples not handled in plpy.prepare, yet.");
2100 ReleaseSysCache(typeTup);
2105 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2106 if (plan->plan == NULL)
2108 PLy_exception_set(PLy_exc_spi_error,
2109 "Unable to prepare plan. SPI_prepare failed -- %s.",
2110 PLy_spi_error_string(SPI_result));
2114 /* transfer plan from procCxt to topCxt */
2115 tmpplan = plan->plan;
2116 plan->plan = SPI_saveplan(tmpplan);
2117 SPI_freeplan(tmpplan);
2118 if (plan->plan == NULL)
2120 PLy_exception_set(PLy_exc_spi_error,
2121 "Unable to save plan. SPI_saveplan failed -- %s.",
2122 PLy_spi_error_string(SPI_result));
2128 return (PyObject *) plan;
2131 /* execute(query="select * from foo", limit=5)
2132 * execute(plan=plan, values=(foo, bar), limit=5)
2135 PLy_spi_execute(PyObject * self, PyObject * args)
2139 PyObject *list = NULL;
2147 * there should - hahaha - be an python exception set so just return
2148 * NULL. FIXME -- is this needed?
2150 if (PLy_restart_in_progress)
2154 if (PyArg_ParseTuple(args, "s|i", &query, &limit))
2155 return PLy_spi_execute_query(query, limit);
2159 if ((PyArg_ParseTuple(args, "O|Oi", &plan, &list, &limit)) &&
2160 (is_PLyPlanObject(plan)))
2162 PyObject *rv = PLy_spi_execute_plan(plan, list, limit);
2167 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2172 PLy_spi_execute_plan(PyObject * ob, PyObject * list, int limit)
2178 PLyPlanObject *plan;
2184 if ((!PySequence_Check(list)) || (PyString_Check(list)))
2186 char *msg = "plpy.execute() takes a sequence as its second argument";
2188 PyErr_SetString(PLy_exc_spi_error, msg);
2191 nargs = PySequence_Length(list);
2196 plan = (PLyPlanObject *) ob;
2198 if (nargs != plan->nargs)
2202 PyObject *so = PyObject_Str(list);
2204 sv = PyString_AsString(so);
2205 PLy_exception_set(PLy_exc_spi_error,
2206 "Expected sequence of %d arguments, got %d. %s",
2207 plan->nargs, nargs, sv);
2219 * cleanup plan->values array
2221 for (i = 0; i < nargs; i++)
2223 if (!plan->args[i].out.d.typbyval &&
2224 (plan->values[i] != (Datum) NULL))
2226 pfree(DatumGetPointer(plan->values[i]));
2227 plan->values[i] = (Datum) NULL;
2231 if (!PyErr_Occurred())
2232 PyErr_SetString(PLy_exc_error,
2233 "Unknown error in PLy_spi_execute_plan");
2234 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2240 for (i = 0; i < nargs; i++)
2246 elem = PySequence_GetItem(list, i);
2247 so = PyObject_Str(elem);
2248 sv = PyString_AsString(so);
2251 * FIXME -- if this can elog, we have leak
2253 plan->values[i] = FunctionCall3(&(plan->args[i].out.d.typfunc),
2254 CStringGetDatum(sv),
2255 ObjectIdGetDatum(plan->args[i].out.d.typelem),
2263 rv = SPI_execp(plan->plan, plan->values, NULL, limit);
2266 for (i = 0; i < nargs; i++)
2268 if (!plan->args[i].out.d.typbyval &&
2269 (plan->values[i] != (Datum) NULL))
2271 pfree(DatumGetPointer(plan->values[i]));
2272 plan->values[i] = (Datum) NULL;
2278 PLy_exception_set(PLy_exc_spi_error,
2279 "Unable to execute plan. SPI_execp failed -- %s",
2280 PLy_spi_error_string(rv));
2284 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2288 PLy_spi_execute_query(char *query, int limit)
2297 if ((!PLy_restart_in_progress) && (!PyErr_Occurred()))
2298 PyErr_SetString(PLy_exc_spi_error,
2299 "Unknown error in PLy_spi_execute_query.");
2300 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2304 rv = SPI_exec(query, limit);
2308 PLy_exception_set(PLy_exc_spi_error,
2309 "Unable to execute query. SPI_exec failed -- %s",
2310 PLy_spi_error_string(rv));
2314 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2318 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2320 PLyResultObject *result;
2324 result = (PLyResultObject *) PLy_result_new();
2325 Py_DECREF(result->status);
2326 result->status = PyInt_FromLong(status);
2328 if (status == SPI_OK_UTILITY)
2330 Py_DECREF(result->nrows);
2331 result->nrows = PyInt_FromLong(0);
2333 else if (status != SPI_OK_SELECT)
2335 Py_DECREF(result->nrows);
2336 result->nrows = PyInt_FromLong(rows);
2344 PLy_typeinfo_init(&args);
2345 Py_DECREF(result->nrows);
2346 result->nrows = PyInt_FromLong(rows);
2353 if (!PyErr_Occurred())
2354 PyErr_SetString(PLy_exc_error,
2355 "Unknown error in PLy_spi_execute_fetch_result");
2357 PLy_typeinfo_dealloc(&args);
2363 Py_DECREF(result->rows);
2364 result->rows = PyList_New(rows);
2366 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2367 for (i = 0; i < rows; i++)
2369 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2372 PyList_SetItem(result->rows, i, row);
2374 PLy_typeinfo_dealloc(&args);
2376 SPI_freetuptable(tuptable);
2381 return (PyObject *) result;
2385 PLy_spi_error_string(int code)
2389 case SPI_ERROR_TYPUNKNOWN:
2390 return "SPI_ERROR_TYPUNKNOWN";
2391 case SPI_ERROR_NOOUTFUNC:
2392 return "SPI_ERROR_NOOUTFUNC";
2393 case SPI_ERROR_NOATTRIBUTE:
2394 return "SPI_ERROR_NOATTRIBUTE";
2395 case SPI_ERROR_TRANSACTION:
2396 return "SPI_ERROR_TRANSACTION";
2397 case SPI_ERROR_PARAM:
2398 return "SPI_ERROR_PARAM";
2399 case SPI_ERROR_ARGUMENT:
2400 return "SPI_ERROR_ARGUMENT";
2401 case SPI_ERROR_CURSOR:
2402 return "SPI_ERROR_CURSOR";
2403 case SPI_ERROR_UNCONNECTED:
2404 return "SPI_ERROR_UNCONNECTED";
2405 case SPI_ERROR_OPUNKNOWN:
2406 return "SPI_ERROR_OPUNKNOWN";
2407 case SPI_ERROR_COPY:
2408 return "SPI_ERROR_COPY";
2409 case SPI_ERROR_CONNECT:
2410 return "SPI_ERROR_CONNECT";
2412 return "Unknown or Invalid code";
2415 /* language handler and interpreter initialization
2421 static volatile int init_active = 0;
2426 elog(FATAL, "plpython: Initialization of language module failed.");
2432 PLy_init_safe_interp();
2433 if (PyErr_Occurred())
2434 PLy_elog(FATAL, "Untrapped error in initialization.");
2435 PLy_procedure_cache = PyDict_New();
2436 if (PLy_procedure_cache == NULL)
2437 PLy_elog(ERROR, "Unable to create procedure cache.");
2445 PLy_init_interp(void)
2451 mainmod = PyImport_AddModule("__main__");
2452 if ((mainmod == NULL) || (PyErr_Occurred()))
2453 PLy_elog(ERROR, "Unable to import '__main__' module.");
2455 PLy_interp_globals = PyModule_GetDict(mainmod);
2457 if ((PLy_interp_globals == NULL) || (PyErr_Occurred()))
2458 PLy_elog(ERROR, "Unable to initialize globals.");
2473 * initialize plpy module
2475 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2476 plpy = Py_InitModule("plpy", PLy_methods);
2477 plpy_dict = PyModule_GetDict(plpy);
2479 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2481 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2482 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2483 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2484 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2485 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2486 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2489 * initialize main module, and add plpy
2491 main_mod = PyImport_AddModule("__main__");
2492 main_dict = PyModule_GetDict(main_mod);
2493 plpy_mod = PyImport_AddModule("plpy");
2494 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2495 if (PyErr_Occurred())
2496 elog(ERROR, "Unable to init plpy.");
2504 PLy_r_open(PyObject * self, PyObject * args)
2506 PyErr_SetString(PyExc_IOError, "can't open files in restricted mode");
2511 static PyMethodDef PLy_r_exec_methods[] = {
2512 {"r_open", (PyCFunction) PLy_r_open, METH_VARARGS, NULL},
2513 {NULL, NULL, 0, NULL}
2521 PLy_init_safe_interp(void)
2526 char *rname = "rexec";
2531 rmod = PyImport_ImportModuleEx(rname, PLy_interp_globals,
2532 PLy_interp_globals, Py_None);
2533 if ((rmod == NULL) || (PyErr_Occurred()))
2534 PLy_elog(ERROR, "Unable to import %s.", rname);
2535 PyDict_SetItemString(PLy_interp_globals, rname, rmod);
2536 PLy_interp_safe = rmod;
2538 len = sizeof(PLy_importable_modules_list) / sizeof(char *);
2539 PLy_importable_modules = build_tuple(PLy_importable_modules_list, len);
2541 len = sizeof(PLy_ok_posix_names_list) / sizeof(char *);
2542 PLy_ok_posix_names = build_tuple(PLy_ok_posix_names_list, len);
2544 len = sizeof(PLy_ok_sys_names_list) / sizeof(char *);
2545 PLy_ok_sys_names = build_tuple(PLy_ok_sys_names_list, len);
2547 PLy_interp_safe_globals = PyDict_New();
2548 if (PLy_interp_safe_globals == NULL)
2549 PLy_elog(ERROR, "Unable to create shared global dictionary.");
2552 * get an rexec.RExec class
2554 rexec = PyDict_GetItemString(PyModule_GetDict(rmod), "RExec");
2556 if (rexec == NULL || !PyClass_Check(rexec))
2557 PLy_elog(ERROR, "Unable to get RExec object.");
2560 rexec_dict = ((PyClassObject *) rexec)->cl_dict;
2563 * tweak the list of permitted modules, posix and sys functions
2565 PyDict_SetItemString(rexec_dict, "ok_builtin_modules", PLy_importable_modules);
2566 PyDict_SetItemString(rexec_dict, "ok_posix_names", PLy_ok_posix_names);
2567 PyDict_SetItemString(rexec_dict, "ok_sys_names", PLy_ok_sys_names);
2570 * change the r_open behavior
2572 if (populate_methods(rexec, PLy_r_exec_methods))
2573 PLy_elog(ERROR, "Failed to update RExec methods.");
2576 /* Helper function to build tuples from string lists */
2579 build_tuple(char *string_list[], int len)
2581 PyObject *tup = PyTuple_New(len);
2584 for (i = 0; i < len; i++)
2586 PyObject *m = PyString_FromString(string_list[i]);
2588 PyTuple_SetItem(tup, i, m);
2593 /* Helper function for populating a class with method wrappers. */
2595 populate_methods(PyObject * klass, PyMethodDef * methods)
2597 if (!klass || !methods)
2600 for (; methods->ml_name; ++methods)
2603 /* get a wrapper for the built-in function */
2604 PyObject *func = PyCFunction_New(methods, NULL);
2611 /* turn the function into an unbound method */
2612 if (!(meth = PyMethod_New(func, NULL, klass)))
2618 /* add method to dictionary */
2619 status = PyDict_SetItemString(((PyClassObject *) klass)->cl_dict,
2620 methods->ml_name, meth);
2624 /* stop now if an error occurred, otherwise do the next method */
2632 /* the python interface to the elog function
2633 * don't confuse these with PLy_elog
2635 static PyObject *PLy_output(int, PyObject *, PyObject *);
2638 PLy_debug(PyObject * self, PyObject * args)
2640 return PLy_output(DEBUG1, self, args);
2644 PLy_log(PyObject * self, PyObject * args)
2646 return PLy_output(LOG, self, args);
2650 PLy_info(PyObject * self, PyObject * args)
2652 return PLy_output(INFO, self, args);
2656 PLy_notice(PyObject * self, PyObject * args)
2658 return PLy_output(NOTICE, self, args);
2662 PLy_warning(PyObject * self, PyObject * args)
2664 return PLy_output(WARNING, self, args);
2668 PLy_error(PyObject * self, PyObject * args)
2670 return PLy_output(ERROR, self, args);
2674 PLy_fatal(PyObject * self, PyObject * args)
2676 return PLy_output(FATAL, self, args);
2681 PLy_output(volatile int level, PyObject * self, PyObject * args)
2690 elog(WARNING, "plpython, args is NULL in %s", __FUNCTION__);
2692 so = PyObject_Str(args);
2693 if ((so == NULL) || ((sv = PyString_AsString(so)) == NULL))
2696 sv = "Unable to parse error message in `plpy.elog'";
2700 * returning NULL here causes the python interpreter to bail. when
2701 * control passes back into plpython_*_handler, we check for python
2702 * exceptions and do the actual elog call. actually PLy_elog.
2706 PyErr_SetString(PLy_exc_error, sv);
2709 else if (level >= FATAL)
2711 PyErr_SetString(PLy_exc_fatal, sv);
2716 * ok, this is a WARNING, or LOG message
2718 * but just in case DON'T long jump out of the interpreter!
2728 * the real error message should already be written into the
2729 * postgresql log, no? whatever, this shouldn't happen so die
2732 elog(FATAL, "plpython: Aiieee, elog threw an unknown exception!");
2736 elog(level, "%s", sv);
2744 * return a legal object so the interpreter will continue on its merry
2751 /* Get the last procedure name called by the backend ( the innermost,
2752 * If a plpython procedure call calls the backend and the backend calls
2753 * another plpython procedure )
2757 PLy_procedure_name(PLyProcedure * proc)
2760 return "<unknown procedure>";
2761 return proc->proname;
2764 /* output a python traceback/exception via the postgresql elog
2765 * function. not pretty.
2768 static char *PLy_traceback(int *);
2769 static char *PLy_vprintf(const char *fmt, va_list ap);
2770 static char *PLy_printf(const char *fmt,...);
2773 PLy_exception_set(PyObject * exc, const char *fmt,...)
2779 vsnprintf(buf, sizeof(buf), fmt, ap);
2782 PyErr_SetString(exc, buf);
2786 PLy_elog(int elevel, const char *fmt,...)
2796 xmsg = PLy_traceback(&xlevel);
2799 emsg = PLy_vprintf(fmt, ap);
2809 * elog called siglongjmp. cleanup, restore and reraise
2811 PLy_restart_in_progress += 1;
2819 elog(elevel, "plpython: %s\n%s", emsg, xmsg);
2823 elog(elevel, "plpython: %s", emsg);
2832 PLy_traceback(int *xlevel)
2846 * get the current exception
2848 PyErr_Fetch(&e, &v, &tb);
2851 * oops, no exception, return
2859 PyErr_NormalizeException(&e, &v, &tb);
2861 eob = PyObject_Str(e);
2862 if ((v) && ((vob = PyObject_Str(v)) != NULL))
2863 vstr = PyString_AsString(vob);
2867 estr = PyString_AsString(eob);
2868 xstr = PLy_printf("%s: %s", estr, vstr);
2874 * intuit an appropriate error level for based on the exception type
2876 if ((PLy_exc_error) && (PyErr_GivenExceptionMatches(e, PLy_exc_error)))
2878 else if ((PLy_exc_fatal) && (PyErr_GivenExceptionMatches(e, PLy_exc_fatal)))
2889 PLy_printf(const char *fmt,...)
2895 emsg = PLy_vprintf(fmt, ap);
2901 PLy_vprintf(const char *fmt, va_list ap)
2908 blen = strlen(fmt) * 2;
2911 buf = PLy_malloc(blen * sizeof(char));
2915 bchar = vsnprintf(buf, blen, fmt, ap);
2916 if ((bchar > 0) && (bchar < blen))
2924 buf = PLy_realloc(buf, blen);
2930 /* python module code
2934 /* some dumb utility functions
2938 PLy_malloc(size_t bytes)
2940 void *ptr = malloc(bytes);
2943 elog(FATAL, "plpython: Memory exhausted.");
2948 PLy_realloc(void *optr, size_t bytes)
2950 void *nptr = realloc(optr, bytes);
2953 elog(FATAL, "plpython: Memory exhausted.");