1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.93 2007/01/28 19:36:46 adunstan Exp $
6 *********************************************************************
9 #if defined(_MSC_VER) && defined(_DEBUG)
10 /* Python uses #pragma to bring in a non-default libpython on VC++ if
11 * _DEBUG is defined */
13 /* Also hide away errcode, since we load Python.h before postgres.h */
14 #define errcode __msvc_errcode
18 #elif defined (_MSC_VER)
19 #define errcode __msvc_errcode
32 /* postgreSQL stuff */
33 #include "access/heapam.h"
34 #include "catalog/pg_proc.h"
35 #include "catalog/pg_type.h"
36 #include "commands/trigger.h"
37 #include "executor/spi.h"
40 #include "nodes/makefuncs.h"
41 #include "parser/parse_type.h"
42 #include "tcop/tcopprot.h"
43 #include "utils/builtins.h"
44 #include "utils/lsyscache.h"
45 #include "utils/memutils.h"
46 #include "utils/syscache.h"
47 #include "utils/typcache.h"
54 /* convert Postgresql Datum or tuple into a PyObject.
55 * input to Python. Tuples are converted to dictionary
59 typedef PyObject *(*PLyDatumToObFunc) (const char *);
61 typedef struct PLyDatumToOb
63 PLyDatumToObFunc func;
69 typedef struct PLyTupleToOb
75 typedef union PLyTypeInput
81 /* convert PyObject to a Postgresql Datum or tuple.
84 typedef struct PLyObToDatum
86 FmgrInfo typfunc; /* The type's input function */
87 Oid typoid; /* The OID of the type */
92 typedef struct PLyObToTuple
98 typedef union PLyTypeOutput
104 /* all we need to move Postgresql data to Python objects,
107 typedef struct PLyTypeInfo
114 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
115 * 1 rowtype 2 rowtype, but I/O functions not set up yet
120 /* cached procedure data */
121 typedef struct PLyProcedure
123 char *proname; /* SQL name of procedure */
124 char *pyname; /* Python name of procedure */
125 TransactionId fn_xmin;
128 PLyTypeInfo result; /* also used to store info for trigger tuple
130 bool is_setof; /* true, if procedure returns result set */
131 PyObject *setof; /* contents of result set. */
132 char **argnames; /* Argument names */
133 PLyTypeInfo args[FUNC_MAX_ARGS];
135 PyObject *code; /* compiled procedure code */
136 PyObject *statics; /* data saved across calls, local scope */
137 PyObject *globals; /* data saved across calls, global scope */
138 PyObject *me; /* PyCObject containing pointer to this
144 typedef struct PLyPlanObject
147 void *plan; /* return of an SPI_saveplan */
154 typedef struct PLyResultObject
157 /* HeapTuple *tuples; */
158 PyObject * nrows; /* number of rows returned by query */
159 PyObject *rows; /* data rows, or None if no data returned */
160 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
164 /* function declarations */
166 /* Two exported functions: first is the magic telling Postgresql
167 * what function call interface it implements. Second is for
168 * initialization of the interpreter during library load.
170 Datum plpython_call_handler(PG_FUNCTION_ARGS);
173 PG_FUNCTION_INFO_V1(plpython_call_handler);
175 /* most of the remaining of the declarations, all static */
177 /* these should only be called once at the first call
178 * of plpython_call_handler. initialize the python interpreter
181 static void PLy_init_interp(void);
182 static void PLy_init_plpy(void);
184 /* call PyErr_SetString with a vprint interface */
186 PLy_exception_set(PyObject *, const char *,...)
187 __attribute__((format(printf, 2, 3)));
189 /* Get the innermost python procedure called from the backend */
190 static char *PLy_procedure_name(PLyProcedure *);
192 /* some utility functions */
193 static void PLy_elog(int, const char *,...);
194 static char *PLy_traceback(int *);
195 static char *PLy_vprintf(const char *fmt, va_list ap);
196 static char *PLy_printf(const char *fmt,...);
198 static void *PLy_malloc(size_t);
199 static void *PLy_realloc(void *, size_t);
200 static char *PLy_strdup(const char *);
201 static void PLy_free(void *);
203 /* sub handlers for functions and triggers */
204 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
205 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
207 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
208 static void PLy_function_delete_args(PLyProcedure *);
209 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
211 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
212 TriggerData *, HeapTuple);
214 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
216 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
219 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
221 HeapTuple procTup, char *key);
223 static void PLy_procedure_compile(PLyProcedure *, const char *);
224 static char *PLy_procedure_munge_source(const char *, const char *);
225 static void PLy_procedure_delete(PLyProcedure *);
227 static void PLy_typeinfo_init(PLyTypeInfo *);
228 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
229 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
230 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
231 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
232 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
233 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
234 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
236 /* conversion functions */
237 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
238 static PyObject *PLyBool_FromString(const char *);
239 static PyObject *PLyFloat_FromString(const char *);
240 static PyObject *PLyInt_FromString(const char *);
241 static PyObject *PLyLong_FromString(const char *);
242 static PyObject *PLyString_FromString(const char *);
244 static HeapTuple PLyMapping_ToTuple(PLyTypeInfo *, PyObject *);
245 static HeapTuple PLySequence_ToTuple(PLyTypeInfo *, PyObject *);
246 static HeapTuple PLyObject_ToTuple(PLyTypeInfo *, PyObject *);
249 * Currently active plpython function
251 static PLyProcedure *PLy_curr_procedure = NULL;
254 * When a callback from Python into PG incurs an error, we temporarily store
255 * the error information here, and return NULL to the Python interpreter.
256 * Any further callback attempts immediately fail, and when the Python
257 * interpreter returns to the calling function, we re-throw the error (even if
258 * Python thinks it trapped the error and doesn't return NULL). Eventually
259 * this ought to be improved to let Python code really truly trap the error,
260 * but that's more of a change from the pre-8.0 semantics than I have time for
261 * now --- it will only be possible if the callback query is executed inside a
264 static ErrorData *PLy_error_in_progress = NULL;
266 static PyObject *PLy_interp_globals = NULL;
267 static PyObject *PLy_interp_safe_globals = NULL;
268 static PyObject *PLy_procedure_cache = NULL;
270 /* Python exceptions */
271 static PyObject *PLy_exc_error = NULL;
272 static PyObject *PLy_exc_fatal = NULL;
273 static PyObject *PLy_exc_spi_error = NULL;
275 /* some globals for the python module */
276 static char PLy_plan_doc[] = {
277 "Store a PostgreSQL plan"
280 static char PLy_result_doc[] = {
281 "Results of a PostgreSQL query"
286 * the function definitions
290 * This routine is a crock, and so is everyplace that calls it. The problem
291 * is that the cached form of plpython functions/queries is allocated permanently
292 * (mostly via malloc()) and never released until backend exit. Subsidiary
293 * data structures such as fmgr info records therefore must live forever
294 * as well. A better implementation would store all this stuff in a per-
295 * function memory context that could be reclaimed at need. In the meantime,
296 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
297 * it might allocate, and whatever the eventual function might allocate using
298 * fn_mcxt, will live forever too.
301 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
303 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
307 plpython_call_handler(PG_FUNCTION_ARGS)
310 PLyProcedure *save_curr_proc;
311 PLyProcedure *volatile proc = NULL;
313 if (SPI_connect() != SPI_OK_CONNECT)
314 elog(ERROR, "could not connect to SPI manager");
316 save_curr_proc = PLy_curr_procedure;
320 if (CALLED_AS_TRIGGER(fcinfo))
322 TriggerData *tdata = (TriggerData *) fcinfo->context;
325 proc = PLy_procedure_get(fcinfo,
326 RelationGetRelid(tdata->tg_relation));
327 PLy_curr_procedure = proc;
328 trv = PLy_trigger_handler(fcinfo, proc);
329 retval = PointerGetDatum(trv);
333 proc = PLy_procedure_get(fcinfo, InvalidOid);
334 PLy_curr_procedure = proc;
335 retval = PLy_function_handler(fcinfo, proc);
340 PLy_curr_procedure = save_curr_proc;
343 /* note: Py_DECREF needs braces around it, as of 2003/08 */
351 PLy_curr_procedure = save_curr_proc;
358 /* trigger and function sub handlers
360 * the python function is expected to return Py_None if the tuple is
361 * acceptable and unmodified. Otherwise it should return a PyString
362 * object who's value is SKIP, or MODIFY. SKIP means don't perform
363 * this action. MODIFY means the tuple has been modified, so update
364 * tuple and perform action. SKIP and MODIFY assume the trigger fires
365 * BEFORE the event and is ROW level. postgres expects the function
366 * to take no arguments and return an argument of type trigger.
369 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
372 PyObject *volatile plargs = NULL;
373 PyObject *volatile plrv = NULL;
377 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
378 plrv = PLy_procedure_call(proc, "TD", plargs);
380 Assert(plrv != NULL);
381 Assert(!PLy_error_in_progress);
384 * Disconnect from SPI manager
386 if (SPI_finish() != SPI_OK_FINISH)
387 elog(ERROR, "SPI_finish failed");
390 * return of None means we're happy with the tuple
396 if (!PyString_Check(plrv))
398 (errcode(ERRCODE_DATA_EXCEPTION),
399 errmsg("unexpected return value from trigger procedure"),
400 errdetail("Expected None or a String.")));
402 srv = PyString_AsString(plrv);
403 if (pg_strcasecmp(srv, "SKIP") == 0)
405 else if (pg_strcasecmp(srv, "MODIFY") == 0)
407 TriggerData *tdata = (TriggerData *) fcinfo->context;
409 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
410 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
411 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
413 elog(WARNING, "ignoring modified tuple in DELETE trigger");
415 else if (pg_strcasecmp(srv, "OK") != 0)
418 * accept "OK" as an alternative to None; otherwise, raise an
422 (errcode(ERRCODE_DATA_EXCEPTION),
423 errmsg("unexpected return value from trigger procedure"),
424 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
444 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
447 PyObject *volatile plntup;
448 PyObject *volatile plkeys;
449 PyObject *volatile platt;
450 PyObject *volatile plval;
451 PyObject *volatile plstr;
457 int *volatile modattrs;
458 Datum *volatile modvalues;
459 char *volatile modnulls;
462 plntup = plkeys = platt = plval = plstr = NULL;
469 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
470 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
471 if (!PyDict_Check(plntup))
472 elog(ERROR, "TD[\"new\"] is not a dictionary object");
475 plkeys = PyDict_Keys(plntup);
476 natts = PyList_Size(plkeys);
478 modattrs = (int *) palloc(natts * sizeof(int));
479 modvalues = (Datum *) palloc(natts * sizeof(Datum));
480 modnulls = (char *) palloc(natts * sizeof(char));
482 tupdesc = tdata->tg_relation->rd_att;
484 for (i = 0; i < natts; i++)
488 platt = PyList_GetItem(plkeys, i);
489 if (!PyString_Check(platt))
490 elog(ERROR, "attribute name is not a string");
491 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
492 if (attn == SPI_ERROR_NOATTRIBUTE)
493 elog(ERROR, "invalid attribute \"%s\" in tuple",
494 PyString_AsString(platt));
497 plval = PyDict_GetItem(plntup, platt);
499 elog(FATAL, "python interpreter is probably corrupted");
505 if (tupdesc->attrs[atti]->attisdropped)
507 modvalues[i] = (Datum) 0;
510 else if (plval != Py_None)
512 plstr = PyObject_Str(plval);
514 PLy_elog(ERROR, "function \"%s\" could not modify tuple",
516 src = PyString_AsString(plstr);
519 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
521 proc->result.out.r.atts[atti].typioparam,
522 tupdesc->attrs[atti]->atttypmod);
531 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
533 proc->result.out.r.atts[atti].typioparam,
534 tupdesc->attrs[atti]->atttypmod);
542 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
543 modattrs, modvalues, modnulls);
545 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
576 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
578 TriggerData *tdata = (TriggerData *) fcinfo->context;
589 PyObject *volatile pltdata = NULL;
594 pltdata = PyDict_New();
596 PLy_elog(ERROR, "could not build arguments for trigger procedure");
598 pltname = PyString_FromString(tdata->tg_trigger->tgname);
599 PyDict_SetItemString(pltdata, "name", pltname);
602 stroid = DatumGetCString(DirectFunctionCall1(oidout,
603 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
604 pltrelid = PyString_FromString(stroid);
605 PyDict_SetItemString(pltdata, "relid", pltrelid);
609 stroid = SPI_getrelname(tdata->tg_relation);
610 plttablename = PyString_FromString(stroid);
611 PyDict_SetItemString(pltdata, "table_name", plttablename);
612 Py_DECREF(plttablename);
615 stroid = SPI_getnspname(tdata->tg_relation);
616 plttableschema = PyString_FromString(stroid);
617 PyDict_SetItemString(pltdata, "table_schema", plttableschema);
618 Py_DECREF(plttableschema);
622 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
623 pltwhen = PyString_FromString("BEFORE");
624 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
625 pltwhen = PyString_FromString("AFTER");
628 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
629 pltwhen = NULL; /* keep compiler quiet */
631 PyDict_SetItemString(pltdata, "when", pltwhen);
634 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
636 pltlevel = PyString_FromString("ROW");
637 PyDict_SetItemString(pltdata, "level", pltlevel);
640 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
642 pltevent = PyString_FromString("INSERT");
644 PyDict_SetItemString(pltdata, "old", Py_None);
645 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
646 tdata->tg_relation->rd_att);
647 PyDict_SetItemString(pltdata, "new", pytnew);
649 *rv = tdata->tg_trigtuple;
651 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
653 pltevent = PyString_FromString("DELETE");
655 PyDict_SetItemString(pltdata, "new", Py_None);
656 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
657 tdata->tg_relation->rd_att);
658 PyDict_SetItemString(pltdata, "old", pytold);
660 *rv = tdata->tg_trigtuple;
662 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
664 pltevent = PyString_FromString("UPDATE");
666 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
667 tdata->tg_relation->rd_att);
668 PyDict_SetItemString(pltdata, "new", pytnew);
670 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
671 tdata->tg_relation->rd_att);
672 PyDict_SetItemString(pltdata, "old", pytold);
674 *rv = tdata->tg_newtuple;
678 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
679 pltevent = NULL; /* keep compiler quiet */
682 PyDict_SetItemString(pltdata, "event", pltevent);
685 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
687 pltlevel = PyString_FromString("STATEMENT");
688 PyDict_SetItemString(pltdata, "level", pltlevel);
691 PyDict_SetItemString(pltdata, "old", Py_None);
692 PyDict_SetItemString(pltdata, "new", Py_None);
695 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
696 pltevent = PyString_FromString("INSERT");
697 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
698 pltevent = PyString_FromString("DELETE");
699 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
700 pltevent = PyString_FromString("UPDATE");
703 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
704 pltevent = NULL; /* keep compiler quiet */
707 PyDict_SetItemString(pltdata, "event", pltevent);
711 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
713 if (tdata->tg_trigger->tgnargs)
721 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
722 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
724 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
727 * stolen, don't Py_DECREF
729 PyList_SetItem(pltargs, i, pltarg);
737 PyDict_SetItemString(pltdata, "args", pltargs);
752 /* function handler and friends */
754 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
757 PyObject *volatile plargs = NULL;
758 PyObject *volatile plrv = NULL;
759 PyObject *volatile plrv_so = NULL;
764 if (!proc->is_setof || proc->setof == NULL)
766 /* Simple type returning function or first time for SETOF function */
767 plargs = PLy_function_build_args(fcinfo, proc);
768 plrv = PLy_procedure_call(proc, "args", plargs);
772 * SETOF function parameters will be deleted when last row is
775 PLy_function_delete_args(proc);
776 Assert(plrv != NULL);
777 Assert(!PLy_error_in_progress);
781 * Disconnect from SPI manager and then create the return values datum
782 * (if the input function does a palloc for it this must not be
783 * allocated in the SPI memory context because SPI_finish would free
786 if (SPI_finish() != SPI_OK_FINISH)
787 elog(ERROR, "SPI_finish failed");
791 bool has_error = false;
792 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
794 if (proc->setof == NULL)
796 /* first time -- do checks and setup */
797 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
798 (rsi->allowedModes & SFRM_ValuePerCall) == 0)
801 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
802 errmsg("only value per call is allowed")));
804 rsi->returnMode = SFRM_ValuePerCall;
806 /* Make iterator out of returned object */
807 proc->setof = PyObject_GetIter(plrv);
811 if (proc->setof == NULL)
813 (errcode(ERRCODE_DATATYPE_MISMATCH),
814 errmsg("returned object can not be iterated"),
815 errdetail("SETOF must be returned as iterable object")));
818 /* Fetch next from iterator */
819 plrv = PyIter_Next(proc->setof);
821 rsi->isDone = ExprMultipleResult;
824 rsi->isDone = ExprEndResult;
825 has_error = PyErr_Occurred() != NULL;
828 if (rsi->isDone == ExprEndResult)
830 /* Iterator is exhausted or error happened */
831 Py_DECREF(proc->setof);
838 PLy_function_delete_args(proc);
842 (errcode(ERRCODE_DATA_EXCEPTION),
843 errmsg("error fetching next item from iterator")));
845 fcinfo->isnull = true;
851 * If the function is declared to return void, the Python return value
852 * must be None. For void-returning functions, we also treat a None
853 * return value as a special "void datum" rather than NULL (as is the
854 * case for non-void-returning functions).
856 if (proc->result.out.d.typoid == VOIDOID)
860 (errcode(ERRCODE_DATATYPE_MISMATCH),
861 errmsg("invalid return value from plpython function"),
862 errdetail("Functions returning type \"void\" must return None.")));
864 fcinfo->isnull = false;
867 else if (plrv == Py_None)
869 fcinfo->isnull = true;
870 if (proc->result.is_rowtype < 1)
871 rv = InputFunctionCall(&proc->result.out.d.typfunc,
873 proc->result.out.d.typioparam,
879 else if (proc->result.is_rowtype >= 1)
881 HeapTuple tuple = NULL;
883 if (PySequence_Check(plrv))
884 /* composite type as sequence (tuple, list etc) */
885 tuple = PLySequence_ToTuple(&proc->result, plrv);
886 else if (PyMapping_Check(plrv))
887 /* composite type as mapping (currently only dict) */
888 tuple = PLyMapping_ToTuple(&proc->result, plrv);
890 /* returned as smth, must provide method __getattr__(name) */
891 tuple = PLyObject_ToTuple(&proc->result, plrv);
895 fcinfo->isnull = false;
896 rv = HeapTupleGetDatum(tuple);
900 fcinfo->isnull = true;
906 fcinfo->isnull = false;
907 plrv_so = PyObject_Str(plrv);
909 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
910 plrv_sc = PyString_AsString(plrv_so);
911 rv = InputFunctionCall(&proc->result.out.d.typfunc,
913 proc->result.out.d.typioparam,
935 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
939 PyDict_SetItemString(proc->globals, kargs, vargs);
940 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
941 proc->globals, proc->globals);
944 * If there was an error in a PG callback, propagate that no matter what
945 * Python claims about its success.
947 if (PLy_error_in_progress)
949 ErrorData *edata = PLy_error_in_progress;
951 PLy_error_in_progress = NULL;
955 if (rv == NULL || PyErr_Occurred())
958 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
965 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
967 PyObject *volatile arg = NULL;
968 PyObject *volatile args = NULL;
973 args = PyList_New(proc->nargs);
974 for (i = 0; i < proc->nargs; i++)
976 if (proc->args[i].is_rowtype > 0)
978 if (fcinfo->argnull[i])
986 HeapTupleData tmptup;
988 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
989 /* Extract rowtype info and find a tupdesc */
990 tupType = HeapTupleHeaderGetTypeId(td);
991 tupTypmod = HeapTupleHeaderGetTypMod(td);
992 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
994 /* Set up I/O funcs if not done yet */
995 if (proc->args[i].is_rowtype != 1)
996 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
998 /* Build a temporary HeapTuple control structure */
999 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1002 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
1003 ReleaseTupleDesc(tupdesc);
1008 if (fcinfo->argnull[i])
1014 ct = OutputFunctionCall(&(proc->args[i].in.d.typfunc),
1016 arg = (proc->args[i].in.d.func) (ct);
1027 if (PyList_SetItem(args, i, arg) == -1 ||
1029 PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1))
1030 PLy_elog(ERROR, "problem setting up arguments for \"%s\"", proc->proname);
1048 PLy_function_delete_args(PLyProcedure * proc)
1052 if (!proc->argnames)
1055 for (i = 0; i < proc->nargs; i++)
1056 PyDict_DelItemString(proc->globals, proc->argnames[i]);
1061 * PLyProcedure functions
1064 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
1065 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
1066 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
1069 static PLyProcedure *
1070 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
1076 PLyProcedure *proc = NULL;
1079 fn_oid = fcinfo->flinfo->fn_oid;
1080 procTup = SearchSysCache(PROCOID,
1081 ObjectIdGetDatum(fn_oid),
1083 if (!HeapTupleIsValid(procTup))
1084 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1086 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
1087 if (rv >= sizeof(key) || rv < 0)
1088 elog(ERROR, "key too long");
1090 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
1095 if (!PyCObject_Check(plproc))
1096 elog(FATAL, "expected a PyCObject, didn't get one");
1098 proc = PyCObject_AsVoidPtr(plproc);
1099 if (proc->me != plproc)
1100 elog(FATAL, "proc->me != plproc");
1101 /* did we find an up-to-date cache entry? */
1102 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
1103 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
1111 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
1113 ReleaseSysCache(procTup);
1118 static PLyProcedure *
1119 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
1120 HeapTuple procTup, char *key)
1122 char procName[NAMEDATALEN + 256];
1123 Form_pg_proc procStruct;
1124 PLyProcedure *volatile proc;
1125 char *volatile procSource = NULL;
1134 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1136 if (OidIsValid(tgreloid))
1137 rv = snprintf(procName, sizeof(procName),
1138 "__plpython_procedure_%s_%u_trigger_%u",
1139 NameStr(procStruct->proname),
1140 fcinfo->flinfo->fn_oid,
1143 rv = snprintf(procName, sizeof(procName),
1144 "__plpython_procedure_%s_%u",
1145 NameStr(procStruct->proname),
1146 fcinfo->flinfo->fn_oid);
1147 if (rv >= sizeof(procName) || rv < 0)
1148 elog(ERROR, "procedure name would overrun buffer");
1150 proc = PLy_malloc(sizeof(PLyProcedure));
1151 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1152 proc->pyname = PLy_strdup(procName);
1153 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1154 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1155 /* Remember if function is STABLE/IMMUTABLE */
1157 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1158 PLy_typeinfo_init(&proc->result);
1159 for (i = 0; i < FUNC_MAX_ARGS; i++)
1160 PLy_typeinfo_init(&proc->args[i]);
1162 proc->code = proc->statics = NULL;
1163 proc->globals = proc->me = NULL;
1164 proc->is_setof = procStruct->proretset;
1166 proc->argnames = NULL;
1171 * get information required for output conversion of the return value,
1172 * but only if this isn't a trigger.
1174 if (!CALLED_AS_TRIGGER(fcinfo))
1176 HeapTuple rvTypeTup;
1177 Form_pg_type rvTypeStruct;
1179 rvTypeTup = SearchSysCache(TYPEOID,
1180 ObjectIdGetDatum(procStruct->prorettype),
1182 if (!HeapTupleIsValid(rvTypeTup))
1183 elog(ERROR, "cache lookup failed for type %u",
1184 procStruct->prorettype);
1185 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1187 /* Disallow pseudotype result, except for void */
1188 if (rvTypeStruct->typtype == 'p' &&
1189 procStruct->prorettype != VOIDOID)
1191 if (procStruct->prorettype == TRIGGEROID)
1193 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1194 errmsg("trigger functions may only be called as triggers")));
1197 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1198 errmsg("plpython functions cannot return type %s",
1199 format_type_be(procStruct->prorettype))));
1202 if (rvTypeStruct->typtype == 'c')
1205 * Tuple: set up later, during first call to
1206 * PLy_function_handler
1208 proc->result.out.d.typoid = procStruct->prorettype;
1209 proc->result.is_rowtype = 2;
1212 PLy_output_datum_func(&proc->result, rvTypeTup);
1214 ReleaseSysCache(rvTypeTup);
1219 * input/output conversion for trigger tuples. use the result
1220 * TypeInfo variable to store the tuple conversion info.
1222 TriggerData *tdata = (TriggerData *) fcinfo->context;
1224 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1225 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1229 * now get information required for input conversion of the
1230 * procedure's arguments.
1232 proc->nargs = fcinfo->nargs;
1235 argnames = SysCacheGetAttr(PROCOID, procTup, Anum_pg_proc_proargnames, &isnull);
1238 deconstruct_array(DatumGetArrayTypeP(argnames), TEXTOID, -1, false, 'i',
1239 &elems, NULL, &nelems);
1240 if (nelems != proc->nargs)
1242 "proargnames must have the same number of elements "
1243 "as the function has arguments");
1244 proc->argnames = (char **) PLy_malloc(sizeof(char *) * proc->nargs);
1247 for (i = 0; i < fcinfo->nargs; i++)
1249 HeapTuple argTypeTup;
1250 Form_pg_type argTypeStruct;
1252 argTypeTup = SearchSysCache(TYPEOID,
1253 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1255 if (!HeapTupleIsValid(argTypeTup))
1256 elog(ERROR, "cache lookup failed for type %u",
1257 procStruct->proargtypes.values[i]);
1258 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1260 /* Disallow pseudotype argument */
1261 if (argTypeStruct->typtype == 'p')
1263 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1264 errmsg("plpython functions cannot take type %s",
1265 format_type_be(procStruct->proargtypes.values[i]))));
1267 if (argTypeStruct->typtype != 'c')
1268 PLy_input_datum_func(&(proc->args[i]),
1269 procStruct->proargtypes.values[i],
1272 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1274 ReleaseSysCache(argTypeTup);
1276 /* Fetch argument name */
1278 proc->argnames[i] = PLy_strdup(DatumGetCString(DirectFunctionCall1(textout, elems[i])));
1282 * get the text of the function.
1284 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1285 Anum_pg_proc_prosrc, &isnull);
1287 elog(ERROR, "null prosrc");
1288 procSource = DatumGetCString(DirectFunctionCall1(textout,
1291 PLy_procedure_compile(proc, procSource);
1295 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1296 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1300 PLy_procedure_delete(proc);
1312 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1314 PyObject *crv = NULL;
1317 proc->globals = PyDict_Copy(PLy_interp_globals);
1320 * SD is private preserved data between calls. GD is global data shared by
1323 proc->statics = PyDict_New();
1324 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1327 * insert the function code into the interpreter
1329 msrc = PLy_procedure_munge_source(proc->pyname, src);
1330 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1333 if (crv != NULL && (!PyErr_Occurred()))
1336 char call[NAMEDATALEN + 256];
1341 * compile a call to the function
1343 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1344 if (clen < 0 || clen >= sizeof(call))
1345 elog(ERROR, "string would overflow buffer");
1346 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1347 if (proc->code != NULL && (!PyErr_Occurred()))
1353 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1357 PLy_procedure_munge_source(const char *name, const char *src)
1366 * room for function source and the def statement
1368 mlen = (strlen(src) * 2) + strlen(name) + 16;
1370 mrc = PLy_malloc(mlen);
1371 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1372 Assert(plen >= 0 && plen < mlen);
1379 if (*sp == '\r' && *(sp + 1) == '\n')
1382 if (*sp == '\n' || *sp == '\r')
1395 if (mp > (mrc + mlen))
1396 elog(FATAL, "buffer overrun in PLy_munge_source");
1402 PLy_procedure_delete(PLyProcedure * proc)
1406 Py_XDECREF(proc->code);
1407 Py_XDECREF(proc->statics);
1408 Py_XDECREF(proc->globals);
1409 Py_XDECREF(proc->me);
1411 PLy_free(proc->proname);
1413 PLy_free(proc->pyname);
1414 for (i = 0; i < proc->nargs; i++)
1416 if (proc->args[i].is_rowtype == 1)
1418 if (proc->args[i].in.r.atts)
1419 PLy_free(proc->args[i].in.r.atts);
1420 if (proc->args[i].out.r.atts)
1421 PLy_free(proc->args[i].out.r.atts);
1423 if (proc->argnames && proc->argnames[i])
1424 PLy_free(proc->argnames[i]);
1427 PLy_free(proc->argnames);
1430 /* conversion functions. remember output from python is
1431 * input to postgresql, and vis versa.
1434 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1438 if (arg->is_rowtype == 0)
1439 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1441 arg->is_rowtype = 1;
1442 arg->in.r.natts = desc->natts;
1443 arg->in.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1445 for (i = 0; i < desc->natts; i++)
1449 if (desc->attrs[i]->attisdropped)
1452 typeTup = SearchSysCache(TYPEOID,
1453 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1455 if (!HeapTupleIsValid(typeTup))
1456 elog(ERROR, "cache lookup failed for type %u",
1457 desc->attrs[i]->atttypid);
1459 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1460 desc->attrs[i]->atttypid,
1463 ReleaseSysCache(typeTup);
1468 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1472 if (arg->is_rowtype == 0)
1473 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1475 arg->is_rowtype = 1;
1476 arg->out.r.natts = desc->natts;
1477 arg->out.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1479 for (i = 0; i < desc->natts; i++)
1483 if (desc->attrs[i]->attisdropped)
1486 typeTup = SearchSysCache(TYPEOID,
1487 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1489 if (!HeapTupleIsValid(typeTup))
1490 elog(ERROR, "cache lookup failed for type %u",
1491 desc->attrs[i]->atttypid);
1493 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1495 ReleaseSysCache(typeTup);
1500 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1502 if (arg->is_rowtype > 0)
1503 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1504 arg->is_rowtype = 0;
1505 PLy_output_datum_func2(&(arg->out.d), typeTup);
1509 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1511 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1513 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1514 arg->typoid = HeapTupleGetOid(typeTup);
1515 arg->typioparam = getTypeIOParam(typeTup);
1516 arg->typbyval = typeStruct->typbyval;
1520 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1522 if (arg->is_rowtype > 0)
1523 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1524 arg->is_rowtype = 0;
1525 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1529 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1531 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1533 /* Get the type's conversion information */
1534 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1535 arg->typioparam = getTypeIOParam(typeTup);
1536 arg->typbyval = typeStruct->typbyval;
1538 /* Determine which kind of Python object we will convert to */
1542 arg->func = PLyBool_FromString;
1547 arg->func = PLyFloat_FromString;
1551 arg->func = PLyInt_FromString;
1554 arg->func = PLyLong_FromString;
1557 arg->func = PLyString_FromString;
1563 PLy_typeinfo_init(PLyTypeInfo * arg)
1565 arg->is_rowtype = -1;
1566 arg->in.r.natts = arg->out.r.natts = 0;
1567 arg->in.r.atts = NULL;
1568 arg->out.r.atts = NULL;
1572 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1574 if (arg->is_rowtype == 1)
1577 PLy_free(arg->in.r.atts);
1578 if (arg->out.r.atts)
1579 PLy_free(arg->out.r.atts);
1583 /* assumes that a bool is always returned as a 't' or 'f' */
1585 PLyBool_FromString(const char *src)
1588 * We would like to use Py_RETURN_TRUE and Py_RETURN_FALSE here for
1589 * generating SQL from trigger functions, but those are only
1590 * supported in Python >= 2.3, and we support older
1591 * versions. http://docs.python.org/api/boolObjects.html
1594 return PyInt_FromLong(1);
1595 return PyInt_FromLong(0);
1599 PLyFloat_FromString(const char *src)
1605 v = strtod(src, &eptr);
1606 if (*eptr != '\0' || errno)
1608 return PyFloat_FromDouble(v);
1612 PLyInt_FromString(const char *src)
1618 v = strtol(src, &eptr, 0);
1619 if (*eptr != '\0' || errno)
1621 return PyInt_FromLong(v);
1625 PLyLong_FromString(const char *src)
1627 return PyLong_FromString((char *) src, NULL, 0);
1631 PLyString_FromString(const char *src)
1633 return PyString_FromString(src);
1637 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1639 PyObject *volatile dict;
1642 if (info->is_rowtype != 1)
1643 elog(ERROR, "PLyTypeInfo structure describes a datum");
1645 dict = PyDict_New();
1647 PLy_elog(ERROR, "could not create tuple dictionary");
1651 for (i = 0; i < info->in.r.natts; i++)
1659 if (desc->attrs[i]->attisdropped)
1662 key = NameStr(desc->attrs[i]->attname);
1663 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1665 if (is_null || info->in.r.atts[i].func == NULL)
1666 PyDict_SetItemString(dict, key, Py_None);
1669 vsrc = OutputFunctionCall(&info->in.r.atts[i].typfunc,
1673 * no exceptions allowed
1675 value = info->in.r.atts[i].func(vsrc);
1677 PyDict_SetItemString(dict, key, value);
1694 PLyMapping_ToTuple(PLyTypeInfo * info, PyObject * mapping)
1702 Assert(PyMapping_Check(mapping));
1704 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1705 if (info->is_rowtype == 2)
1706 PLy_output_tuple_funcs(info, desc);
1707 Assert(info->is_rowtype == 1);
1710 values = palloc(sizeof(Datum) * desc->natts);
1711 nulls = palloc(sizeof(char) * desc->natts);
1712 for (i = 0; i < desc->natts; ++i)
1718 key = NameStr(desc->attrs[i]->attname);
1722 value = PyMapping_GetItemString(mapping, key);
1723 if (value == Py_None)
1725 values[i] = (Datum) NULL;
1732 so = PyObject_Str(value);
1734 PLy_elog(ERROR, "can't convert mapping type");
1735 valuestr = PyString_AsString(so);
1737 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1739 ,info->out.r.atts[i].typioparam
1747 (errcode(ERRCODE_UNDEFINED_COLUMN),
1748 errmsg("no mapping found with key \"%s\"", key),
1749 errhint("to return null in specific column, "
1750 "add value None to map with key named after column")));
1764 tuple = heap_formtuple(desc, values, nulls);
1765 ReleaseTupleDesc(desc);
1774 PLySequence_ToTuple(PLyTypeInfo * info, PyObject * sequence)
1782 Assert(PySequence_Check(sequence));
1785 * Check that sequence length is exactly same as PG tuple's. We actually
1786 * can ignore exceeding items or assume missing ones as null but to avoid
1787 * plpython developer's errors we are strict here
1789 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1790 if (PySequence_Length(sequence) != desc->natts)
1792 (errcode(ERRCODE_DATATYPE_MISMATCH),
1793 errmsg("returned sequence's length must be same as tuple's length")));
1795 if (info->is_rowtype == 2)
1796 PLy_output_tuple_funcs(info, desc);
1797 Assert(info->is_rowtype == 1);
1800 values = palloc(sizeof(Datum) * desc->natts);
1801 nulls = palloc(sizeof(char) * desc->natts);
1802 for (i = 0; i < desc->natts; ++i)
1810 value = PySequence_GetItem(sequence, i);
1812 if (value == Py_None)
1814 values[i] = (Datum) NULL;
1821 so = PyObject_Str(value);
1823 PLy_elog(ERROR, "can't convert sequence type");
1824 valuestr = PyString_AsString(so);
1825 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1827 ,info->out.r.atts[i].typioparam
1846 tuple = heap_formtuple(desc, values, nulls);
1847 ReleaseTupleDesc(desc);
1856 PLyObject_ToTuple(PLyTypeInfo * info, PyObject * object)
1864 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1865 if (info->is_rowtype == 2)
1866 PLy_output_tuple_funcs(info, desc);
1867 Assert(info->is_rowtype == 1);
1870 values = palloc(sizeof(Datum) * desc->natts);
1871 nulls = palloc(sizeof(char) * desc->natts);
1872 for (i = 0; i < desc->natts; ++i)
1878 key = NameStr(desc->attrs[i]->attname);
1882 value = PyObject_GetAttrString(object, key);
1883 if (value == Py_None)
1885 values[i] = (Datum) NULL;
1892 so = PyObject_Str(value);
1894 PLy_elog(ERROR, "can't convert object type");
1895 valuestr = PyString_AsString(so);
1896 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1898 ,info->out.r.atts[i].typioparam
1906 (errcode(ERRCODE_UNDEFINED_COLUMN),
1907 errmsg("no attribute named \"%s\"", key),
1908 errhint("to return null in specific column, "
1909 "let returned object to have attribute named "
1910 "after column with value None")));
1924 tuple = heap_formtuple(desc, values, nulls);
1925 ReleaseTupleDesc(desc);
1933 /* initialization, some python variables function declared here */
1935 /* interface to postgresql elog */
1936 static PyObject *PLy_debug(PyObject *, PyObject *);
1937 static PyObject *PLy_log(PyObject *, PyObject *);
1938 static PyObject *PLy_info(PyObject *, PyObject *);
1939 static PyObject *PLy_notice(PyObject *, PyObject *);
1940 static PyObject *PLy_warning(PyObject *, PyObject *);
1941 static PyObject *PLy_error(PyObject *, PyObject *);
1942 static PyObject *PLy_fatal(PyObject *, PyObject *);
1944 /* PLyPlanObject, PLyResultObject and SPI interface */
1945 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1946 static PyObject *PLy_plan_new(void);
1947 static void PLy_plan_dealloc(PyObject *);
1948 static PyObject *PLy_plan_getattr(PyObject *, char *);
1949 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1951 static PyObject *PLy_result_new(void);
1952 static void PLy_result_dealloc(PyObject *);
1953 static PyObject *PLy_result_getattr(PyObject *, char *);
1954 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1955 static PyObject *PLy_result_status(PyObject *, PyObject *);
1956 static int PLy_result_length(PyObject *);
1957 static PyObject *PLy_result_item(PyObject *, int);
1958 static PyObject *PLy_result_slice(PyObject *, int, int);
1959 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1960 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1963 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1964 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1965 static PyObject *PLy_spi_execute_query(char *query, long limit);
1966 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1967 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1970 static PyTypeObject PLy_PlanType = {
1971 PyObject_HEAD_INIT(NULL)
1973 "PLyPlan", /* tp_name */
1974 sizeof(PLyPlanObject), /* tp_size */
1975 0, /* tp_itemsize */
1980 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1982 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1986 0, /* tp_as_number */
1987 0, /* tp_as_sequence */
1988 0, /* tp_as_mapping */
1992 0, /* tp_getattro */
1993 0, /* tp_setattro */
1994 0, /* tp_as_buffer */
1995 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1996 PLy_plan_doc, /* tp_doc */
1999 static PyMethodDef PLy_plan_methods[] = {
2000 {"status", PLy_plan_status, METH_VARARGS, NULL},
2001 {NULL, NULL, 0, NULL}
2005 static PySequenceMethods PLy_result_as_sequence = {
2006 (inquiry) PLy_result_length, /* sq_length */
2007 (binaryfunc) 0, /* sq_concat */
2008 (intargfunc) 0, /* sq_repeat */
2009 (intargfunc) PLy_result_item, /* sq_item */
2010 (intintargfunc) PLy_result_slice, /* sq_slice */
2011 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
2012 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
2015 static PyTypeObject PLy_ResultType = {
2016 PyObject_HEAD_INIT(NULL)
2018 "PLyResult", /* tp_name */
2019 sizeof(PLyResultObject), /* tp_size */
2020 0, /* tp_itemsize */
2025 (destructor) PLy_result_dealloc, /* tp_dealloc */
2027 (getattrfunc) PLy_result_getattr, /* tp_getattr */
2031 0, /* tp_as_number */
2032 &PLy_result_as_sequence, /* tp_as_sequence */
2033 0, /* tp_as_mapping */
2037 0, /* tp_getattro */
2038 0, /* tp_setattro */
2039 0, /* tp_as_buffer */
2040 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2041 PLy_result_doc, /* tp_doc */
2044 static PyMethodDef PLy_result_methods[] = {
2045 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
2046 {"status", PLy_result_status, METH_VARARGS, NULL},
2047 {NULL, NULL, 0, NULL}
2050 static PyMethodDef PLy_methods[] = {
2054 {"debug", PLy_debug, METH_VARARGS, NULL},
2055 {"log", PLy_log, METH_VARARGS, NULL},
2056 {"info", PLy_info, METH_VARARGS, NULL},
2057 {"notice", PLy_notice, METH_VARARGS, NULL},
2058 {"warning", PLy_warning, METH_VARARGS, NULL},
2059 {"error", PLy_error, METH_VARARGS, NULL},
2060 {"fatal", PLy_fatal, METH_VARARGS, NULL},
2063 * create a stored plan
2065 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
2068 * execute a plan or query
2070 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
2072 {NULL, NULL, 0, NULL}
2076 /* plan object methods */
2082 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
2090 return (PyObject *) ob;
2095 PLy_plan_dealloc(PyObject * arg)
2097 PLyPlanObject *ob = (PLyPlanObject *) arg;
2100 SPI_freeplan(ob->plan);
2102 PLy_free(ob->types);
2107 for (i = 0; i < ob->nargs; i++)
2108 PLy_typeinfo_dealloc(&ob->args[i]);
2112 arg->ob_type->tp_free(arg);
2117 PLy_plan_getattr(PyObject * self, char *name)
2119 return Py_FindMethod(PLy_plan_methods, self, name);
2123 PLy_plan_status(PyObject * self, PyObject * args)
2125 if (PyArg_ParseTuple(args, ""))
2129 /* return PyInt_FromLong(self->status); */
2131 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
2137 /* result object methods */
2140 PLy_result_new(void)
2142 PLyResultObject *ob;
2144 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
2147 /* ob->tuples = NULL; */
2150 ob->status = Py_None;
2151 ob->nrows = PyInt_FromLong(-1);
2152 ob->rows = PyList_New(0);
2154 return (PyObject *) ob;
2158 PLy_result_dealloc(PyObject * arg)
2160 PLyResultObject *ob = (PLyResultObject *) arg;
2162 Py_XDECREF(ob->nrows);
2163 Py_XDECREF(ob->rows);
2164 Py_XDECREF(ob->status);
2166 arg->ob_type->tp_free(arg);
2170 PLy_result_getattr(PyObject * self, char *name)
2172 return Py_FindMethod(PLy_result_methods, self, name);
2176 PLy_result_nrows(PyObject * self, PyObject * args)
2178 PLyResultObject *ob = (PLyResultObject *) self;
2180 Py_INCREF(ob->nrows);
2185 PLy_result_status(PyObject * self, PyObject * args)
2187 PLyResultObject *ob = (PLyResultObject *) self;
2189 Py_INCREF(ob->status);
2194 PLy_result_length(PyObject * arg)
2196 PLyResultObject *ob = (PLyResultObject *) arg;
2198 return PyList_Size(ob->rows);
2202 PLy_result_item(PyObject * arg, int idx)
2205 PLyResultObject *ob = (PLyResultObject *) arg;
2207 rv = PyList_GetItem(ob->rows, idx);
2214 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
2217 PLyResultObject *ob = (PLyResultObject *) arg;
2220 rv = PyList_SetItem(ob->rows, idx, item);
2225 PLy_result_slice(PyObject * arg, int lidx, int hidx)
2228 PLyResultObject *ob = (PLyResultObject *) arg;
2230 rv = PyList_GetSlice(ob->rows, lidx, hidx);
2238 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
2241 PLyResultObject *ob = (PLyResultObject *) arg;
2243 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
2249 PLy_spi_prepare(PyObject * self, PyObject * args)
2251 PLyPlanObject *plan;
2252 PyObject *list = NULL;
2253 PyObject *volatile optr = NULL;
2256 MemoryContext oldcontext;
2258 /* Can't execute more if we have an unhandled error */
2259 if (PLy_error_in_progress)
2261 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2265 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
2267 PyErr_SetString(PLy_exc_spi_error,
2268 "Invalid arguments for plpy.prepare()");
2272 if (list && (!PySequence_Check(list)))
2274 PyErr_SetString(PLy_exc_spi_error,
2275 "Second argument in plpy.prepare() must be a sequence");
2279 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
2282 oldcontext = CurrentMemoryContext;
2290 nargs = PySequence_Length(list);
2293 plan->nargs = nargs;
2294 plan->types = PLy_malloc(sizeof(Oid) * nargs);
2295 plan->values = PLy_malloc(sizeof(Datum) * nargs);
2296 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
2299 * the other loop might throw an exception, if PLyTypeInfo
2300 * member isn't properly initialized the Py_DECREF(plan) will
2303 for (i = 0; i < nargs; i++)
2305 PLy_typeinfo_init(&plan->args[i]);
2306 plan->values[i] = PointerGetDatum(NULL);
2309 for (i = 0; i < nargs; i++)
2314 Form_pg_type typeStruct;
2316 optr = PySequence_GetItem(list, i);
2317 if (!PyString_Check(optr))
2318 elog(ERROR, "Type names must be strings.");
2319 sptr = PyString_AsString(optr);
2322 * Parse possibly-qualified type name and look it up in
2325 names = stringToQualifiedNameList(sptr,
2327 typeTup = typenameType(NULL,
2328 makeTypeNameFromNameList(names));
2330 optr = NULL; /* this is important */
2332 plan->types[i] = HeapTupleGetOid(typeTup);
2333 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2334 if (typeStruct->typtype != 'c')
2335 PLy_output_datum_func(&plan->args[i], typeTup);
2337 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
2338 ReleaseSysCache(typeTup);
2343 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2344 if (plan->plan == NULL)
2345 elog(ERROR, "SPI_prepare failed: %s",
2346 SPI_result_code_string(SPI_result));
2348 /* transfer plan from procCxt to topCxt */
2349 tmpplan = plan->plan;
2350 plan->plan = SPI_saveplan(tmpplan);
2351 SPI_freeplan(tmpplan);
2352 if (plan->plan == NULL)
2353 elog(ERROR, "SPI_saveplan failed: %s",
2354 SPI_result_code_string(SPI_result));
2358 MemoryContextSwitchTo(oldcontext);
2359 PLy_error_in_progress = CopyErrorData();
2363 if (!PyErr_Occurred())
2364 PyErr_SetString(PLy_exc_spi_error,
2365 "Unknown error in PLy_spi_prepare");
2366 /* XXX this oughta be replaced with errcontext mechanism */
2367 PLy_elog(WARNING, "in function %s:",
2368 PLy_procedure_name(PLy_curr_procedure));
2373 return (PyObject *) plan;
2376 /* execute(query="select * from foo", limit=5)
2377 * execute(plan=plan, values=(foo, bar), limit=5)
2380 PLy_spi_execute(PyObject * self, PyObject * args)
2384 PyObject *list = NULL;
2387 /* Can't execute more if we have an unhandled error */
2388 if (PLy_error_in_progress)
2390 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2394 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
2395 return PLy_spi_execute_query(query, limit);
2399 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
2400 is_PLyPlanObject(plan))
2401 return PLy_spi_execute_plan(plan, list, limit);
2403 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2408 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
2413 PLyPlanObject *plan;
2414 MemoryContext oldcontext;
2418 if (!PySequence_Check(list) || PyString_Check(list))
2420 char *msg = "plpy.execute() takes a sequence as its second argument";
2422 PyErr_SetString(PLy_exc_spi_error, msg);
2425 nargs = PySequence_Length(list);
2430 plan = (PLyPlanObject *) ob;
2432 if (nargs != plan->nargs)
2435 PyObject *so = PyObject_Str(list);
2438 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2439 PLy_procedure_name(PLy_curr_procedure));
2440 sv = PyString_AsString(so);
2441 PLy_exception_set(PLy_exc_spi_error,
2442 "Expected sequence of %d arguments, got %d. %s",
2443 plan->nargs, nargs, sv);
2449 oldcontext = CurrentMemoryContext;
2452 char *nulls = palloc(nargs * sizeof(char));
2454 for (i = 0; i < nargs; i++)
2459 elem = PySequence_GetItem(list, i);
2460 if (elem != Py_None)
2462 so = PyObject_Str(elem);
2464 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2465 PLy_procedure_name(PLy_curr_procedure));
2470 char *sv = PyString_AsString(so);
2473 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2475 plan->args[i].out.d.typioparam,
2492 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2494 plan->args[i].out.d.typioparam,
2500 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2501 PLy_curr_procedure->fn_readonly, limit);
2507 MemoryContextSwitchTo(oldcontext);
2508 PLy_error_in_progress = CopyErrorData();
2512 * cleanup plan->values array
2514 for (i = 0; i < nargs; i++)
2516 if (!plan->args[i].out.d.typbyval &&
2517 (plan->values[i] != PointerGetDatum(NULL)))
2519 pfree(DatumGetPointer(plan->values[i]));
2520 plan->values[i] = PointerGetDatum(NULL);
2524 if (!PyErr_Occurred())
2525 PyErr_SetString(PLy_exc_error,
2526 "Unknown error in PLy_spi_execute_plan");
2527 /* XXX this oughta be replaced with errcontext mechanism */
2528 PLy_elog(WARNING, "in function %s:",
2529 PLy_procedure_name(PLy_curr_procedure));
2534 for (i = 0; i < nargs; i++)
2536 if (!plan->args[i].out.d.typbyval &&
2537 (plan->values[i] != PointerGetDatum(NULL)))
2539 pfree(DatumGetPointer(plan->values[i]));
2540 plan->values[i] = PointerGetDatum(NULL);
2546 PLy_exception_set(PLy_exc_spi_error,
2547 "SPI_execute_plan failed: %s",
2548 SPI_result_code_string(rv));
2552 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2556 PLy_spi_execute_query(char *query, long limit)
2559 MemoryContext oldcontext;
2561 oldcontext = CurrentMemoryContext;
2564 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2568 MemoryContextSwitchTo(oldcontext);
2569 PLy_error_in_progress = CopyErrorData();
2571 if (!PyErr_Occurred())
2572 PyErr_SetString(PLy_exc_spi_error,
2573 "Unknown error in PLy_spi_execute_query");
2574 /* XXX this oughta be replaced with errcontext mechanism */
2575 PLy_elog(WARNING, "in function %s:",
2576 PLy_procedure_name(PLy_curr_procedure));
2583 PLy_exception_set(PLy_exc_spi_error,
2584 "SPI_execute failed: %s",
2585 SPI_result_code_string(rv));
2589 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2593 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2595 PLyResultObject *result;
2596 MemoryContext oldcontext;
2598 result = (PLyResultObject *) PLy_result_new();
2599 Py_DECREF(result->status);
2600 result->status = PyInt_FromLong(status);
2602 if (status > 0 && tuptable == NULL)
2604 Py_DECREF(result->nrows);
2605 result->nrows = PyInt_FromLong(rows);
2607 else if (status > 0 && tuptable != NULL)
2612 Py_DECREF(result->nrows);
2613 result->nrows = PyInt_FromLong(rows);
2614 PLy_typeinfo_init(&args);
2616 oldcontext = CurrentMemoryContext;
2621 Py_DECREF(result->rows);
2622 result->rows = PyList_New(rows);
2624 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2625 for (i = 0; i < rows; i++)
2627 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2630 PyList_SetItem(result->rows, i, row);
2632 PLy_typeinfo_dealloc(&args);
2634 SPI_freetuptable(tuptable);
2639 MemoryContextSwitchTo(oldcontext);
2640 PLy_error_in_progress = CopyErrorData();
2642 if (!PyErr_Occurred())
2643 PyErr_SetString(PLy_exc_error,
2644 "Unknown error in PLy_spi_execute_fetch_result");
2646 PLy_typeinfo_dealloc(&args);
2652 return (PyObject *) result;
2657 * language handler and interpreter initialization
2661 * _PG_init() - library load-time initialization
2663 * DO NOT make this static nor change its name!
2668 /* Be sure we do initialization only once (should be redundant now) */
2669 static bool inited = false;
2677 if (PyErr_Occurred())
2678 PLy_elog(FATAL, "untrapped error in initialization");
2679 PLy_procedure_cache = PyDict_New();
2680 if (PLy_procedure_cache == NULL)
2681 PLy_elog(ERROR, "could not create procedure cache");
2687 PLy_init_interp(void)
2691 mainmod = PyImport_AddModule("__main__");
2692 if (mainmod == NULL || PyErr_Occurred())
2693 PLy_elog(ERROR, "could not import \"__main__\" module.");
2695 PLy_interp_globals = PyModule_GetDict(mainmod);
2696 PLy_interp_safe_globals = PyDict_New();
2697 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2699 if (PLy_interp_globals == NULL || PyErr_Occurred())
2700 PLy_elog(ERROR, "could not initialize globals");
2713 * initialize plpy module
2715 if (PyType_Ready(&PLy_PlanType) < 0)
2716 elog(ERROR, "could not init PLy_PlanType");
2717 if (PyType_Ready(&PLy_ResultType) < 0)
2718 elog(ERROR, "could not init PLy_ResultType");
2720 plpy = Py_InitModule("plpy", PLy_methods);
2721 plpy_dict = PyModule_GetDict(plpy);
2723 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2725 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2726 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2727 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2728 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2729 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2730 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2733 * initialize main module, and add plpy
2735 main_mod = PyImport_AddModule("__main__");
2736 main_dict = PyModule_GetDict(main_mod);
2737 plpy_mod = PyImport_AddModule("plpy");
2738 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2739 if (PyErr_Occurred())
2740 elog(ERROR, "could not init plpy");
2743 /* the python interface to the elog function
2744 * don't confuse these with PLy_elog
2746 static PyObject *PLy_output(volatile int, PyObject *, PyObject *);
2749 PLy_debug(PyObject * self, PyObject * args)
2751 return PLy_output(DEBUG2, self, args);
2755 PLy_log(PyObject * self, PyObject * args)
2757 return PLy_output(LOG, self, args);
2761 PLy_info(PyObject * self, PyObject * args)
2763 return PLy_output(INFO, self, args);
2767 PLy_notice(PyObject * self, PyObject * args)
2769 return PLy_output(NOTICE, self, args);
2773 PLy_warning(PyObject * self, PyObject * args)
2775 return PLy_output(WARNING, self, args);
2779 PLy_error(PyObject * self, PyObject * args)
2781 return PLy_output(ERROR, self, args);
2785 PLy_fatal(PyObject * self, PyObject * args)
2787 return PLy_output(FATAL, self, args);
2792 PLy_output(volatile int level, PyObject * self, PyObject * args)
2796 MemoryContext oldcontext;
2798 so = PyObject_Str(args);
2799 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2802 sv = "Unable to parse error message in `plpy.elog'";
2805 oldcontext = CurrentMemoryContext;
2808 elog(level, "%s", sv);
2812 MemoryContextSwitchTo(oldcontext);
2813 PLy_error_in_progress = CopyErrorData();
2818 * returning NULL here causes the python interpreter to bail. when
2819 * control passes back to PLy_procedure_call, we check for PG
2820 * exceptions and re-throw the error.
2822 PyErr_SetString(PLy_exc_error, sv);
2830 * return a legal object so the interpreter will continue on its merry way
2838 * Get the name of the last procedure called by the backend (the
2839 * innermost, if a plpython procedure call calls the backend and the
2840 * backend calls another plpython procedure).
2842 * NB: this returns the SQL name, not the internal Python procedure name
2845 PLy_procedure_name(PLyProcedure * proc)
2848 return "<unknown procedure>";
2849 return proc->proname;
2852 /* output a python traceback/exception via the postgresql elog
2853 * function. not pretty.
2856 PLy_exception_set(PyObject * exc, const char *fmt,...)
2862 vsnprintf(buf, sizeof(buf), fmt, ap);
2865 PyErr_SetString(exc, buf);
2868 /* Emit a PG error or notice, together with any available info about the
2869 * current Python error. This should be used to propagate Python errors
2873 PLy_elog(int elevel, const char *fmt,...)
2880 xmsg = PLy_traceback(&xlevel);
2883 emsg = PLy_vprintf(fmt, ap);
2889 (errmsg("plpython: %s", emsg),
2890 (xmsg) ? errdetail("%s", xmsg) : 0));
2907 PLy_traceback(int *xlevel)
2919 * get the current exception
2921 PyErr_Fetch(&e, &v, &tb);
2924 * oops, no exception, return
2932 PyErr_NormalizeException(&e, &v, &tb);
2935 eob = PyObject_Str(e);
2936 if (v && ((vob = PyObject_Str(v)) != NULL))
2937 vstr = PyString_AsString(vob);
2942 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
2943 * because that function calls us, so we could end up with infinite
2944 * recursion. I'm not even sure if eob could be NULL here -- would an
2945 * Assert() be more appropriate?
2947 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
2948 xstr = PLy_printf("%s: %s", estr, vstr);
2955 * intuit an appropriate error level based on the exception type
2957 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
2959 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
2969 PLy_printf(const char *fmt,...)
2975 emsg = PLy_vprintf(fmt, ap);
2981 PLy_vprintf(const char *fmt, va_list ap)
2988 blen = strlen(fmt) * 2;
2991 buf = PLy_malloc(blen * sizeof(char));
2995 bchar = vsnprintf(buf, blen, fmt, ap);
2996 if (bchar > 0 && bchar < blen)
3004 buf = PLy_realloc(buf, blen);
3010 /* python module code */
3012 /* some dumb utility functions */
3014 PLy_malloc(size_t bytes)
3016 void *ptr = malloc(bytes);
3020 (errcode(ERRCODE_OUT_OF_MEMORY),
3021 errmsg("out of memory")));
3026 PLy_realloc(void *optr, size_t bytes)
3028 void *nptr = realloc(optr, bytes);
3032 (errcode(ERRCODE_OUT_OF_MEMORY),
3033 errmsg("out of memory")));
3038 PLy_strdup(const char *str)
3043 len = strlen(str) + 1;
3044 result = PLy_malloc(len);
3045 memcpy(result, str, len);
3050 /* define this away */