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.24 2002/09/26 05:39:03 momjian 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;
416 * elog(DEBUG3, "PLy_restart_in_progress is %d",
417 * PLy_restart_in_progress);
420 proc = PLy_procedure_get(fcinfo, is_trigger);
424 HeapTuple trv = PLy_trigger_handler(fcinfo, proc);
426 retval = PointerGetDatum(trv);
429 retval = PLy_function_handler(fcinfo, proc);
440 /* trigger and function sub handlers
442 * the python function is expected to return Py_None if the tuple is
443 * acceptable and unmodified. Otherwise it should return a PyString
444 * object who's value is SKIP, or MODIFY. SKIP means don't perform
445 * this action. MODIFY means the tuple has been modified, so update
446 * tuple and perform action. SKIP and MODIFY assume the trigger fires
447 * BEFORE the event and is ROW level. postgres expects the function
448 * to take no arguments and return an argument of type trigger.
451 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
455 PyObject *volatile plargs = NULL;
456 PyObject *volatile plrv = NULL;
471 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
472 plrv = PLy_procedure_call(proc, "TD", plargs);
475 * Disconnect from SPI manager
477 if (SPI_finish() != SPI_OK_FINISH)
478 elog(ERROR, "plpython: SPI_finish failed");
481 elog(FATAL, "Aiieee, PLy_procedure_call returned NULL");
483 if (PLy_restart_in_progress)
484 elog(FATAL, "Aiieee, restart in progress not expected");
487 * return of None means we're happy with the tuple
493 if (!PyString_Check(plrv))
494 elog(ERROR, "plpython: Expected trigger to return None or a String");
496 srv = PyString_AsString(plrv);
497 if (strcasecmp(srv, "SKIP") == 0)
499 else if (strcasecmp(srv, "MODIFY") == 0)
501 TriggerData *tdata = (TriggerData *) fcinfo->context;
503 if ((TRIGGER_FIRED_BY_INSERT(tdata->tg_event)) ||
504 (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event)))
505 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
507 elog(WARNING, "plpython: Ignoring modified tuple in DELETE trigger");
509 else if (strcasecmp(srv, "OK"))
512 * hmmm, perhaps they only read the pltcl page, not a
513 * surprising thing since i've written no documentation, so
514 * accept a belated OK
516 elog(ERROR, "plpython: Expected return to be 'SKIP' or 'MODIFY'");
529 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
533 PyObject *volatile plntup;
534 PyObject *volatile plkeys;
535 PyObject *volatile platt;
536 PyObject *volatile plval;
537 PyObject *volatile plstr;
544 int *volatile modattrs;
545 Datum *volatile modvalues;
546 char *volatile modnulls;
549 plntup = plkeys = platt = plval = plstr = NULL;
577 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
578 elog(ERROR, "plpython: TD[\"new\"] deleted, unable to modify tuple");
579 if (!PyDict_Check(plntup))
580 elog(ERROR, "plpython: TD[\"new\"] is not a dictionary object");
583 plkeys = PyDict_Keys(plntup);
584 natts = PyList_Size(plkeys);
586 if (natts != proc->result.out.r.natts)
587 elog(ERROR, "plpython: TD[\"new\"] has an incorrect number of keys.");
589 modattrs = palloc(natts * sizeof(int));
590 modvalues = palloc(natts * sizeof(Datum));
591 for (i = 0; i < natts; i++)
594 modvalues[i] = (Datum) NULL;
596 modnulls = palloc(natts + 1);
597 memset(modnulls, 'n', natts);
598 modnulls[natts] = '\0';
600 tupdesc = tdata->tg_relation->rd_att;
602 for (j = 0; j < natts; j++)
606 platt = PyList_GetItem(plkeys, j);
607 if (!PyString_Check(platt))
608 elog(ERROR, "plpython: attribute is not a string");
609 attn = modattrs[j] = SPI_fnumber(tupdesc, PyString_AsString(platt));
611 if (attn == SPI_ERROR_NOATTRIBUTE)
612 elog(ERROR, "plpython: invalid attribute `%s' in tuple.",
613 PyString_AsString(platt));
616 plval = PyDict_GetItem(plntup, platt);
618 elog(FATAL, "plpython: interpreter is probably corrupted");
622 if (plval != Py_None)
624 plstr = PyObject_Str(plval);
625 src = PyString_AsString(plstr);
627 modvalues[j] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
628 CStringGetDatum(src),
629 ObjectIdGetDatum(proc->result.out.r.atts[atti].typelem),
630 Int32GetDatum(tupdesc->attrs[j]->atttypmod));
640 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts, modattrs,
641 modvalues, modnulls);
644 * FIXME -- these leak if not explicity pfree'd by other elog calls,
652 elog(ERROR, "plpython: SPI_modifytuple failed -- error %d", SPI_result);
663 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
675 PyObject *volatile pltdata = NULL;
690 tdata = (TriggerData *) fcinfo->context;
692 pltdata = PyDict_New();
694 PLy_elog(ERROR, "Unable to build arguments for trigger procedure");
696 pltname = PyString_FromString(tdata->tg_trigger->tgname);
697 PyDict_SetItemString(pltdata, "name", pltname);
700 stroid = DatumGetCString(DirectFunctionCall1(oidout,
701 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
702 pltrelid = PyString_FromString(stroid);
703 PyDict_SetItemString(pltdata, "relid", pltrelid);
709 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
710 pltwhen = PyString_FromString("BEFORE");
711 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
712 pltwhen = PyString_FromString("AFTER");
714 pltwhen = PyString_FromString("UNKNOWN");
715 PyDict_SetItemString(pltdata, "when", pltwhen);
718 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
719 pltlevel = PyString_FromString("ROW");
720 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
721 pltlevel = PyString_FromString("STATEMENT");
723 pltlevel = PyString_FromString("UNKNOWN");
724 PyDict_SetItemString(pltdata, "level", pltlevel);
727 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
729 pltevent = PyString_FromString("INSERT");
730 PyDict_SetItemString(pltdata, "old", Py_None);
731 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
732 tdata->tg_relation->rd_att);
733 PyDict_SetItemString(pltdata, "new", pytnew);
735 *rv = tdata->tg_trigtuple;
737 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
739 pltevent = PyString_FromString("DELETE");
740 PyDict_SetItemString(pltdata, "new", Py_None);
741 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
742 tdata->tg_relation->rd_att);
743 PyDict_SetItemString(pltdata, "old", pytold);
745 *rv = tdata->tg_trigtuple;
747 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
749 pltevent = PyString_FromString("UPDATE");
750 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
751 tdata->tg_relation->rd_att);
752 PyDict_SetItemString(pltdata, "new", pytnew);
754 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
755 tdata->tg_relation->rd_att);
756 PyDict_SetItemString(pltdata, "old", pytold);
758 *rv = tdata->tg_newtuple;
762 pltevent = PyString_FromString("UNKNOWN");
763 PyDict_SetItemString(pltdata, "old", Py_None);
764 PyDict_SetItemString(pltdata, "new", Py_None);
765 *rv = tdata->tg_trigtuple;
767 PyDict_SetItemString(pltdata, "event", pltevent);
770 if (tdata->tg_trigger->tgnargs)
778 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
779 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
781 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
784 * stolen, don't Py_DECREF
786 PyList_SetItem(pltargs, i, pltarg);
794 PyDict_SetItemString(pltdata, "args", pltargs);
804 /* function handler and friends
807 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
811 PyObject *volatile plargs = NULL;
812 PyObject *volatile plrv = NULL;
813 PyObject *volatile plrv_so = NULL;
819 * setup to catch elog in while building function arguments, and
820 * DECREF the plargs if the function call fails
834 plargs = PLy_function_build_args(fcinfo, proc);
835 plrv = PLy_procedure_call(proc, "args", plargs);
838 * Disconnect from SPI manager and then create the return values datum
839 * (if the input function does a palloc for it this must not be
840 * allocated in the SPI memory context because SPI_finish would free
843 if (SPI_finish() != SPI_OK_FINISH)
844 elog(ERROR, "plpython: SPI_finish failed");
848 elog(FATAL, "Aiieee, PLy_procedure_call returned NULL");
850 if (!PLy_restart_in_progress)
851 PLy_elog(ERROR, "plpython: Function \"%s\" failed.", proc->proname);
854 * FIXME is this dead code? i'm pretty sure it is for unnested
855 * calls, but not for nested calls
862 * convert the python PyObject to a postgresql Datum FIXME returning a
863 * NULL, ie PG_RETURN_NULL() blows the backend to small messy bits...
864 * it this a bug or expected? so just call with the string value of
870 fcinfo->isnull = true;
875 fcinfo->isnull = false;
876 plrv_so = PyObject_Str(plrv);
877 plrv_sc = PyString_AsString(plrv_so);
878 rv = FunctionCall3(&proc->result.out.d.typfunc,
879 PointerGetDatum(plrv_sc),
880 ObjectIdGetDatum(proc->result.out.d.typelem),
894 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
897 PLyProcedure *current;
901 current = PLy_last_procedure;
902 PLy_last_procedure = proc;
903 PyDict_SetItemString(proc->globals, kargs, vargs);
904 rv = PyObject_CallFunction(proc->reval, "O", proc->code);
905 PLy_last_procedure = current;
907 if ((rv == NULL) || (PyErr_Occurred()))
910 if (!PLy_restart_in_progress)
911 PLy_elog(ERROR, "Call of function `%s' failed.", proc->proname);
919 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
922 PyObject *volatile arg = NULL;
923 PyObject *volatile args = NULL;
929 * FIXME -- if the setjmp setup is expensive, add the arg and args
930 * field to the procedure struct and cleanup at the start of the next
943 args = PyList_New(proc->nargs);
944 for (i = 0; i < proc->nargs; i++)
946 if (proc->args[i].is_rel == 1)
948 TupleTableSlot *slot = (TupleTableSlot *) fcinfo->arg[i];
950 arg = PLyDict_FromTuple(&(proc->args[i]), slot->val,
951 slot->ttc_tupleDescriptor);
955 if (!fcinfo->argnull[i])
960 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
962 ObjectIdGetDatum(proc->args[i].in.d.typelem),
964 ct = DatumGetCString(dt);
965 arg = (proc->args[i].in.d.func) (ct);
979 * FIXME -- error check this
981 PyList_SetItem(args, i, arg);
990 /* PLyProcedure functions
992 static PLyProcedure *
993 PLy_procedure_get(FunctionCallInfo fcinfo, bool is_trigger)
999 PLyProcedure *proc = NULL;
1004 fn_oid = fcinfo->flinfo->fn_oid;
1005 procTup = SearchSysCache(PROCOID,
1006 ObjectIdGetDatum(fn_oid),
1008 if (!HeapTupleIsValid(procTup))
1009 elog(ERROR, "plpython: cache lookup for procedure %u failed", fn_oid);
1011 rv = snprintf(key, sizeof(key), "%u%s",
1013 is_trigger ? "_trigger" : "");
1014 if ((rv >= sizeof(key)) || (rv < 0))
1015 elog(FATAL, "plpython: Buffer overrun in %s:%d", __FILE__, __LINE__);
1017 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
1022 if (!PyCObject_Check(plproc))
1023 elog(FATAL, "plpython: Expected a PyCObject, didn't get one");
1027 proc = PyCObject_AsVoidPtr(plproc);
1028 if (proc->me != plproc)
1029 elog(FATAL, "plpython: Aiieee, proc->me != plproc");
1030 /* did we find an up-to-date cache entry? */
1031 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
1032 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
1040 proc = PLy_procedure_create(fcinfo, is_trigger, procTup, key);
1042 ReleaseSysCache(procTup);
1047 static PLyProcedure *
1048 PLy_procedure_create(FunctionCallInfo fcinfo, bool is_trigger,
1049 HeapTuple procTup, char *key)
1054 Form_pg_proc procStruct;
1055 PLyProcedure *volatile proc;
1056 char *volatile procSource = NULL;
1063 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1065 rv = snprintf(procName, sizeof(procName),
1066 "__plpython_procedure_%s_%u%s",
1067 NameStr(procStruct->proname),
1068 fcinfo->flinfo->fn_oid,
1069 is_trigger ? "_trigger" : "");
1070 if ((rv >= sizeof(procName)) || (rv < 0))
1071 elog(FATAL, "plpython: Procedure name would overrun buffer");
1073 proc = PLy_malloc(sizeof(PLyProcedure));
1074 proc->proname = PLy_malloc(strlen(procName) + 1);
1075 strcpy(proc->proname, procName);
1076 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1077 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1078 PLy_typeinfo_init(&proc->result);
1079 for (i = 0; i < FUNC_MAX_ARGS; i++)
1080 PLy_typeinfo_init(&proc->args[i]);
1082 proc->code = proc->interp = proc->reval = proc->statics = NULL;
1083 proc->globals = proc->me = NULL;
1089 PLy_procedure_delete(proc);
1096 * get information required for output conversion of the return value,
1097 * but only if this isn't a trigger.
1101 HeapTuple rvTypeTup;
1102 Form_pg_type rvTypeStruct;
1105 rvDatum = ObjectIdGetDatum(procStruct->prorettype);
1106 rvTypeTup = SearchSysCache(TYPEOID, rvDatum, 0, 0, 0);
1107 if (!HeapTupleIsValid(rvTypeTup))
1108 elog(ERROR, "plpython: cache lookup for type \"%u\" failed",
1109 procStruct->prorettype);
1111 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1112 if (rvTypeStruct->typrelid == InvalidOid)
1113 PLy_output_datum_func(&proc->result, rvTypeStruct);
1115 elog(ERROR, "plpython: tuple return types not supported, yet");
1117 ReleaseSysCache(rvTypeTup);
1122 * input/output conversion for trigger tuples. use the result
1123 * TypeInfo variable to store the tuple conversion info.
1125 TriggerData *tdata = (TriggerData *) fcinfo->context;
1127 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1128 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1132 * now get information required for input conversion of the procedures
1135 proc->nargs = fcinfo->nargs;
1136 for (i = 0; i < fcinfo->nargs; i++)
1138 HeapTuple argTypeTup;
1139 Form_pg_type argTypeStruct;
1142 argDatum = ObjectIdGetDatum(procStruct->proargtypes[i]);
1143 argTypeTup = SearchSysCache(TYPEOID, argDatum, 0, 0, 0);
1144 if (!HeapTupleIsValid(argTypeTup))
1145 elog(ERROR, "plpython: cache lookup for type \"%u\" failed",
1146 procStruct->proargtypes[i]);
1147 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1149 if (argTypeStruct->typrelid == InvalidOid)
1150 PLy_input_datum_func(&(proc->args[i]), argTypeStruct);
1153 TupleTableSlot *slot = (TupleTableSlot *) fcinfo->arg[i];
1155 PLy_input_tuple_funcs(&(proc->args[i]),
1156 slot->ttc_tupleDescriptor);
1159 ReleaseSysCache(argTypeTup);
1164 * get the text of the function.
1166 procDatum = DirectFunctionCall1(textout,
1167 PointerGetDatum(&procStruct->prosrc));
1168 procSource = DatumGetCString(procDatum);
1170 PLy_procedure_compile(proc, procSource);
1174 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1175 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1183 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1192 * get an instance of rexec.RExec for the function
1194 proc->interp = PyObject_CallMethod(PLy_interp_safe, "RExec", NULL);
1195 if ((proc->interp == NULL) || (PyErr_Occurred()))
1196 PLy_elog(ERROR, "Unable to create rexec.RExec instance");
1198 proc->reval = PyObject_GetAttrString(proc->interp, "r_eval");
1199 if ((proc->reval == NULL) || (PyErr_Occurred()))
1200 PLy_elog(ERROR, "Unable to get method `r_eval' from rexec.RExec");
1203 * add a __main__ module to the function's interpreter
1205 module = PyObject_CallMethod(proc->interp, "add_module", "s", "__main__");
1206 if ((module == NULL) || (PyErr_Occurred()))
1207 PLy_elog(ERROR, "Unable to get module `__main__' from rexec.RExec");
1210 * add plpy module to the interpreters main dictionary
1212 proc->globals = PyModule_GetDict(module);
1213 if ((proc->globals == NULL) || (PyErr_Occurred()))
1214 PLy_elog(ERROR, "Unable to get `__main__.__dict__' from rexec.RExec");
1217 * why the hell won't r_import or r_exec('import plpy') work?
1219 module = PyDict_GetItemString(PLy_interp_globals, "plpy");
1220 if ((module == NULL) || (PyErr_Occurred()))
1221 PLy_elog(ERROR, "Unable to get `plpy'");
1223 PyDict_SetItemString(proc->globals, "plpy", module);
1226 * SD is private preserved data between calls GD is global data shared
1229 proc->statics = PyDict_New();
1230 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1231 PyDict_SetItemString(proc->globals, "GD", PLy_interp_safe_globals);
1234 * insert the function code into the interpreter
1236 msrc = PLy_procedure_munge_source(proc->proname, src);
1237 crv = PyObject_CallMethod(proc->interp, "r_exec", "s", msrc);
1240 if ((crv != NULL) && (!PyErr_Occurred()))
1248 * compile a call to the function
1250 clen = snprintf(call, sizeof(call), "%s()", proc->proname);
1251 if ((clen < 0) || (clen >= sizeof(call)))
1252 elog(ERROR, "plpython: string would overflow buffer.");
1253 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1254 if ((proc->code != NULL) && (!PyErr_Occurred()))
1260 PLy_elog(ERROR, "Unable to compile function %s", proc->proname);
1264 PLy_procedure_munge_source(const char *name, const char *src)
1275 * room for function source and the def statement
1277 mlen = (strlen(src) * 2) + strlen(name) + 16;
1279 mrc = PLy_malloc(mlen);
1280 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1281 if ((plen < 0) || (plen >= mlen))
1282 elog(FATAL, "Aiieee, impossible buffer overrun (or snprintf failure)");
1301 if (mp > (mrc + mlen))
1302 elog(FATAL, "plpython: Buffer overrun in PLy_munge_source");
1308 PLy_procedure_delete(PLyProcedure * proc)
1314 Py_XDECREF(proc->code);
1315 Py_XDECREF(proc->interp);
1316 Py_XDECREF(proc->reval);
1317 Py_XDECREF(proc->statics);
1318 Py_XDECREF(proc->globals);
1319 Py_XDECREF(proc->me);
1321 PLy_free(proc->proname);
1322 for (i = 0; i < proc->nargs; i++)
1323 if (proc->args[i].is_rel == 1)
1325 if (proc->args[i].in.r.atts)
1326 PLy_free(proc->args[i].in.r.atts);
1327 if (proc->args[i].out.r.atts)
1328 PLy_free(proc->args[i].out.r.atts);
1334 /* conversion functions. remember output from python is
1335 * input to postgresql, and vis versa.
1338 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1345 if (arg->is_rel == 0)
1346 elog(FATAL, "plpython: PLyTypeInfo struct is initialized for a Datum");
1349 arg->in.r.natts = desc->natts;
1350 arg->in.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1352 for (i = 0; i < desc->natts; i++)
1355 Form_pg_type typeStruct;
1357 datum = ObjectIdGetDatum(desc->attrs[i]->atttypid);
1358 typeTup = SearchSysCache(TYPEOID, datum, 0, 0, 0);
1359 if (!HeapTupleIsValid(typeTup))
1361 char *attname = NameStr(desc->attrs[i]->attname);
1363 elog(ERROR, "plpython: Cache lookup for attribute `%s' type `%u' failed",
1364 attname, desc->attrs[i]->atttypid);
1367 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1369 PLy_input_datum_func2(&(arg->in.r.atts[i]), typeStruct);
1371 ReleaseSysCache(typeTup);
1376 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1383 if (arg->is_rel == 0)
1384 elog(FATAL, "plpython: PLyTypeInfo struct is initialized for a Datum");
1387 arg->out.r.natts = desc->natts;
1388 arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1390 for (i = 0; i < desc->natts; i++)
1393 Form_pg_type typeStruct;
1395 datum = ObjectIdGetDatum(desc->attrs[i]->atttypid);
1396 typeTup = SearchSysCache(TYPEOID, datum, 0, 0, 0);
1397 if (!HeapTupleIsValid(typeTup))
1399 char *attname = NameStr(desc->attrs[i]->attname);
1401 elog(ERROR, "plpython: Cache lookup for attribute `%s' type `%u' failed",
1402 attname, desc->attrs[i]->atttypid);
1405 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1407 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeStruct);
1409 ReleaseSysCache(typeTup);
1414 PLy_output_datum_func(PLyTypeInfo * arg, Form_pg_type typeStruct)
1418 if (arg->is_rel == 1)
1419 elog(FATAL, "plpython: PLyTypeInfo struct is initialized for a Tuple");
1421 PLy_output_datum_func2(&(arg->out.d), typeStruct);
1425 PLy_output_datum_func2(PLyObToDatum * arg, Form_pg_type typeStruct)
1429 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1430 arg->typelem = typeStruct->typelem;
1431 arg->typbyval = typeStruct->typbyval;
1435 PLy_input_datum_func(PLyTypeInfo * arg, Form_pg_type typeStruct)
1439 if (arg->is_rel == 1)
1440 elog(FATAL, "plpython: PLyTypeInfo struct is initialized for Tuple");
1442 PLy_input_datum_func2(&(arg->in.d), typeStruct);
1446 PLy_input_datum_func2(PLyDatumToOb * arg, Form_pg_type typeStruct)
1450 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1451 arg->typelem = typeStruct->typelem;
1452 arg->typbyval = typeStruct->typbyval;
1455 * hmmm, wierd. means this arg will always be converted to a python
1458 if (!OidIsValid(typeStruct->typoutput))
1460 elog(ERROR, "plpython: (FIXME) typeStruct->typoutput is invalid");
1466 type = NameStr(typeStruct->typname);
1471 if (strcasecmp("bool", type))
1473 arg->func = PLyBool_FromString;
1480 if ((strncasecmp("float", type, 5) == 0) &&
1481 ((type[5] == '8') || (type[5] == '4')))
1483 arg->func = PLyFloat_FromString;
1490 if ((strncasecmp("int", type, 3) == 0) &&
1491 ((type[3] == '4') || (type[3] == '2')) &&
1494 arg->func = PLyInt_FromString;
1497 else if (strcasecmp("int8", type) == 0)
1498 arg->func = PLyLong_FromString;
1503 if (strcasecmp("numeric", type) == 0)
1505 arg->func = PLyFloat_FromString;
1513 arg->func = PLyString_FromString;
1517 PLy_typeinfo_init(PLyTypeInfo * arg)
1520 arg->in.r.natts = arg->out.r.natts = 0;
1521 arg->in.r.atts = NULL;
1522 arg->out.r.atts = NULL;
1526 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1528 if (arg->is_rel == 1)
1531 PLy_free(arg->in.r.atts);
1532 if (arg->out.r.atts)
1533 PLy_free(arg->out.r.atts);
1537 /* assumes that a bool is always returned as a 't' or 'f'
1540 PLyBool_FromString(const char *src)
1545 return PyInt_FromLong(1);
1546 return PyInt_FromLong(0);
1550 PLyFloat_FromString(const char *src)
1558 v = strtod(src, &eptr);
1559 if ((*eptr != '\0') || (errno))
1561 return PyFloat_FromDouble(v);
1565 PLyInt_FromString(const char *src)
1573 v = strtol(src, &eptr, 0);
1574 if ((*eptr != '\0') || (errno))
1576 return PyInt_FromLong(v);
1580 PLyLong_FromString(const char *src)
1582 return PyLong_FromString((char *) src, NULL, 0);
1586 PLyString_FromString(const char *src)
1588 return PyString_FromString(src);
1592 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1595 PyObject *volatile dict;
1600 if (info->is_rel != 1)
1601 elog(FATAL, "plpython: PLyTypeInfo structure describes a datum.");
1603 dict = PyDict_New();
1605 PLy_elog(ERROR, "Unable to create tuple dictionary.");
1616 for (i = 0; i < info->in.r.natts; i++)
1625 key = NameStr(desc->attrs[i]->attname);
1626 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1628 if ((is_null) || (info->in.r.atts[i].func == NULL))
1629 PyDict_SetItemString(dict, key, Py_None);
1632 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1634 ObjectIdGetDatum(info->in.r.atts[i].typelem),
1635 Int32GetDatum(desc->attrs[i]->atttypmod));
1636 vsrc = DatumGetCString(vdat);
1639 * no exceptions allowed
1641 value = info->in.r.atts[i].func(vsrc);
1643 PyDict_SetItemString(dict, key, value);
1653 /* initialization, some python variables function declared here
1656 /* interface to postgresql elog
1658 static PyObject *PLy_debug(PyObject *, PyObject *);
1659 static PyObject *PLy_log(PyObject *, PyObject *);
1660 static PyObject *PLy_info(PyObject *, PyObject *);
1661 static PyObject *PLy_notice(PyObject *, PyObject *);
1662 static PyObject *PLy_warning(PyObject *, PyObject *);
1663 static PyObject *PLy_error(PyObject *, PyObject *);
1664 static PyObject *PLy_fatal(PyObject *, PyObject *);
1666 /* PLyPlanObject, PLyResultObject and SPI interface
1668 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1669 static PyObject *PLy_plan_new(void);
1670 static void PLy_plan_dealloc(PyObject *);
1671 static PyObject *PLy_plan_getattr(PyObject *, char *);
1672 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1674 static PyObject *PLy_result_new(void);
1675 static void PLy_result_dealloc(PyObject *);
1676 static PyObject *PLy_result_getattr(PyObject *, char *);
1679 /* Appear to be unused */
1680 static PyObject *PLy_result_fetch(PyObject *, PyObject *);
1681 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1682 static PyObject *PLy_result_status(PyObject *, PyObject *);
1684 static int PLy_result_length(PyObject *);
1685 static PyObject *PLy_result_item(PyObject *, int);
1686 static PyObject *PLy_result_slice(PyObject *, int, int);
1687 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1688 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1691 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1692 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1693 static const char *PLy_spi_error_string(int);
1694 static PyObject *PLy_spi_execute_query(char *query, int limit);
1695 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, int);
1696 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1699 static PyTypeObject PLy_PlanType = {
1700 PyObject_HEAD_INIT(NULL)
1702 "PLyPlan", /* tp_name */
1703 sizeof(PLyPlanObject), /* tp_size */
1704 0, /* tp_itemsize */
1709 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1711 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1715 0, /* tp_as_number */
1716 0, /* tp_as_sequence */
1717 0, /* tp_as_mapping */
1721 0, /* tp_getattro */
1722 0, /* tp_setattro */
1723 0, /* tp_as_buffer */
1725 PLy_plan_doc, /* tp_doc */
1728 static PyMethodDef PLy_plan_methods[] = {
1729 {"status", (PyCFunction) PLy_plan_status, METH_VARARGS, NULL},
1730 {NULL, NULL, 0, NULL}
1734 static PySequenceMethods PLy_result_as_sequence = {
1735 (inquiry) PLy_result_length, /* sq_length */
1736 (binaryfunc) 0, /* sq_concat */
1737 (intargfunc) 0, /* sq_repeat */
1738 (intargfunc) PLy_result_item, /* sq_item */
1739 (intintargfunc) PLy_result_slice, /* sq_slice */
1740 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1741 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1744 static PyTypeObject PLy_ResultType = {
1745 PyObject_HEAD_INIT(NULL)
1747 "PLyResult", /* tp_name */
1748 sizeof(PLyResultObject), /* tp_size */
1749 0, /* tp_itemsize */
1754 (destructor) PLy_result_dealloc, /* tp_dealloc */
1756 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1760 0, /* tp_as_number */
1761 &PLy_result_as_sequence, /* tp_as_sequence */
1762 0, /* tp_as_mapping */
1766 0, /* tp_getattro */
1767 0, /* tp_setattro */
1768 0, /* tp_as_buffer */
1770 PLy_result_doc, /* tp_doc */
1774 /* Appear to be unused */
1775 static PyMethodDef PLy_result_methods[] = {
1776 {"fetch", (PyCFunction) PLy_result_fetch, METH_VARARGS, NULL,},
1777 {"nrows", (PyCFunction) PLy_result_nrows, METH_VARARGS, NULL},
1778 {"status", (PyCFunction) PLy_result_status, METH_VARARGS, NULL},
1779 {NULL, NULL, 0, NULL}
1783 static PyMethodDef PLy_methods[] = {
1787 {"debug", PLy_debug, METH_VARARGS, NULL},
1788 {"log", PLy_log, METH_VARARGS, NULL},
1789 {"info", PLy_info, METH_VARARGS, NULL},
1790 {"notice", PLy_notice, METH_VARARGS, NULL},
1791 {"warning", PLy_warning, METH_VARARGS, NULL},
1792 {"error", PLy_error, METH_VARARGS, NULL},
1793 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1796 * create a stored plan
1798 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1801 * execute a plan or query
1803 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1805 {NULL, NULL, 0, NULL}
1809 /* plan object methods
1818 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1826 return (PyObject *) ob;
1831 PLy_plan_dealloc(PyObject * arg)
1833 PLyPlanObject *ob = (PLyPlanObject *) arg;
1840 * free the plan... pfree(ob->plan);
1842 * FIXME -- leaks saved plan on object destruction. can this be
1847 PLy_free(ob->types);
1852 for (i = 0; i < ob->nargs; i++)
1853 PLy_typeinfo_dealloc(&ob->args[i]);
1864 PLy_plan_getattr(PyObject * self, char *name)
1866 return Py_FindMethod(PLy_plan_methods, self, name);
1870 PLy_plan_status(PyObject * self, PyObject * args)
1872 if (PyArg_ParseTuple(args, ""))
1876 /* return PyInt_FromLong(self->status); */
1878 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1884 /* result object methods
1888 PLy_result_new(void)
1890 PLyResultObject *ob;
1894 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1897 /* ob->tuples = NULL; */
1900 ob->status = Py_None;
1901 ob->nrows = PyInt_FromLong(-1);
1902 ob->rows = PyList_New(0);
1904 return (PyObject *) ob;
1908 PLy_result_dealloc(PyObject * arg)
1910 PLyResultObject *ob = (PLyResultObject *) arg;
1914 Py_XDECREF(ob->nrows);
1915 Py_XDECREF(ob->rows);
1916 Py_XDECREF(ob->status);
1922 PLy_result_getattr(PyObject * self, char *attr)
1928 /* Appear to be unused */
1930 PLy_result_fetch(PyObject * self, PyObject * args)
1936 PLy_result_nrows(PyObject * self, PyObject * args)
1938 PLyResultObject *ob = (PLyResultObject *) self;
1940 Py_INCREF(ob->nrows);
1945 PLy_result_status(PyObject * self, PyObject * args)
1947 PLyResultObject *ob = (PLyResultObject *) self;
1949 Py_INCREF(ob->status);
1954 PLy_result_length(PyObject * arg)
1956 PLyResultObject *ob = (PLyResultObject *) arg;
1958 return PyList_Size(ob->rows);
1962 PLy_result_item(PyObject * arg, int idx)
1965 PLyResultObject *ob = (PLyResultObject *) arg;
1967 rv = PyList_GetItem(ob->rows, idx);
1974 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1977 PLyResultObject *ob = (PLyResultObject *) arg;
1980 rv = PyList_SetItem(ob->rows, idx, item);
1985 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1988 PLyResultObject *ob = (PLyResultObject *) arg;
1990 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1998 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
2001 PLyResultObject *ob = (PLyResultObject *) arg;
2003 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
2010 PLy_spi_prepare(PyObject * self, PyObject * args)
2013 PLyPlanObject *plan;
2014 PyObject *list = NULL;
2015 PyObject *volatile optr = NULL;
2020 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
2022 PyErr_SetString(PLy_exc_spi_error,
2023 "Invalid arguments for plpy.prepare()");
2027 if ((list) && (!PySequence_Check(list)))
2029 PyErr_SetString(PLy_exc_spi_error,
2030 "Second argument in plpy.prepare() must be a sequence");
2035 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
2044 if (!PyErr_Occurred())
2045 PyErr_SetString(PLy_exc_spi_error,
2046 "Unknown error in PLy_spi_prepare.");
2047 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2057 nargs = PySequence_Length(list);
2060 plan->nargs = nargs;
2061 plan->types = PLy_malloc(sizeof(Oid) * nargs);
2062 plan->values = PLy_malloc(sizeof(Datum) * nargs);
2063 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
2066 * the other loop might throw an exception, if PLyTypeInfo
2067 * member isn't properly initialized the Py_DECREF(plan) will
2070 for (i = 0; i < nargs; i++)
2072 PLy_typeinfo_init(&plan->args[i]);
2073 plan->values[i] = (Datum) NULL;
2076 for (i = 0; i < nargs; i++)
2080 Form_pg_type typeStruct;
2082 optr = PySequence_GetItem(list, i);
2083 if (!PyString_Check(optr))
2085 PyErr_SetString(PLy_exc_spi_error,
2086 "Type names must be strings.");
2089 sptr = PyString_AsString(optr);
2090 /* XXX should extend this to allow qualified type names */
2091 typeTup = typenameType(makeTypeName(sptr));
2093 optr = NULL; /* this is important */
2095 plan->types[i] = HeapTupleGetOid(typeTup);
2096 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2097 if (typeStruct->typrelid == InvalidOid)
2098 PLy_output_datum_func(&plan->args[i], typeStruct);
2101 PyErr_SetString(PLy_exc_spi_error,
2102 "tuples not handled in plpy.prepare, yet.");
2105 ReleaseSysCache(typeTup);
2110 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2111 if (plan->plan == NULL)
2113 PLy_exception_set(PLy_exc_spi_error,
2114 "Unable to prepare plan. SPI_prepare failed -- %s.",
2115 PLy_spi_error_string(SPI_result));
2119 plan->plan = SPI_saveplan(plan->plan);
2120 if (plan->plan == NULL)
2122 PLy_exception_set(PLy_exc_spi_error,
2123 "Unable to save plan. SPI_saveplan failed -- %s.",
2124 PLy_spi_error_string(SPI_result));
2130 return (PyObject *) plan;
2133 /* execute(query="select * from foo", limit=5)
2134 * execute(plan=plan, values=(foo, bar), limit=5)
2137 PLy_spi_execute(PyObject * self, PyObject * args)
2141 PyObject *list = NULL;
2149 * there should - hahaha - be an python exception set so just return
2150 * NULL. FIXME -- is this needed?
2152 if (PLy_restart_in_progress)
2156 if (PyArg_ParseTuple(args, "s|i", &query, &limit))
2157 return PLy_spi_execute_query(query, limit);
2161 if ((PyArg_ParseTuple(args, "O|Oi", &plan, &list, &limit)) &&
2162 (is_PLyPlanObject(plan)))
2164 PyObject *rv = PLy_spi_execute_plan(plan, list, limit);
2169 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2174 PLy_spi_execute_plan(PyObject * ob, PyObject * list, int limit)
2180 PLyPlanObject *plan;
2186 if ((!PySequence_Check(list)) || (PyString_Check(list)))
2188 char *msg = "plpy.execute() takes a sequence as its second argument";
2190 PyErr_SetString(PLy_exc_spi_error, msg);
2193 nargs = PySequence_Length(list);
2198 plan = (PLyPlanObject *) ob;
2200 if (nargs != plan->nargs)
2204 PyObject *so = PyObject_Str(list);
2206 sv = PyString_AsString(so);
2207 PLy_exception_set(PLy_exc_spi_error,
2208 "Expected sequence of %d arguments, got %d. %s",
2209 plan->nargs, nargs, sv);
2221 * cleanup plan->values array
2223 for (i = 0; i < nargs; i++)
2225 if (!plan->args[i].out.d.typbyval &&
2226 (plan->values[i] != (Datum) NULL))
2228 pfree(DatumGetPointer(plan->values[i]));
2229 plan->values[i] = (Datum) NULL;
2233 if (!PyErr_Occurred())
2234 PyErr_SetString(PLy_exc_error,
2235 "Unknown error in PLy_spi_execute_plan");
2236 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2242 for (i = 0; i < nargs; i++)
2248 elem = PySequence_GetItem(list, i);
2249 so = PyObject_Str(elem);
2250 sv = PyString_AsString(so);
2253 * FIXME -- if this can elog, we have leak
2255 plan->values[i] = FunctionCall3(&(plan->args[i].out.d.typfunc),
2256 CStringGetDatum(sv),
2257 ObjectIdGetDatum(plan->args[i].out.d.typelem),
2265 rv = SPI_execp(plan->plan, plan->values, NULL, limit);
2268 for (i = 0; i < nargs; i++)
2270 if (!plan->args[i].out.d.typbyval &&
2271 (plan->values[i] != (Datum) NULL))
2273 pfree(DatumGetPointer(plan->values[i]));
2274 plan->values[i] = (Datum) NULL;
2280 PLy_exception_set(PLy_exc_spi_error,
2281 "Unable to execute plan. SPI_execp failed -- %s",
2282 PLy_spi_error_string(rv));
2286 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2290 PLy_spi_execute_query(char *query, int limit)
2299 if ((!PLy_restart_in_progress) && (!PyErr_Occurred()))
2300 PyErr_SetString(PLy_exc_spi_error,
2301 "Unknown error in PLy_spi_execute_query.");
2302 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2306 rv = SPI_exec(query, limit);
2310 PLy_exception_set(PLy_exc_spi_error,
2311 "Unable to execute query. SPI_exec failed -- %s",
2312 PLy_spi_error_string(rv));
2316 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2320 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2322 PLyResultObject *result;
2326 result = (PLyResultObject *) PLy_result_new();
2327 Py_DECREF(result->status);
2328 result->status = PyInt_FromLong(status);
2330 if (status == SPI_OK_UTILITY)
2332 Py_DECREF(result->nrows);
2333 result->nrows = PyInt_FromLong(0);
2335 else if (status != SPI_OK_SELECT)
2337 Py_DECREF(result->nrows);
2338 result->nrows = PyInt_FromLong(rows);
2346 PLy_typeinfo_init(&args);
2347 Py_DECREF(result->nrows);
2348 result->nrows = PyInt_FromLong(rows);
2355 if (!PyErr_Occurred())
2356 PyErr_SetString(PLy_exc_error,
2357 "Unknown error in PLy_spi_execute_fetch_result");
2359 PLy_typeinfo_dealloc(&args);
2365 Py_DECREF(result->rows);
2366 result->rows = PyList_New(rows);
2368 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2369 for (i = 0; i < rows; i++)
2371 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2374 PyList_SetItem(result->rows, i, row);
2376 PLy_typeinfo_dealloc(&args);
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!");
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.");