1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.105 2007/11/23 01:46:34 alvherre 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
27 * Py_ssize_t compat for Python <= 2.4
29 #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
30 typedef int Py_ssize_t;
32 #define PY_SSIZE_T_MAX INT_MAX
33 #define PY_SSIZE_T_MIN INT_MIN
37 * PyBool_FromLong is supported from 2.3.
39 #if PY_VERSION_HEX < 0x02030000
40 #define PyBool_FromLong(x) PyInt_FromLong(x)
50 /* postgreSQL stuff */
51 #include "access/heapam.h"
52 #include "catalog/pg_proc.h"
53 #include "catalog/pg_type.h"
54 #include "commands/trigger.h"
55 #include "executor/spi.h"
58 #include "nodes/makefuncs.h"
59 #include "parser/parse_type.h"
60 #include "tcop/tcopprot.h"
61 #include "utils/builtins.h"
62 #include "utils/lsyscache.h"
63 #include "utils/memutils.h"
64 #include "utils/syscache.h"
65 #include "utils/typcache.h"
72 /* convert Postgresql Datum or tuple into a PyObject.
73 * input to Python. Tuples are converted to dictionary
77 typedef PyObject *(*PLyDatumToObFunc) (const char *);
79 typedef struct PLyDatumToOb
81 PLyDatumToObFunc func;
87 typedef struct PLyTupleToOb
93 typedef union PLyTypeInput
99 /* convert PyObject to a Postgresql Datum or tuple.
102 typedef struct PLyObToDatum
104 FmgrInfo typfunc; /* The type's input function */
105 Oid typoid; /* The OID of the type */
110 typedef struct PLyObToTuple
116 typedef union PLyTypeOutput
122 /* all we need to move Postgresql data to Python objects,
125 typedef struct PLyTypeInfo
132 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
133 * 1 rowtype 2 rowtype, but I/O functions not set up yet
138 /* cached procedure data */
139 typedef struct PLyProcedure
141 char *proname; /* SQL name of procedure */
142 char *pyname; /* Python name of procedure */
143 TransactionId fn_xmin;
144 ItemPointerData fn_tid;
146 PLyTypeInfo result; /* also used to store info for trigger tuple
148 bool is_setof; /* true, if procedure returns result set */
149 PyObject *setof; /* contents of result set. */
150 char **argnames; /* Argument names */
151 PLyTypeInfo args[FUNC_MAX_ARGS];
153 PyObject *code; /* compiled procedure code */
154 PyObject *statics; /* data saved across calls, local scope */
155 PyObject *globals; /* data saved across calls, global scope */
156 PyObject *me; /* PyCObject containing pointer to this
162 typedef struct PLyPlanObject
165 void *plan; /* return of an SPI_saveplan */
172 typedef struct PLyResultObject
175 /* HeapTuple *tuples; */
176 PyObject * nrows; /* number of rows returned by query */
177 PyObject *rows; /* data rows, or None if no data returned */
178 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
182 /* function declarations */
184 /* Two exported functions: first is the magic telling Postgresql
185 * what function call interface it implements. Second is for
186 * initialization of the interpreter during library load.
188 Datum plpython_call_handler(PG_FUNCTION_ARGS);
191 PG_FUNCTION_INFO_V1(plpython_call_handler);
193 /* most of the remaining of the declarations, all static */
195 /* these should only be called once at the first call
196 * of plpython_call_handler. initialize the python interpreter
199 static void PLy_init_interp(void);
200 static void PLy_init_plpy(void);
202 /* call PyErr_SetString with a vprint interface */
204 PLy_exception_set(PyObject *, const char *,...)
205 __attribute__((format(printf, 2, 3)));
207 /* Get the innermost python procedure called from the backend */
208 static char *PLy_procedure_name(PLyProcedure *);
210 /* some utility functions */
211 static void PLy_elog(int, const char *,...);
212 static char *PLy_traceback(int *);
214 static void *PLy_malloc(size_t);
215 static char *PLy_strdup(const char *);
216 static void PLy_free(void *);
218 /* sub handlers for functions and triggers */
219 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
220 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
222 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
223 static void PLy_function_delete_args(PLyProcedure *);
224 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
226 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
227 TriggerData *, HeapTuple);
229 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
231 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
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 *, HeapTuple);
245 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
246 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
247 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
248 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
249 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
251 /* conversion functions */
252 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
253 static PyObject *PLyBool_FromString(const char *);
254 static PyObject *PLyFloat_FromString(const char *);
255 static PyObject *PLyInt_FromString(const char *);
256 static PyObject *PLyLong_FromString(const char *);
257 static PyObject *PLyString_FromString(const char *);
259 static HeapTuple PLyMapping_ToTuple(PLyTypeInfo *, PyObject *);
260 static HeapTuple PLySequence_ToTuple(PLyTypeInfo *, PyObject *);
261 static HeapTuple PLyObject_ToTuple(PLyTypeInfo *, PyObject *);
264 * Currently active plpython function
266 static PLyProcedure *PLy_curr_procedure = NULL;
269 * When a callback from Python into PG incurs an error, we temporarily store
270 * the error information here, and return NULL to the Python interpreter.
271 * Any further callback attempts immediately fail, and when the Python
272 * interpreter returns to the calling function, we re-throw the error (even if
273 * Python thinks it trapped the error and doesn't return NULL). Eventually
274 * this ought to be improved to let Python code really truly trap the error,
275 * but that's more of a change from the pre-8.0 semantics than I have time for
276 * now --- it will only be possible if the callback query is executed inside a
279 static ErrorData *PLy_error_in_progress = NULL;
281 static PyObject *PLy_interp_globals = NULL;
282 static PyObject *PLy_interp_safe_globals = NULL;
283 static PyObject *PLy_procedure_cache = NULL;
285 /* Python exceptions */
286 static PyObject *PLy_exc_error = NULL;
287 static PyObject *PLy_exc_fatal = NULL;
288 static PyObject *PLy_exc_spi_error = NULL;
290 /* some globals for the python module */
291 static char PLy_plan_doc[] = {
292 "Store a PostgreSQL plan"
295 static char PLy_result_doc[] = {
296 "Results of a PostgreSQL query"
301 * the function definitions
305 * This routine is a crock, and so is everyplace that calls it. The problem
306 * is that the cached form of plpython functions/queries is allocated permanently
307 * (mostly via malloc()) and never released until backend exit. Subsidiary
308 * data structures such as fmgr info records therefore must live forever
309 * as well. A better implementation would store all this stuff in a per-
310 * function memory context that could be reclaimed at need. In the meantime,
311 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
312 * it might allocate, and whatever the eventual function might allocate using
313 * fn_mcxt, will live forever too.
316 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
318 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
322 plpython_call_handler(PG_FUNCTION_ARGS)
325 PLyProcedure *save_curr_proc;
326 PLyProcedure *volatile proc = NULL;
328 if (SPI_connect() != SPI_OK_CONNECT)
329 elog(ERROR, "could not connect to SPI manager");
331 save_curr_proc = PLy_curr_procedure;
335 if (CALLED_AS_TRIGGER(fcinfo))
337 TriggerData *tdata = (TriggerData *) fcinfo->context;
340 proc = PLy_procedure_get(fcinfo,
341 RelationGetRelid(tdata->tg_relation));
342 PLy_curr_procedure = proc;
343 trv = PLy_trigger_handler(fcinfo, proc);
344 retval = PointerGetDatum(trv);
348 proc = PLy_procedure_get(fcinfo, InvalidOid);
349 PLy_curr_procedure = proc;
350 retval = PLy_function_handler(fcinfo, proc);
355 PLy_curr_procedure = save_curr_proc;
358 /* note: Py_DECREF needs braces around it, as of 2003/08 */
366 PLy_curr_procedure = save_curr_proc;
373 /* trigger and function sub handlers
375 * the python function is expected to return Py_None if the tuple is
376 * acceptable and unmodified. Otherwise it should return a PyString
377 * object who's value is SKIP, or MODIFY. SKIP means don't perform
378 * this action. MODIFY means the tuple has been modified, so update
379 * tuple and perform action. SKIP and MODIFY assume the trigger fires
380 * BEFORE the event and is ROW level. postgres expects the function
381 * to take no arguments and return an argument of type trigger.
384 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
387 PyObject *volatile plargs = NULL;
388 PyObject *volatile plrv = NULL;
392 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
393 plrv = PLy_procedure_call(proc, "TD", plargs);
395 Assert(plrv != NULL);
396 Assert(!PLy_error_in_progress);
399 * Disconnect from SPI manager
401 if (SPI_finish() != SPI_OK_FINISH)
402 elog(ERROR, "SPI_finish failed");
405 * return of None means we're happy with the tuple
411 if (!PyString_Check(plrv))
413 (errcode(ERRCODE_DATA_EXCEPTION),
414 errmsg("unexpected return value from trigger procedure"),
415 errdetail("Expected None or a String.")));
417 srv = PyString_AsString(plrv);
418 if (pg_strcasecmp(srv, "SKIP") == 0)
420 else if (pg_strcasecmp(srv, "MODIFY") == 0)
422 TriggerData *tdata = (TriggerData *) fcinfo->context;
424 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
425 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
426 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
428 elog(WARNING, "ignoring modified tuple in DELETE trigger");
430 else if (pg_strcasecmp(srv, "OK") != 0)
433 * accept "OK" as an alternative to None; otherwise, raise an
437 (errcode(ERRCODE_DATA_EXCEPTION),
438 errmsg("unexpected return value from trigger procedure"),
439 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
459 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
462 PyObject *volatile plntup;
463 PyObject *volatile plkeys;
464 PyObject *volatile platt;
465 PyObject *volatile plval;
466 PyObject *volatile plstr;
472 int *volatile modattrs;
473 Datum *volatile modvalues;
474 char *volatile modnulls;
477 plntup = plkeys = platt = plval = plstr = NULL;
484 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
485 elog(ERROR, "TD[\"new\"] deleted, cannot modify tuple");
486 if (!PyDict_Check(plntup))
487 elog(ERROR, "TD[\"new\"] is not a dictionary object");
490 plkeys = PyDict_Keys(plntup);
491 natts = PyList_Size(plkeys);
493 modattrs = (int *) palloc(natts * sizeof(int));
494 modvalues = (Datum *) palloc(natts * sizeof(Datum));
495 modnulls = (char *) palloc(natts * sizeof(char));
497 tupdesc = tdata->tg_relation->rd_att;
499 for (i = 0; i < natts; i++)
503 platt = PyList_GetItem(plkeys, i);
504 if (!PyString_Check(platt))
505 elog(ERROR, "attribute name is not a string");
506 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
507 if (attn == SPI_ERROR_NOATTRIBUTE)
508 elog(ERROR, "invalid attribute \"%s\" in tuple",
509 PyString_AsString(platt));
512 plval = PyDict_GetItem(plntup, platt);
514 elog(FATAL, "python interpreter is probably corrupted");
520 if (tupdesc->attrs[atti]->attisdropped)
522 modvalues[i] = (Datum) 0;
525 else if (plval != Py_None)
527 plstr = PyObject_Str(plval);
529 PLy_elog(ERROR, "function \"%s\" could not modify tuple",
531 src = PyString_AsString(plstr);
534 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
536 proc->result.out.r.atts[atti].typioparam,
537 tupdesc->attrs[atti]->atttypmod);
546 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
548 proc->result.out.r.atts[atti].typioparam,
549 tupdesc->attrs[atti]->atttypmod);
557 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
558 modattrs, modvalues, modnulls);
560 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
591 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
593 TriggerData *tdata = (TriggerData *) fcinfo->context;
604 PyObject *volatile pltdata = NULL;
609 pltdata = PyDict_New();
611 PLy_elog(ERROR, "could not build arguments for trigger procedure");
613 pltname = PyString_FromString(tdata->tg_trigger->tgname);
614 PyDict_SetItemString(pltdata, "name", pltname);
617 stroid = DatumGetCString(DirectFunctionCall1(oidout,
618 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
619 pltrelid = PyString_FromString(stroid);
620 PyDict_SetItemString(pltdata, "relid", pltrelid);
624 stroid = SPI_getrelname(tdata->tg_relation);
625 plttablename = PyString_FromString(stroid);
626 PyDict_SetItemString(pltdata, "table_name", plttablename);
627 Py_DECREF(plttablename);
630 stroid = SPI_getnspname(tdata->tg_relation);
631 plttableschema = PyString_FromString(stroid);
632 PyDict_SetItemString(pltdata, "table_schema", plttableschema);
633 Py_DECREF(plttableschema);
637 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
638 pltwhen = PyString_FromString("BEFORE");
639 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
640 pltwhen = PyString_FromString("AFTER");
643 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
644 pltwhen = NULL; /* keep compiler quiet */
646 PyDict_SetItemString(pltdata, "when", pltwhen);
649 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
651 pltlevel = PyString_FromString("ROW");
652 PyDict_SetItemString(pltdata, "level", pltlevel);
655 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
657 pltevent = PyString_FromString("INSERT");
659 PyDict_SetItemString(pltdata, "old", Py_None);
660 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
661 tdata->tg_relation->rd_att);
662 PyDict_SetItemString(pltdata, "new", pytnew);
664 *rv = tdata->tg_trigtuple;
666 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
668 pltevent = PyString_FromString("DELETE");
670 PyDict_SetItemString(pltdata, "new", Py_None);
671 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
672 tdata->tg_relation->rd_att);
673 PyDict_SetItemString(pltdata, "old", pytold);
675 *rv = tdata->tg_trigtuple;
677 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
679 pltevent = PyString_FromString("UPDATE");
681 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
682 tdata->tg_relation->rd_att);
683 PyDict_SetItemString(pltdata, "new", pytnew);
685 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
686 tdata->tg_relation->rd_att);
687 PyDict_SetItemString(pltdata, "old", pytold);
689 *rv = tdata->tg_newtuple;
693 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
694 pltevent = NULL; /* keep compiler quiet */
697 PyDict_SetItemString(pltdata, "event", pltevent);
700 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
702 pltlevel = PyString_FromString("STATEMENT");
703 PyDict_SetItemString(pltdata, "level", pltlevel);
706 PyDict_SetItemString(pltdata, "old", Py_None);
707 PyDict_SetItemString(pltdata, "new", Py_None);
710 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
711 pltevent = PyString_FromString("INSERT");
712 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
713 pltevent = PyString_FromString("DELETE");
714 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
715 pltevent = PyString_FromString("UPDATE");
718 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
719 pltevent = NULL; /* keep compiler quiet */
722 PyDict_SetItemString(pltdata, "event", pltevent);
726 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
728 if (tdata->tg_trigger->tgnargs)
736 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
737 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
739 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
742 * stolen, don't Py_DECREF
744 PyList_SetItem(pltargs, i, pltarg);
752 PyDict_SetItemString(pltdata, "args", pltargs);
767 /* function handler and friends */
769 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
772 PyObject *volatile plargs = NULL;
773 PyObject *volatile plrv = NULL;
774 PyObject *volatile plrv_so = NULL;
779 if (!proc->is_setof || proc->setof == NULL)
781 /* Simple type returning function or first time for SETOF function */
782 plargs = PLy_function_build_args(fcinfo, proc);
783 plrv = PLy_procedure_call(proc, "args", plargs);
787 * SETOF function parameters will be deleted when last row is
790 PLy_function_delete_args(proc);
791 Assert(plrv != NULL);
792 Assert(!PLy_error_in_progress);
796 * Disconnect from SPI manager and then create the return values datum
797 * (if the input function does a palloc for it this must not be
798 * allocated in the SPI memory context because SPI_finish would free
801 if (SPI_finish() != SPI_OK_FINISH)
802 elog(ERROR, "SPI_finish failed");
806 bool has_error = false;
807 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
809 if (proc->setof == NULL)
811 /* first time -- do checks and setup */
812 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
813 (rsi->allowedModes & SFRM_ValuePerCall) == 0)
816 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
817 errmsg("only value per call is allowed")));
819 rsi->returnMode = SFRM_ValuePerCall;
821 /* Make iterator out of returned object */
822 proc->setof = PyObject_GetIter(plrv);
826 if (proc->setof == NULL)
828 (errcode(ERRCODE_DATATYPE_MISMATCH),
829 errmsg("returned object cannot be iterated"),
830 errdetail("SETOF must be returned as iterable object")));
833 /* Fetch next from iterator */
834 plrv = PyIter_Next(proc->setof);
836 rsi->isDone = ExprMultipleResult;
839 rsi->isDone = ExprEndResult;
840 has_error = PyErr_Occurred() != NULL;
843 if (rsi->isDone == ExprEndResult)
845 /* Iterator is exhausted or error happened */
846 Py_DECREF(proc->setof);
853 PLy_function_delete_args(proc);
857 (errcode(ERRCODE_DATA_EXCEPTION),
858 errmsg("error fetching next item from iterator")));
860 fcinfo->isnull = true;
866 * If the function is declared to return void, the Python return value
867 * must be None. For void-returning functions, we also treat a None
868 * return value as a special "void datum" rather than NULL (as is the
869 * case for non-void-returning functions).
871 if (proc->result.out.d.typoid == VOIDOID)
875 (errcode(ERRCODE_DATATYPE_MISMATCH),
876 errmsg("invalid return value from plpython function"),
877 errdetail("Functions returning type \"void\" must return None.")));
879 fcinfo->isnull = false;
882 else if (plrv == Py_None)
884 fcinfo->isnull = true;
885 if (proc->result.is_rowtype < 1)
886 rv = InputFunctionCall(&proc->result.out.d.typfunc,
888 proc->result.out.d.typioparam,
894 else if (proc->result.is_rowtype >= 1)
896 HeapTuple tuple = NULL;
898 if (PySequence_Check(plrv))
899 /* composite type as sequence (tuple, list etc) */
900 tuple = PLySequence_ToTuple(&proc->result, plrv);
901 else if (PyMapping_Check(plrv))
902 /* composite type as mapping (currently only dict) */
903 tuple = PLyMapping_ToTuple(&proc->result, plrv);
905 /* returned as smth, must provide method __getattr__(name) */
906 tuple = PLyObject_ToTuple(&proc->result, plrv);
910 fcinfo->isnull = false;
911 rv = HeapTupleGetDatum(tuple);
915 fcinfo->isnull = true;
921 fcinfo->isnull = false;
922 plrv_so = PyObject_Str(plrv);
924 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
925 plrv_sc = PyString_AsString(plrv_so);
926 rv = InputFunctionCall(&proc->result.out.d.typfunc,
928 proc->result.out.d.typioparam,
950 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
954 PyDict_SetItemString(proc->globals, kargs, vargs);
955 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
956 proc->globals, proc->globals);
959 * If there was an error in a PG callback, propagate that no matter what
960 * Python claims about its success.
962 if (PLy_error_in_progress)
964 ErrorData *edata = PLy_error_in_progress;
966 PLy_error_in_progress = NULL;
970 if (rv == NULL || PyErr_Occurred())
973 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
980 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
982 PyObject *volatile arg = NULL;
983 PyObject *volatile args = NULL;
988 args = PyList_New(proc->nargs);
989 for (i = 0; i < proc->nargs; i++)
991 if (proc->args[i].is_rowtype > 0)
993 if (fcinfo->argnull[i])
1001 HeapTupleData tmptup;
1003 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
1004 /* Extract rowtype info and find a tupdesc */
1005 tupType = HeapTupleHeaderGetTypeId(td);
1006 tupTypmod = HeapTupleHeaderGetTypMod(td);
1007 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1009 /* Set up I/O funcs if not done yet */
1010 if (proc->args[i].is_rowtype != 1)
1011 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
1013 /* Build a temporary HeapTuple control structure */
1014 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1017 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
1018 ReleaseTupleDesc(tupdesc);
1023 if (fcinfo->argnull[i])
1029 ct = OutputFunctionCall(&(proc->args[i].in.d.typfunc),
1031 arg = (proc->args[i].in.d.func) (ct);
1042 if (PyList_SetItem(args, i, arg) == -1 ||
1044 PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1))
1045 PLy_elog(ERROR, "problem setting up arguments for \"%s\"", proc->proname);
1063 PLy_function_delete_args(PLyProcedure * proc)
1067 if (!proc->argnames)
1070 for (i = 0; i < proc->nargs; i++)
1071 PyDict_DelItemString(proc->globals, proc->argnames[i]);
1076 * PLyProcedure functions
1079 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
1080 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
1081 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
1084 static PLyProcedure *
1085 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
1091 PLyProcedure *proc = NULL;
1094 fn_oid = fcinfo->flinfo->fn_oid;
1095 procTup = SearchSysCache(PROCOID,
1096 ObjectIdGetDatum(fn_oid),
1098 if (!HeapTupleIsValid(procTup))
1099 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1101 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
1102 if (rv >= sizeof(key) || rv < 0)
1103 elog(ERROR, "key too long");
1105 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
1110 if (!PyCObject_Check(plproc))
1111 elog(FATAL, "expected a PyCObject, didn't get one");
1113 proc = PyCObject_AsVoidPtr(plproc);
1114 if (proc->me != plproc)
1115 elog(FATAL, "proc->me != plproc");
1116 /* did we find an up-to-date cache entry? */
1117 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
1118 !ItemPointerEquals(&proc->fn_tid, &procTup->t_self))
1126 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
1128 ReleaseSysCache(procTup);
1133 static PLyProcedure *
1134 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
1135 HeapTuple procTup, char *key)
1137 char procName[NAMEDATALEN + 256];
1138 Form_pg_proc procStruct;
1139 PLyProcedure *volatile proc;
1140 char *volatile procSource = NULL;
1149 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1151 if (OidIsValid(tgreloid))
1152 rv = snprintf(procName, sizeof(procName),
1153 "__plpython_procedure_%s_%u_trigger_%u",
1154 NameStr(procStruct->proname),
1155 fcinfo->flinfo->fn_oid,
1158 rv = snprintf(procName, sizeof(procName),
1159 "__plpython_procedure_%s_%u",
1160 NameStr(procStruct->proname),
1161 fcinfo->flinfo->fn_oid);
1162 if (rv >= sizeof(procName) || rv < 0)
1163 elog(ERROR, "procedure name would overrun buffer");
1165 proc = PLy_malloc(sizeof(PLyProcedure));
1166 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1167 proc->pyname = PLy_strdup(procName);
1168 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1169 proc->fn_tid = procTup->t_self;
1170 /* Remember if function is STABLE/IMMUTABLE */
1172 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1173 PLy_typeinfo_init(&proc->result);
1174 for (i = 0; i < FUNC_MAX_ARGS; i++)
1175 PLy_typeinfo_init(&proc->args[i]);
1177 proc->code = proc->statics = NULL;
1178 proc->globals = proc->me = NULL;
1179 proc->is_setof = procStruct->proretset;
1181 proc->argnames = NULL;
1186 * get information required for output conversion of the return value,
1187 * but only if this isn't a trigger.
1189 if (!CALLED_AS_TRIGGER(fcinfo))
1191 HeapTuple rvTypeTup;
1192 Form_pg_type rvTypeStruct;
1194 rvTypeTup = SearchSysCache(TYPEOID,
1195 ObjectIdGetDatum(procStruct->prorettype),
1197 if (!HeapTupleIsValid(rvTypeTup))
1198 elog(ERROR, "cache lookup failed for type %u",
1199 procStruct->prorettype);
1200 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1202 /* Disallow pseudotype result, except for void */
1203 if (rvTypeStruct->typtype == TYPTYPE_PSEUDO &&
1204 procStruct->prorettype != VOIDOID)
1206 if (procStruct->prorettype == TRIGGEROID)
1208 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1209 errmsg("trigger functions can only be called as triggers")));
1212 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1213 errmsg("plpython functions cannot return type %s",
1214 format_type_be(procStruct->prorettype))));
1217 if (rvTypeStruct->typtype == TYPTYPE_COMPOSITE)
1220 * Tuple: set up later, during first call to
1221 * PLy_function_handler
1223 proc->result.out.d.typoid = procStruct->prorettype;
1224 proc->result.is_rowtype = 2;
1227 PLy_output_datum_func(&proc->result, rvTypeTup);
1229 ReleaseSysCache(rvTypeTup);
1234 * input/output conversion for trigger tuples. use the result
1235 * TypeInfo variable to store the tuple conversion info.
1237 TriggerData *tdata = (TriggerData *) fcinfo->context;
1239 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1240 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1244 * now get information required for input conversion of the
1245 * procedure's arguments.
1247 proc->nargs = fcinfo->nargs;
1250 argnames = SysCacheGetAttr(PROCOID, procTup, Anum_pg_proc_proargnames, &isnull);
1253 deconstruct_array(DatumGetArrayTypeP(argnames), TEXTOID, -1, false, 'i',
1254 &elems, NULL, &nelems);
1255 if (nelems != proc->nargs)
1257 "proargnames must have the same number of elements "
1258 "as the function has arguments");
1259 proc->argnames = (char **) PLy_malloc(sizeof(char *) * proc->nargs);
1260 memset(proc->argnames, 0, sizeof(char *) * proc->nargs);
1263 for (i = 0; i < fcinfo->nargs; i++)
1265 HeapTuple argTypeTup;
1266 Form_pg_type argTypeStruct;
1268 argTypeTup = SearchSysCache(TYPEOID,
1269 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1271 if (!HeapTupleIsValid(argTypeTup))
1272 elog(ERROR, "cache lookup failed for type %u",
1273 procStruct->proargtypes.values[i]);
1274 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1276 /* Disallow pseudotype argument */
1277 if (argTypeStruct->typtype == TYPTYPE_PSEUDO)
1279 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1280 errmsg("plpython functions cannot take type %s",
1281 format_type_be(procStruct->proargtypes.values[i]))));
1283 if (argTypeStruct->typtype != TYPTYPE_COMPOSITE)
1284 PLy_input_datum_func(&(proc->args[i]),
1285 procStruct->proargtypes.values[i],
1288 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1290 ReleaseSysCache(argTypeTup);
1292 /* Fetch argument name */
1294 proc->argnames[i] = PLy_strdup(DatumGetCString(DirectFunctionCall1(textout, elems[i])));
1298 * get the text of the function.
1300 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1301 Anum_pg_proc_prosrc, &isnull);
1303 elog(ERROR, "null prosrc");
1304 procSource = DatumGetCString(DirectFunctionCall1(textout,
1307 PLy_procedure_compile(proc, procSource);
1311 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1312 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1316 PLy_procedure_delete(proc);
1328 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1330 PyObject *crv = NULL;
1333 proc->globals = PyDict_Copy(PLy_interp_globals);
1336 * SD is private preserved data between calls. GD is global data shared by
1339 proc->statics = PyDict_New();
1340 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1343 * insert the function code into the interpreter
1345 msrc = PLy_procedure_munge_source(proc->pyname, src);
1346 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1349 if (crv != NULL && (!PyErr_Occurred()))
1352 char call[NAMEDATALEN + 256];
1357 * compile a call to the function
1359 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1360 if (clen < 0 || clen >= sizeof(call))
1361 elog(ERROR, "string would overflow buffer");
1362 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1363 if (proc->code != NULL && (!PyErr_Occurred()))
1369 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1373 PLy_procedure_munge_source(const char *name, const char *src)
1382 * room for function source and the def statement
1384 mlen = (strlen(src) * 2) + strlen(name) + 16;
1386 mrc = PLy_malloc(mlen);
1387 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1388 Assert(plen >= 0 && plen < mlen);
1395 if (*sp == '\r' && *(sp + 1) == '\n')
1398 if (*sp == '\n' || *sp == '\r')
1411 if (mp > (mrc + mlen))
1412 elog(FATAL, "buffer overrun in PLy_munge_source");
1418 PLy_procedure_delete(PLyProcedure * proc)
1422 Py_XDECREF(proc->code);
1423 Py_XDECREF(proc->statics);
1424 Py_XDECREF(proc->globals);
1425 Py_XDECREF(proc->me);
1427 PLy_free(proc->proname);
1429 PLy_free(proc->pyname);
1430 for (i = 0; i < proc->nargs; i++)
1432 if (proc->args[i].is_rowtype == 1)
1434 if (proc->args[i].in.r.atts)
1435 PLy_free(proc->args[i].in.r.atts);
1436 if (proc->args[i].out.r.atts)
1437 PLy_free(proc->args[i].out.r.atts);
1439 if (proc->argnames && proc->argnames[i])
1440 PLy_free(proc->argnames[i]);
1443 PLy_free(proc->argnames);
1446 /* conversion functions. remember output from python is
1447 * input to postgresql, and vis versa.
1450 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1454 if (arg->is_rowtype == 0)
1455 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1457 arg->is_rowtype = 1;
1458 arg->in.r.natts = desc->natts;
1459 arg->in.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1461 for (i = 0; i < desc->natts; i++)
1465 if (desc->attrs[i]->attisdropped)
1468 typeTup = SearchSysCache(TYPEOID,
1469 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1471 if (!HeapTupleIsValid(typeTup))
1472 elog(ERROR, "cache lookup failed for type %u",
1473 desc->attrs[i]->atttypid);
1475 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1476 desc->attrs[i]->atttypid,
1479 ReleaseSysCache(typeTup);
1484 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1488 if (arg->is_rowtype == 0)
1489 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1491 arg->is_rowtype = 1;
1492 arg->out.r.natts = desc->natts;
1493 arg->out.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1495 for (i = 0; i < desc->natts; i++)
1499 if (desc->attrs[i]->attisdropped)
1502 typeTup = SearchSysCache(TYPEOID,
1503 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1505 if (!HeapTupleIsValid(typeTup))
1506 elog(ERROR, "cache lookup failed for type %u",
1507 desc->attrs[i]->atttypid);
1509 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1511 ReleaseSysCache(typeTup);
1516 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1518 if (arg->is_rowtype > 0)
1519 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1520 arg->is_rowtype = 0;
1521 PLy_output_datum_func2(&(arg->out.d), typeTup);
1525 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1527 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1529 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1530 arg->typoid = HeapTupleGetOid(typeTup);
1531 arg->typioparam = getTypeIOParam(typeTup);
1532 arg->typbyval = typeStruct->typbyval;
1536 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1538 if (arg->is_rowtype > 0)
1539 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1540 arg->is_rowtype = 0;
1541 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1545 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1547 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1549 /* Get the type's conversion information */
1550 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1551 arg->typioparam = getTypeIOParam(typeTup);
1552 arg->typbyval = typeStruct->typbyval;
1554 /* Determine which kind of Python object we will convert to */
1558 arg->func = PLyBool_FromString;
1563 arg->func = PLyFloat_FromString;
1567 arg->func = PLyInt_FromString;
1570 arg->func = PLyLong_FromString;
1573 arg->func = PLyString_FromString;
1579 PLy_typeinfo_init(PLyTypeInfo * arg)
1581 arg->is_rowtype = -1;
1582 arg->in.r.natts = arg->out.r.natts = 0;
1583 arg->in.r.atts = NULL;
1584 arg->out.r.atts = NULL;
1588 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1590 if (arg->is_rowtype == 1)
1593 PLy_free(arg->in.r.atts);
1594 if (arg->out.r.atts)
1595 PLy_free(arg->out.r.atts);
1599 /* assumes that a bool is always returned as a 't' or 'f' */
1601 PLyBool_FromString(const char *src)
1604 * We would like to use Py_RETURN_TRUE and Py_RETURN_FALSE here for
1605 * generating SQL from trigger functions, but those are only supported in
1606 * Python >= 2.3, and we support older versions.
1607 * http://docs.python.org/api/boolObjects.html
1610 return PyBool_FromLong(1);
1611 return PyBool_FromLong(0);
1615 PLyFloat_FromString(const char *src)
1621 v = strtod(src, &eptr);
1622 if (*eptr != '\0' || errno)
1624 return PyFloat_FromDouble(v);
1628 PLyInt_FromString(const char *src)
1634 v = strtol(src, &eptr, 0);
1635 if (*eptr != '\0' || errno)
1637 return PyInt_FromLong(v);
1641 PLyLong_FromString(const char *src)
1643 return PyLong_FromString((char *) src, NULL, 0);
1647 PLyString_FromString(const char *src)
1649 return PyString_FromString(src);
1653 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1655 PyObject *volatile dict;
1658 if (info->is_rowtype != 1)
1659 elog(ERROR, "PLyTypeInfo structure describes a datum");
1661 dict = PyDict_New();
1663 PLy_elog(ERROR, "could not create tuple dictionary");
1667 for (i = 0; i < info->in.r.natts; i++)
1675 if (desc->attrs[i]->attisdropped)
1678 key = NameStr(desc->attrs[i]->attname);
1679 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1681 if (is_null || info->in.r.atts[i].func == NULL)
1682 PyDict_SetItemString(dict, key, Py_None);
1685 vsrc = OutputFunctionCall(&info->in.r.atts[i].typfunc,
1689 * no exceptions allowed
1691 value = info->in.r.atts[i].func(vsrc);
1693 PyDict_SetItemString(dict, key, value);
1710 PLyMapping_ToTuple(PLyTypeInfo * info, PyObject * mapping)
1718 Assert(PyMapping_Check(mapping));
1720 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1721 if (info->is_rowtype == 2)
1722 PLy_output_tuple_funcs(info, desc);
1723 Assert(info->is_rowtype == 1);
1726 values = palloc(sizeof(Datum) * desc->natts);
1727 nulls = palloc(sizeof(char) * desc->natts);
1728 for (i = 0; i < desc->natts; ++i)
1731 PyObject *volatile value,
1734 key = NameStr(desc->attrs[i]->attname);
1738 value = PyMapping_GetItemString(mapping, key);
1739 if (value == Py_None)
1741 values[i] = (Datum) NULL;
1748 so = PyObject_Str(value);
1750 PLy_elog(ERROR, "cannot convert mapping type");
1751 valuestr = PyString_AsString(so);
1753 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1755 ,info->out.r.atts[i].typioparam
1763 (errcode(ERRCODE_UNDEFINED_COLUMN),
1764 errmsg("no mapping found with key \"%s\"", key),
1765 errhint("to return null in specific column, "
1766 "add value None to map with key named after column")));
1780 tuple = heap_formtuple(desc, values, nulls);
1781 ReleaseTupleDesc(desc);
1790 PLySequence_ToTuple(PLyTypeInfo * info, PyObject * sequence)
1798 Assert(PySequence_Check(sequence));
1801 * Check that sequence length is exactly same as PG tuple's. We actually
1802 * can ignore exceeding items or assume missing ones as null but to avoid
1803 * plpython developer's errors we are strict here
1805 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1806 if (PySequence_Length(sequence) != desc->natts)
1808 (errcode(ERRCODE_DATATYPE_MISMATCH),
1809 errmsg("returned sequence's length must be same as tuple's length")));
1811 if (info->is_rowtype == 2)
1812 PLy_output_tuple_funcs(info, desc);
1813 Assert(info->is_rowtype == 1);
1816 values = palloc(sizeof(Datum) * desc->natts);
1817 nulls = palloc(sizeof(char) * desc->natts);
1818 for (i = 0; i < desc->natts; ++i)
1820 PyObject *volatile value,
1826 value = PySequence_GetItem(sequence, i);
1828 if (value == Py_None)
1830 values[i] = (Datum) NULL;
1837 so = PyObject_Str(value);
1839 PLy_elog(ERROR, "cannot convert sequence type");
1840 valuestr = PyString_AsString(so);
1841 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1843 ,info->out.r.atts[i].typioparam
1862 tuple = heap_formtuple(desc, values, nulls);
1863 ReleaseTupleDesc(desc);
1872 PLyObject_ToTuple(PLyTypeInfo * info, PyObject * object)
1880 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1881 if (info->is_rowtype == 2)
1882 PLy_output_tuple_funcs(info, desc);
1883 Assert(info->is_rowtype == 1);
1886 values = palloc(sizeof(Datum) * desc->natts);
1887 nulls = palloc(sizeof(char) * desc->natts);
1888 for (i = 0; i < desc->natts; ++i)
1891 PyObject *volatile value,
1894 key = NameStr(desc->attrs[i]->attname);
1898 value = PyObject_GetAttrString(object, key);
1899 if (value == Py_None)
1901 values[i] = (Datum) NULL;
1908 so = PyObject_Str(value);
1910 PLy_elog(ERROR, "cannot convert object type");
1911 valuestr = PyString_AsString(so);
1912 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1914 ,info->out.r.atts[i].typioparam
1922 (errcode(ERRCODE_UNDEFINED_COLUMN),
1923 errmsg("no attribute named \"%s\"", key),
1924 errhint("to return null in specific column, "
1925 "let returned object to have attribute named "
1926 "after column with value None")));
1940 tuple = heap_formtuple(desc, values, nulls);
1941 ReleaseTupleDesc(desc);
1949 /* initialization, some python variables function declared here */
1951 /* interface to postgresql elog */
1952 static PyObject *PLy_debug(PyObject *, PyObject *);
1953 static PyObject *PLy_log(PyObject *, PyObject *);
1954 static PyObject *PLy_info(PyObject *, PyObject *);
1955 static PyObject *PLy_notice(PyObject *, PyObject *);
1956 static PyObject *PLy_warning(PyObject *, PyObject *);
1957 static PyObject *PLy_error(PyObject *, PyObject *);
1958 static PyObject *PLy_fatal(PyObject *, PyObject *);
1960 /* PLyPlanObject, PLyResultObject and SPI interface */
1961 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1962 static PyObject *PLy_plan_new(void);
1963 static void PLy_plan_dealloc(PyObject *);
1964 static PyObject *PLy_plan_getattr(PyObject *, char *);
1965 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1967 static PyObject *PLy_result_new(void);
1968 static void PLy_result_dealloc(PyObject *);
1969 static PyObject *PLy_result_getattr(PyObject *, char *);
1970 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1971 static PyObject *PLy_result_status(PyObject *, PyObject *);
1972 static Py_ssize_t PLy_result_length(PyObject *);
1973 static PyObject *PLy_result_item(PyObject *, Py_ssize_t);
1974 static PyObject *PLy_result_slice(PyObject *, Py_ssize_t, Py_ssize_t);
1975 static int PLy_result_ass_item(PyObject *, Py_ssize_t, PyObject *);
1976 static int PLy_result_ass_slice(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
1979 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1980 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1981 static PyObject *PLy_spi_execute_query(char *query, long limit);
1982 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1983 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1986 static PyTypeObject PLy_PlanType = {
1987 PyObject_HEAD_INIT(NULL)
1989 "PLyPlan", /* tp_name */
1990 sizeof(PLyPlanObject), /* tp_size */
1991 0, /* tp_itemsize */
1996 PLy_plan_dealloc, /* tp_dealloc */
1998 PLy_plan_getattr, /* tp_getattr */
2002 0, /* tp_as_number */
2003 0, /* tp_as_sequence */
2004 0, /* tp_as_mapping */
2008 0, /* tp_getattro */
2009 0, /* tp_setattro */
2010 0, /* tp_as_buffer */
2011 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2012 PLy_plan_doc, /* tp_doc */
2015 static PyMethodDef PLy_plan_methods[] = {
2016 {"status", PLy_plan_status, METH_VARARGS, NULL},
2017 {NULL, NULL, 0, NULL}
2020 static PySequenceMethods PLy_result_as_sequence = {
2021 PLy_result_length, /* sq_length */
2022 NULL, /* sq_concat */
2023 NULL, /* sq_repeat */
2024 PLy_result_item, /* sq_item */
2025 PLy_result_slice, /* sq_slice */
2026 PLy_result_ass_item, /* sq_ass_item */
2027 PLy_result_ass_slice, /* sq_ass_slice */
2030 static PyTypeObject PLy_ResultType = {
2031 PyObject_HEAD_INIT(NULL)
2033 "PLyResult", /* tp_name */
2034 sizeof(PLyResultObject), /* tp_size */
2035 0, /* tp_itemsize */
2040 PLy_result_dealloc, /* tp_dealloc */
2042 PLy_result_getattr, /* tp_getattr */
2046 0, /* tp_as_number */
2047 &PLy_result_as_sequence, /* tp_as_sequence */
2048 0, /* tp_as_mapping */
2052 0, /* tp_getattro */
2053 0, /* tp_setattro */
2054 0, /* tp_as_buffer */
2055 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2056 PLy_result_doc, /* tp_doc */
2059 static PyMethodDef PLy_result_methods[] = {
2060 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
2061 {"status", PLy_result_status, METH_VARARGS, NULL},
2062 {NULL, NULL, 0, NULL}
2065 static PyMethodDef PLy_methods[] = {
2069 {"debug", PLy_debug, METH_VARARGS, NULL},
2070 {"log", PLy_log, METH_VARARGS, NULL},
2071 {"info", PLy_info, METH_VARARGS, NULL},
2072 {"notice", PLy_notice, METH_VARARGS, NULL},
2073 {"warning", PLy_warning, METH_VARARGS, NULL},
2074 {"error", PLy_error, METH_VARARGS, NULL},
2075 {"fatal", PLy_fatal, METH_VARARGS, NULL},
2078 * create a stored plan
2080 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
2083 * execute a plan or query
2085 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
2087 {NULL, NULL, 0, NULL}
2091 /* plan object methods */
2097 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
2105 return (PyObject *) ob;
2110 PLy_plan_dealloc(PyObject * arg)
2112 PLyPlanObject *ob = (PLyPlanObject *) arg;
2115 SPI_freeplan(ob->plan);
2117 PLy_free(ob->types);
2122 for (i = 0; i < ob->nargs; i++)
2123 PLy_typeinfo_dealloc(&ob->args[i]);
2127 arg->ob_type->tp_free(arg);
2132 PLy_plan_getattr(PyObject * self, char *name)
2134 return Py_FindMethod(PLy_plan_methods, self, name);
2138 PLy_plan_status(PyObject * self, PyObject * args)
2140 if (PyArg_ParseTuple(args, ""))
2144 /* return PyInt_FromLong(self->status); */
2146 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
2152 /* result object methods */
2155 PLy_result_new(void)
2157 PLyResultObject *ob;
2159 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
2162 /* ob->tuples = NULL; */
2165 ob->status = Py_None;
2166 ob->nrows = PyInt_FromLong(-1);
2167 ob->rows = PyList_New(0);
2169 return (PyObject *) ob;
2173 PLy_result_dealloc(PyObject * arg)
2175 PLyResultObject *ob = (PLyResultObject *) arg;
2177 Py_XDECREF(ob->nrows);
2178 Py_XDECREF(ob->rows);
2179 Py_XDECREF(ob->status);
2181 arg->ob_type->tp_free(arg);
2185 PLy_result_getattr(PyObject * self, char *name)
2187 return Py_FindMethod(PLy_result_methods, self, name);
2191 PLy_result_nrows(PyObject * self, PyObject * args)
2193 PLyResultObject *ob = (PLyResultObject *) self;
2195 Py_INCREF(ob->nrows);
2200 PLy_result_status(PyObject * self, PyObject * args)
2202 PLyResultObject *ob = (PLyResultObject *) self;
2204 Py_INCREF(ob->status);
2209 PLy_result_length(PyObject * arg)
2211 PLyResultObject *ob = (PLyResultObject *) arg;
2213 return PyList_Size(ob->rows);
2217 PLy_result_item(PyObject * arg, Py_ssize_t idx)
2220 PLyResultObject *ob = (PLyResultObject *) arg;
2222 rv = PyList_GetItem(ob->rows, idx);
2229 PLy_result_ass_item(PyObject * arg, Py_ssize_t idx, PyObject * item)
2232 PLyResultObject *ob = (PLyResultObject *) arg;
2235 rv = PyList_SetItem(ob->rows, idx, item);
2240 PLy_result_slice(PyObject * arg, Py_ssize_t lidx, Py_ssize_t hidx)
2243 PLyResultObject *ob = (PLyResultObject *) arg;
2245 rv = PyList_GetSlice(ob->rows, lidx, hidx);
2253 PLy_result_ass_slice(PyObject * arg, Py_ssize_t lidx, Py_ssize_t hidx, PyObject * slice)
2256 PLyResultObject *ob = (PLyResultObject *) arg;
2258 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
2264 PLy_spi_prepare(PyObject * self, PyObject * args)
2266 PLyPlanObject *plan;
2267 PyObject *list = NULL;
2268 PyObject *volatile optr = NULL;
2271 MemoryContext oldcontext;
2273 /* Can't execute more if we have an unhandled error */
2274 if (PLy_error_in_progress)
2276 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2280 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
2282 PyErr_SetString(PLy_exc_spi_error,
2283 "Invalid arguments for plpy.prepare()");
2287 if (list && (!PySequence_Check(list)))
2289 PyErr_SetString(PLy_exc_spi_error,
2290 "Second argument in plpy.prepare() must be a sequence");
2294 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
2297 oldcontext = CurrentMemoryContext;
2305 nargs = PySequence_Length(list);
2308 plan->nargs = nargs;
2309 plan->types = PLy_malloc(sizeof(Oid) * nargs);
2310 plan->values = PLy_malloc(sizeof(Datum) * nargs);
2311 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
2314 * the other loop might throw an exception, if PLyTypeInfo
2315 * member isn't properly initialized the Py_DECREF(plan) will
2318 for (i = 0; i < nargs; i++)
2320 PLy_typeinfo_init(&plan->args[i]);
2321 plan->values[i] = PointerGetDatum(NULL);
2324 for (i = 0; i < nargs; i++)
2330 Form_pg_type typeStruct;
2332 optr = PySequence_GetItem(list, i);
2333 if (!PyString_Check(optr))
2334 elog(ERROR, "Type names must be strings.");
2335 sptr = PyString_AsString(optr);
2337 /********************************************************
2338 * Resolve argument type names and then look them up by
2339 * oid in the system cache, and remember the required
2340 *information for input conversion.
2341 ********************************************************/
2343 parseTypeString(sptr, &typeId, &typmod);
2345 typeTup = SearchSysCache(TYPEOID,
2346 ObjectIdGetDatum(typeId),
2348 if (!HeapTupleIsValid(typeTup))
2349 elog(ERROR, "cache lookup failed for type %u", typeId);
2352 optr = NULL; /* this is important */
2354 plan->types[i] = typeId;
2355 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2356 if (typeStruct->typtype != TYPTYPE_COMPOSITE)
2357 PLy_output_datum_func(&plan->args[i], typeTup);
2359 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
2360 ReleaseSysCache(typeTup);
2365 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2366 if (plan->plan == NULL)
2367 elog(ERROR, "SPI_prepare failed: %s",
2368 SPI_result_code_string(SPI_result));
2370 /* transfer plan from procCxt to topCxt */
2371 tmpplan = plan->plan;
2372 plan->plan = SPI_saveplan(tmpplan);
2373 SPI_freeplan(tmpplan);
2374 if (plan->plan == NULL)
2375 elog(ERROR, "SPI_saveplan failed: %s",
2376 SPI_result_code_string(SPI_result));
2380 MemoryContextSwitchTo(oldcontext);
2381 PLy_error_in_progress = CopyErrorData();
2385 if (!PyErr_Occurred())
2386 PyErr_SetString(PLy_exc_spi_error,
2387 "Unknown error in PLy_spi_prepare");
2388 /* XXX this oughta be replaced with errcontext mechanism */
2389 PLy_elog(WARNING, "in function %s:",
2390 PLy_procedure_name(PLy_curr_procedure));
2395 return (PyObject *) plan;
2398 /* execute(query="select * from foo", limit=5)
2399 * execute(plan=plan, values=(foo, bar), limit=5)
2402 PLy_spi_execute(PyObject * self, PyObject * args)
2406 PyObject *list = NULL;
2409 /* Can't execute more if we have an unhandled error */
2410 if (PLy_error_in_progress)
2412 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2416 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
2417 return PLy_spi_execute_query(query, limit);
2421 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
2422 is_PLyPlanObject(plan))
2423 return PLy_spi_execute_plan(plan, list, limit);
2425 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2430 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
2435 PLyPlanObject *plan;
2436 MemoryContext oldcontext;
2440 if (!PySequence_Check(list) || PyString_Check(list))
2442 char *msg = "plpy.execute() takes a sequence as its second argument";
2444 PyErr_SetString(PLy_exc_spi_error, msg);
2447 nargs = PySequence_Length(list);
2452 plan = (PLyPlanObject *) ob;
2454 if (nargs != plan->nargs)
2457 PyObject *so = PyObject_Str(list);
2460 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2461 PLy_procedure_name(PLy_curr_procedure));
2462 sv = PyString_AsString(so);
2463 PLy_exception_set(PLy_exc_spi_error,
2464 "Expected sequence of %d arguments, got %d. %s",
2465 plan->nargs, nargs, sv);
2471 oldcontext = CurrentMemoryContext;
2474 char *nulls = palloc(nargs * sizeof(char));
2477 for (j = 0; j < nargs; j++)
2482 elem = PySequence_GetItem(list, j);
2483 if (elem != Py_None)
2485 so = PyObject_Str(elem);
2487 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2488 PLy_procedure_name(PLy_curr_procedure));
2493 char *sv = PyString_AsString(so);
2496 InputFunctionCall(&(plan->args[j].out.d.typfunc),
2498 plan->args[j].out.d.typioparam,
2515 InputFunctionCall(&(plan->args[j].out.d.typfunc),
2517 plan->args[j].out.d.typioparam,
2523 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2524 PLy_curr_procedure->fn_readonly, limit);
2532 MemoryContextSwitchTo(oldcontext);
2533 PLy_error_in_progress = CopyErrorData();
2537 * cleanup plan->values array
2539 for (k = 0; k < nargs; k++)
2541 if (!plan->args[k].out.d.typbyval &&
2542 (plan->values[k] != PointerGetDatum(NULL)))
2544 pfree(DatumGetPointer(plan->values[k]));
2545 plan->values[k] = PointerGetDatum(NULL);
2549 if (!PyErr_Occurred())
2550 PyErr_SetString(PLy_exc_error,
2551 "Unknown error in PLy_spi_execute_plan");
2552 /* XXX this oughta be replaced with errcontext mechanism */
2553 PLy_elog(WARNING, "in function %s:",
2554 PLy_procedure_name(PLy_curr_procedure));
2559 for (i = 0; i < nargs; i++)
2561 if (!plan->args[i].out.d.typbyval &&
2562 (plan->values[i] != PointerGetDatum(NULL)))
2564 pfree(DatumGetPointer(plan->values[i]));
2565 plan->values[i] = PointerGetDatum(NULL);
2571 PLy_exception_set(PLy_exc_spi_error,
2572 "SPI_execute_plan failed: %s",
2573 SPI_result_code_string(rv));
2577 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2581 PLy_spi_execute_query(char *query, long limit)
2584 MemoryContext oldcontext;
2586 oldcontext = CurrentMemoryContext;
2589 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2593 MemoryContextSwitchTo(oldcontext);
2594 PLy_error_in_progress = CopyErrorData();
2596 if (!PyErr_Occurred())
2597 PyErr_SetString(PLy_exc_spi_error,
2598 "Unknown error in PLy_spi_execute_query");
2599 /* XXX this oughta be replaced with errcontext mechanism */
2600 PLy_elog(WARNING, "in function %s:",
2601 PLy_procedure_name(PLy_curr_procedure));
2608 PLy_exception_set(PLy_exc_spi_error,
2609 "SPI_execute failed: %s",
2610 SPI_result_code_string(rv));
2614 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2618 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2620 PLyResultObject *result;
2621 MemoryContext oldcontext;
2623 result = (PLyResultObject *) PLy_result_new();
2624 Py_DECREF(result->status);
2625 result->status = PyInt_FromLong(status);
2627 if (status > 0 && tuptable == NULL)
2629 Py_DECREF(result->nrows);
2630 result->nrows = PyInt_FromLong(rows);
2632 else if (status > 0 && tuptable != NULL)
2637 Py_DECREF(result->nrows);
2638 result->nrows = PyInt_FromLong(rows);
2639 PLy_typeinfo_init(&args);
2641 oldcontext = CurrentMemoryContext;
2646 Py_DECREF(result->rows);
2647 result->rows = PyList_New(rows);
2649 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2650 for (i = 0; i < rows; i++)
2652 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2655 PyList_SetItem(result->rows, i, row);
2657 PLy_typeinfo_dealloc(&args);
2659 SPI_freetuptable(tuptable);
2664 MemoryContextSwitchTo(oldcontext);
2665 PLy_error_in_progress = CopyErrorData();
2667 if (!PyErr_Occurred())
2668 PyErr_SetString(PLy_exc_error,
2669 "Unknown error in PLy_spi_execute_fetch_result");
2671 PLy_typeinfo_dealloc(&args);
2677 return (PyObject *) result;
2682 * language handler and interpreter initialization
2686 * _PG_init() - library load-time initialization
2688 * DO NOT make this static nor change its name!
2693 /* Be sure we do initialization only once (should be redundant now) */
2694 static bool inited = false;
2702 if (PyErr_Occurred())
2703 PLy_elog(FATAL, "untrapped error in initialization");
2704 PLy_procedure_cache = PyDict_New();
2705 if (PLy_procedure_cache == NULL)
2706 PLy_elog(ERROR, "could not create procedure cache");
2712 PLy_init_interp(void)
2716 mainmod = PyImport_AddModule("__main__");
2717 if (mainmod == NULL || PyErr_Occurred())
2718 PLy_elog(ERROR, "could not import \"__main__\" module.");
2720 PLy_interp_globals = PyModule_GetDict(mainmod);
2721 PLy_interp_safe_globals = PyDict_New();
2722 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2724 if (PLy_interp_globals == NULL || PyErr_Occurred())
2725 PLy_elog(ERROR, "could not initialize globals");
2738 * initialize plpy module
2740 if (PyType_Ready(&PLy_PlanType) < 0)
2741 elog(ERROR, "could not init PLy_PlanType");
2742 if (PyType_Ready(&PLy_ResultType) < 0)
2743 elog(ERROR, "could not init PLy_ResultType");
2745 plpy = Py_InitModule("plpy", PLy_methods);
2746 plpy_dict = PyModule_GetDict(plpy);
2748 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2750 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2751 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2752 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2753 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2754 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2755 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2758 * initialize main module, and add plpy
2760 main_mod = PyImport_AddModule("__main__");
2761 main_dict = PyModule_GetDict(main_mod);
2762 plpy_mod = PyImport_AddModule("plpy");
2763 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2764 if (PyErr_Occurred())
2765 elog(ERROR, "could not init plpy");
2768 /* the python interface to the elog function
2769 * don't confuse these with PLy_elog
2771 static PyObject *PLy_output(volatile int, PyObject *, PyObject *);
2774 PLy_debug(PyObject * self, PyObject * args)
2776 return PLy_output(DEBUG2, self, args);
2780 PLy_log(PyObject * self, PyObject * args)
2782 return PLy_output(LOG, self, args);
2786 PLy_info(PyObject * self, PyObject * args)
2788 return PLy_output(INFO, self, args);
2792 PLy_notice(PyObject * self, PyObject * args)
2794 return PLy_output(NOTICE, self, args);
2798 PLy_warning(PyObject * self, PyObject * args)
2800 return PLy_output(WARNING, self, args);
2804 PLy_error(PyObject * self, PyObject * args)
2806 return PLy_output(ERROR, self, args);
2810 PLy_fatal(PyObject * self, PyObject * args)
2812 return PLy_output(FATAL, self, args);
2817 PLy_output(volatile int level, PyObject * self, PyObject * args)
2821 MemoryContext oldcontext;
2823 so = PyObject_Str(args);
2824 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2827 sv = "could not parse error message in `plpy.elog'";
2830 oldcontext = CurrentMemoryContext;
2833 elog(level, "%s", sv);
2837 MemoryContextSwitchTo(oldcontext);
2838 PLy_error_in_progress = CopyErrorData();
2843 * returning NULL here causes the python interpreter to bail. when
2844 * control passes back to PLy_procedure_call, we check for PG
2845 * exceptions and re-throw the error.
2847 PyErr_SetString(PLy_exc_error, sv);
2855 * return a legal object so the interpreter will continue on its merry way
2863 * Get the name of the last procedure called by the backend (the
2864 * innermost, if a plpython procedure call calls the backend and the
2865 * backend calls another plpython procedure).
2867 * NB: this returns the SQL name, not the internal Python procedure name
2870 PLy_procedure_name(PLyProcedure * proc)
2873 return "<unknown procedure>";
2874 return proc->proname;
2877 /* output a python traceback/exception via the postgresql elog
2878 * function. not pretty.
2881 PLy_exception_set(PyObject * exc, const char *fmt,...)
2887 vsnprintf(buf, sizeof(buf), fmt, ap);
2890 PyErr_SetString(exc, buf);
2893 /* Emit a PG error or notice, together with any available info about the
2894 * current Python error. This should be used to propagate Python errors
2898 PLy_elog(int elevel, const char *fmt,...)
2902 StringInfoData emsg;
2904 xmsg = PLy_traceback(&xlevel);
2906 initStringInfo(&emsg);
2913 success = appendStringInfoVA(&emsg, fmt, ap);
2917 enlargeStringInfo(&emsg, emsg.maxlen);
2923 (errmsg("plpython: %s", emsg.data),
2924 (xmsg) ? errdetail("%s", xmsg) : 0));
2941 PLy_traceback(int *xlevel)
2950 StringInfoData xstr;
2953 * get the current exception
2955 PyErr_Fetch(&e, &v, &tb);
2958 * oops, no exception, return
2966 PyErr_NormalizeException(&e, &v, &tb);
2969 eob = PyObject_Str(e);
2970 if (v && ((vob = PyObject_Str(v)) != NULL))
2971 vstr = PyString_AsString(vob);
2976 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
2977 * because that function calls us, so we could end up with infinite
2978 * recursion. I'm not even sure if eob could be NULL here -- would an
2979 * Assert() be more appropriate?
2981 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
2982 initStringInfo(&xstr);
2983 appendStringInfo(&xstr, "%s: %s", estr, vstr);
2990 * intuit an appropriate error level based on the exception type
2992 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
2994 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
3003 /* python module code */
3005 /* some dumb utility functions */
3007 PLy_malloc(size_t bytes)
3009 void *ptr = malloc(bytes);
3013 (errcode(ERRCODE_OUT_OF_MEMORY),
3014 errmsg("out of memory")));
3019 PLy_strdup(const char *str)
3024 len = strlen(str) + 1;
3025 result = PLy_malloc(len);
3026 memcpy(result, str, len);
3031 /* define this away */