1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.119 2009/03/26 22:26:08 petere 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 "catalog/pg_proc.h"
52 #include "catalog/pg_type.h"
53 #include "commands/trigger.h"
54 #include "executor/spi.h"
57 #include "miscadmin.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"
67 /* define our text domain for translations */
69 #define TEXTDOMAIN PG_TEXTDOMAIN("plpython")
76 /* convert Postgresql Datum or tuple into a PyObject.
77 * input to Python. Tuples are converted to dictionary
81 typedef PyObject *(*PLyDatumToObFunc) (const char *);
83 typedef struct PLyDatumToOb
85 PLyDatumToObFunc func;
86 FmgrInfo typfunc; /* The type's output function */
87 Oid typoid; /* The OID of the type */
92 typedef struct PLyTupleToOb
98 typedef union PLyTypeInput
104 /* convert PyObject to a Postgresql Datum or tuple.
107 typedef struct PLyObToDatum
109 FmgrInfo typfunc; /* The type's input function */
110 Oid typoid; /* The OID of the type */
115 typedef struct PLyObToTuple
121 typedef union PLyTypeOutput
127 /* all we need to move Postgresql data to Python objects,
130 typedef struct PLyTypeInfo
137 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
138 * 1 rowtype 2 rowtype, but I/O functions not set up yet
143 /* cached procedure data */
144 typedef struct PLyProcedure
146 char *proname; /* SQL name of procedure */
147 char *pyname; /* Python name of procedure */
148 TransactionId fn_xmin;
149 ItemPointerData fn_tid;
151 PLyTypeInfo result; /* also used to store info for trigger tuple
153 bool is_setof; /* true, if procedure returns result set */
154 PyObject *setof; /* contents of result set. */
155 char **argnames; /* Argument names */
156 PLyTypeInfo args[FUNC_MAX_ARGS];
158 PyObject *code; /* compiled procedure code */
159 PyObject *statics; /* data saved across calls, local scope */
160 PyObject *globals; /* data saved across calls, global scope */
161 PyObject *me; /* PyCObject containing pointer to this
167 typedef struct PLyPlanObject
170 void *plan; /* return of an SPI_saveplan */
177 typedef struct PLyResultObject
180 /* HeapTuple *tuples; */
181 PyObject * nrows; /* number of rows returned by query */
182 PyObject *rows; /* data rows, or None if no data returned */
183 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
187 /* function declarations */
189 /* Two exported functions: first is the magic telling Postgresql
190 * what function call interface it implements. Second is for
191 * initialization of the interpreter during library load.
193 Datum plpython_call_handler(PG_FUNCTION_ARGS);
196 PG_FUNCTION_INFO_V1(plpython_call_handler);
198 /* most of the remaining of the declarations, all static */
200 /* these should only be called once at the first call
201 * of plpython_call_handler. initialize the python interpreter
204 static void PLy_init_interp(void);
205 static void PLy_init_plpy(void);
207 /* call PyErr_SetString with a vprint interface and translation support */
209 PLy_exception_set(PyObject *, const char *,...)
210 __attribute__((format(printf, 2, 3)));
212 /* Get the innermost python procedure called from the backend */
213 static char *PLy_procedure_name(PLyProcedure *);
215 /* some utility functions */
216 static void PLy_elog(int, const char *,...)
217 __attribute__((format(printf, 2, 3)));
218 static char *PLy_traceback(int *);
220 static void *PLy_malloc(size_t);
221 static void *PLy_malloc0(size_t);
222 static char *PLy_strdup(const char *);
223 static void PLy_free(void *);
225 /* sub handlers for functions and triggers */
226 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
227 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
229 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
230 static void PLy_function_delete_args(PLyProcedure *);
231 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
233 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
234 TriggerData *, HeapTuple);
236 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
238 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
241 static PLyProcedure *PLy_procedure_create(HeapTuple procTup, Oid tgreloid,
244 static void PLy_procedure_compile(PLyProcedure *, const char *);
245 static char *PLy_procedure_munge_source(const char *, const char *);
246 static void PLy_procedure_delete(PLyProcedure *);
248 static void PLy_typeinfo_init(PLyTypeInfo *);
249 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
250 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
251 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
252 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
253 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
254 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
255 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
257 /* conversion functions */
258 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
259 static PyObject *PLyBool_FromString(const char *);
260 static PyObject *PLyFloat_FromString(const char *);
261 static PyObject *PLyInt_FromString(const char *);
262 static PyObject *PLyLong_FromString(const char *);
263 static PyObject *PLyString_FromString(const char *);
265 static HeapTuple PLyMapping_ToTuple(PLyTypeInfo *, PyObject *);
266 static HeapTuple PLySequence_ToTuple(PLyTypeInfo *, PyObject *);
267 static HeapTuple PLyObject_ToTuple(PLyTypeInfo *, PyObject *);
270 * Currently active plpython function
272 static PLyProcedure *PLy_curr_procedure = NULL;
275 * When a callback from Python into PG incurs an error, we temporarily store
276 * the error information here, and return NULL to the Python interpreter.
277 * Any further callback attempts immediately fail, and when the Python
278 * interpreter returns to the calling function, we re-throw the error (even if
279 * Python thinks it trapped the error and doesn't return NULL). Eventually
280 * this ought to be improved to let Python code really truly trap the error,
281 * but that's more of a change from the pre-8.0 semantics than I have time for
282 * now --- it will only be possible if the callback query is executed inside a
285 static ErrorData *PLy_error_in_progress = NULL;
287 static PyObject *PLy_interp_globals = NULL;
288 static PyObject *PLy_interp_safe_globals = NULL;
289 static PyObject *PLy_procedure_cache = NULL;
291 /* Python exceptions */
292 static PyObject *PLy_exc_error = NULL;
293 static PyObject *PLy_exc_fatal = NULL;
294 static PyObject *PLy_exc_spi_error = NULL;
296 /* some globals for the python module */
297 static char PLy_plan_doc[] = {
298 "Store a PostgreSQL plan"
301 static char PLy_result_doc[] = {
302 "Results of a PostgreSQL query"
307 * the function definitions
311 * This routine is a crock, and so is everyplace that calls it. The problem
312 * is that the cached form of plpython functions/queries is allocated permanently
313 * (mostly via malloc()) and never released until backend exit. Subsidiary
314 * data structures such as fmgr info records therefore must live forever
315 * as well. A better implementation would store all this stuff in a per-
316 * function memory context that could be reclaimed at need. In the meantime,
317 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
318 * it might allocate, and whatever the eventual function might allocate using
319 * fn_mcxt, will live forever too.
322 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
324 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
328 plpython_call_handler(PG_FUNCTION_ARGS)
331 PLyProcedure *save_curr_proc;
332 PLyProcedure *volatile proc = NULL;
334 if (SPI_connect() != SPI_OK_CONNECT)
335 elog(ERROR, "SPI_connect failed");
337 save_curr_proc = PLy_curr_procedure;
341 if (CALLED_AS_TRIGGER(fcinfo))
343 TriggerData *tdata = (TriggerData *) fcinfo->context;
346 proc = PLy_procedure_get(fcinfo,
347 RelationGetRelid(tdata->tg_relation));
348 PLy_curr_procedure = proc;
349 trv = PLy_trigger_handler(fcinfo, proc);
350 retval = PointerGetDatum(trv);
354 proc = PLy_procedure_get(fcinfo, InvalidOid);
355 PLy_curr_procedure = proc;
356 retval = PLy_function_handler(fcinfo, proc);
361 PLy_curr_procedure = save_curr_proc;
364 /* note: Py_DECREF needs braces around it, as of 2003/08 */
372 PLy_curr_procedure = save_curr_proc;
379 /* trigger and function sub handlers
381 * the python function is expected to return Py_None if the tuple is
382 * acceptable and unmodified. Otherwise it should return a PyString
383 * object who's value is SKIP, or MODIFY. SKIP means don't perform
384 * this action. MODIFY means the tuple has been modified, so update
385 * tuple and perform action. SKIP and MODIFY assume the trigger fires
386 * BEFORE the event and is ROW level. postgres expects the function
387 * to take no arguments and return an argument of type trigger.
390 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
393 PyObject *volatile plargs = NULL;
394 PyObject *volatile plrv = NULL;
398 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
399 plrv = PLy_procedure_call(proc, "TD", plargs);
401 Assert(plrv != NULL);
402 Assert(!PLy_error_in_progress);
405 * Disconnect from SPI manager
407 if (SPI_finish() != SPI_OK_FINISH)
408 elog(ERROR, "SPI_finish failed");
411 * return of None means we're happy with the tuple
417 if (!PyString_Check(plrv))
419 (errcode(ERRCODE_DATA_EXCEPTION),
420 errmsg("unexpected return value from trigger procedure"),
421 errdetail("Expected None or a string.")));
423 srv = PyString_AsString(plrv);
424 if (pg_strcasecmp(srv, "SKIP") == 0)
426 else if (pg_strcasecmp(srv, "MODIFY") == 0)
428 TriggerData *tdata = (TriggerData *) fcinfo->context;
430 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
431 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
432 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
435 (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
437 else if (pg_strcasecmp(srv, "OK") != 0)
440 * accept "OK" as an alternative to None; otherwise, raise an
444 (errcode(ERRCODE_DATA_EXCEPTION),
445 errmsg("unexpected return value from trigger procedure"),
446 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
466 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
469 PyObject *volatile plntup;
470 PyObject *volatile plkeys;
471 PyObject *volatile platt;
472 PyObject *volatile plval;
473 PyObject *volatile plstr;
479 int *volatile modattrs;
480 Datum *volatile modvalues;
481 char *volatile modnulls;
484 plntup = plkeys = platt = plval = plstr = NULL;
491 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
493 (errmsg("TD[\"new\"] deleted, cannot modify row")));
494 if (!PyDict_Check(plntup))
496 (errmsg("TD[\"new\"] is not a dictionary")));
499 plkeys = PyDict_Keys(plntup);
500 natts = PyList_Size(plkeys);
502 modattrs = (int *) palloc(natts * sizeof(int));
503 modvalues = (Datum *) palloc(natts * sizeof(Datum));
504 modnulls = (char *) palloc(natts * sizeof(char));
506 tupdesc = tdata->tg_relation->rd_att;
508 for (i = 0; i < natts; i++)
512 platt = PyList_GetItem(plkeys, i);
513 if (!PyString_Check(platt))
515 (errmsg("name of TD[\"new\"] attribute at ordinal position %d is not a string", i)));
516 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
517 if (attn == SPI_ERROR_NOATTRIBUTE)
519 (errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
520 PyString_AsString(platt))));
523 plval = PyDict_GetItem(plntup, platt);
525 elog(FATAL, "Python interpreter is probably corrupted");
531 if (tupdesc->attrs[atti]->attisdropped)
533 modvalues[i] = (Datum) 0;
536 else if (plval != Py_None)
538 plstr = PyObject_Str(plval);
540 PLy_elog(ERROR, "could not compute string representation of Python object in PL/Python function \"%s\" while modifying trigger row",
542 src = PyString_AsString(plstr);
545 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
547 proc->result.out.r.atts[atti].typioparam,
548 tupdesc->attrs[atti]->atttypmod);
557 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
559 proc->result.out.r.atts[atti].typioparam,
560 tupdesc->attrs[atti]->atttypmod);
568 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
569 modattrs, modvalues, modnulls);
571 elog(ERROR, "SPI_modifytuple failed: error %d", SPI_result);
602 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
604 TriggerData *tdata = (TriggerData *) fcinfo->context;
615 PyObject *volatile pltdata = NULL;
620 pltdata = PyDict_New();
622 PLy_elog(ERROR, "could not create new dictionary while building trigger arguments");
624 pltname = PyString_FromString(tdata->tg_trigger->tgname);
625 PyDict_SetItemString(pltdata, "name", pltname);
628 stroid = DatumGetCString(DirectFunctionCall1(oidout,
629 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
630 pltrelid = PyString_FromString(stroid);
631 PyDict_SetItemString(pltdata, "relid", pltrelid);
635 stroid = SPI_getrelname(tdata->tg_relation);
636 plttablename = PyString_FromString(stroid);
637 PyDict_SetItemString(pltdata, "table_name", plttablename);
638 Py_DECREF(plttablename);
641 stroid = SPI_getnspname(tdata->tg_relation);
642 plttableschema = PyString_FromString(stroid);
643 PyDict_SetItemString(pltdata, "table_schema", plttableschema);
644 Py_DECREF(plttableschema);
648 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
649 pltwhen = PyString_FromString("BEFORE");
650 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
651 pltwhen = PyString_FromString("AFTER");
654 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
655 pltwhen = NULL; /* keep compiler quiet */
657 PyDict_SetItemString(pltdata, "when", pltwhen);
660 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
662 pltlevel = PyString_FromString("ROW");
663 PyDict_SetItemString(pltdata, "level", pltlevel);
666 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
668 pltevent = PyString_FromString("INSERT");
670 PyDict_SetItemString(pltdata, "old", Py_None);
671 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
672 tdata->tg_relation->rd_att);
673 PyDict_SetItemString(pltdata, "new", pytnew);
675 *rv = tdata->tg_trigtuple;
677 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
679 pltevent = PyString_FromString("DELETE");
681 PyDict_SetItemString(pltdata, "new", Py_None);
682 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
683 tdata->tg_relation->rd_att);
684 PyDict_SetItemString(pltdata, "old", pytold);
686 *rv = tdata->tg_trigtuple;
688 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
690 pltevent = PyString_FromString("UPDATE");
692 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
693 tdata->tg_relation->rd_att);
694 PyDict_SetItemString(pltdata, "new", pytnew);
696 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
697 tdata->tg_relation->rd_att);
698 PyDict_SetItemString(pltdata, "old", pytold);
700 *rv = tdata->tg_newtuple;
704 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
705 pltevent = NULL; /* keep compiler quiet */
708 PyDict_SetItemString(pltdata, "event", pltevent);
711 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
713 pltlevel = PyString_FromString("STATEMENT");
714 PyDict_SetItemString(pltdata, "level", pltlevel);
717 PyDict_SetItemString(pltdata, "old", Py_None);
718 PyDict_SetItemString(pltdata, "new", Py_None);
721 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
722 pltevent = PyString_FromString("INSERT");
723 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
724 pltevent = PyString_FromString("DELETE");
725 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
726 pltevent = PyString_FromString("UPDATE");
727 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
728 pltevent = PyString_FromString("TRUNCATE");
731 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
732 pltevent = NULL; /* keep compiler quiet */
735 PyDict_SetItemString(pltdata, "event", pltevent);
739 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
741 if (tdata->tg_trigger->tgnargs)
749 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
750 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
752 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
755 * stolen, don't Py_DECREF
757 PyList_SetItem(pltargs, i, pltarg);
765 PyDict_SetItemString(pltdata, "args", pltargs);
780 /* function handler and friends */
782 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
785 PyObject *volatile plargs = NULL;
786 PyObject *volatile plrv = NULL;
787 PyObject *volatile plrv_so = NULL;
792 if (!proc->is_setof || proc->setof == NULL)
794 /* Simple type returning function or first time for SETOF function */
795 plargs = PLy_function_build_args(fcinfo, proc);
796 plrv = PLy_procedure_call(proc, "args", plargs);
800 * SETOF function parameters will be deleted when last row is
803 PLy_function_delete_args(proc);
804 Assert(plrv != NULL);
805 Assert(!PLy_error_in_progress);
809 * Disconnect from SPI manager and then create the return values datum
810 * (if the input function does a palloc for it this must not be
811 * allocated in the SPI memory context because SPI_finish would free
814 if (SPI_finish() != SPI_OK_FINISH)
815 elog(ERROR, "SPI_finish failed");
819 bool has_error = false;
820 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
822 if (proc->setof == NULL)
824 /* first time -- do checks and setup */
825 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
826 (rsi->allowedModes & SFRM_ValuePerCall) == 0)
829 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
830 errmsg("unsupported set function return mode"),
831 errdetail("PL/Python set-returning functions only support returning only value per call.")));
833 rsi->returnMode = SFRM_ValuePerCall;
835 /* Make iterator out of returned object */
836 proc->setof = PyObject_GetIter(plrv);
840 if (proc->setof == NULL)
842 (errcode(ERRCODE_DATATYPE_MISMATCH),
843 errmsg("returned object cannot be iterated"),
844 errdetail("PL/Python set-returning functions must return an iterable object.")));
847 /* Fetch next from iterator */
848 plrv = PyIter_Next(proc->setof);
850 rsi->isDone = ExprMultipleResult;
853 rsi->isDone = ExprEndResult;
854 has_error = PyErr_Occurred() != NULL;
857 if (rsi->isDone == ExprEndResult)
859 /* Iterator is exhausted or error happened */
860 Py_DECREF(proc->setof);
867 PLy_function_delete_args(proc);
871 (errcode(ERRCODE_DATA_EXCEPTION),
872 errmsg("error fetching next item from iterator")));
874 fcinfo->isnull = true;
880 * If the function is declared to return void, the Python return value
881 * must be None. For void-returning functions, we also treat a None
882 * return value as a special "void datum" rather than NULL (as is the
883 * case for non-void-returning functions).
885 if (proc->result.out.d.typoid == VOIDOID)
889 (errcode(ERRCODE_DATATYPE_MISMATCH),
890 errmsg("PL/Python function with return type \"void\" did not return None")));
892 fcinfo->isnull = false;
895 else if (plrv == Py_None)
897 fcinfo->isnull = true;
898 if (proc->result.is_rowtype < 1)
899 rv = InputFunctionCall(&proc->result.out.d.typfunc,
901 proc->result.out.d.typioparam,
907 else if (proc->result.is_rowtype >= 1)
909 HeapTuple tuple = NULL;
911 if (PySequence_Check(plrv))
912 /* composite type as sequence (tuple, list etc) */
913 tuple = PLySequence_ToTuple(&proc->result, plrv);
914 else if (PyMapping_Check(plrv))
915 /* composite type as mapping (currently only dict) */
916 tuple = PLyMapping_ToTuple(&proc->result, plrv);
918 /* returned as smth, must provide method __getattr__(name) */
919 tuple = PLyObject_ToTuple(&proc->result, plrv);
923 fcinfo->isnull = false;
924 rv = HeapTupleGetDatum(tuple);
928 fcinfo->isnull = true;
934 fcinfo->isnull = false;
935 plrv_so = PyObject_Str(plrv);
937 PLy_elog(ERROR, "could not create string representation of Python object in PL/Python function \"%s\" while creating return value", proc->proname);
938 plrv_sc = PyString_AsString(plrv_so);
939 rv = InputFunctionCall(&proc->result.out.d.typfunc,
941 proc->result.out.d.typioparam,
963 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
967 PyDict_SetItemString(proc->globals, kargs, vargs);
968 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
969 proc->globals, proc->globals);
972 * If there was an error in a PG callback, propagate that no matter what
973 * Python claims about its success.
975 if (PLy_error_in_progress)
977 ErrorData *edata = PLy_error_in_progress;
979 PLy_error_in_progress = NULL;
983 if (rv == NULL || PyErr_Occurred())
986 PLy_elog(ERROR, "PL/Python function \"%s\" failed", proc->proname);
993 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
995 PyObject *volatile arg = NULL;
996 PyObject *volatile args = NULL;
1001 args = PyList_New(proc->nargs);
1002 for (i = 0; i < proc->nargs; i++)
1004 if (proc->args[i].is_rowtype > 0)
1006 if (fcinfo->argnull[i])
1014 HeapTupleData tmptup;
1016 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
1017 /* Extract rowtype info and find a tupdesc */
1018 tupType = HeapTupleHeaderGetTypeId(td);
1019 tupTypmod = HeapTupleHeaderGetTypMod(td);
1020 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1022 /* Set up I/O funcs if not done yet */
1023 if (proc->args[i].is_rowtype != 1)
1024 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
1026 /* Build a temporary HeapTuple control structure */
1027 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1030 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
1031 ReleaseTupleDesc(tupdesc);
1036 if (fcinfo->argnull[i])
1042 ct = OutputFunctionCall(&(proc->args[i].in.d.typfunc),
1044 arg = (proc->args[i].in.d.func) (ct);
1055 if (PyList_SetItem(args, i, arg) == -1 ||
1057 PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1))
1058 PLy_elog(ERROR, "PyDict_SetItemString() failed for PL/Python function \"%s\" while setting up arguments", proc->proname);
1076 PLy_function_delete_args(PLyProcedure * proc)
1080 if (!proc->argnames)
1083 for (i = 0; i < proc->nargs; i++)
1084 PyDict_DelItemString(proc->globals, proc->argnames[i]);
1089 * PLyProcedure functions
1092 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
1093 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
1094 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
1097 static PLyProcedure *
1098 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
1104 PLyProcedure *proc = NULL;
1107 fn_oid = fcinfo->flinfo->fn_oid;
1108 procTup = SearchSysCache(PROCOID,
1109 ObjectIdGetDatum(fn_oid),
1111 if (!HeapTupleIsValid(procTup))
1112 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1114 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
1115 if (rv >= sizeof(key) || rv < 0)
1116 elog(ERROR, "key too long");
1118 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
1123 if (!PyCObject_Check(plproc))
1124 elog(FATAL, "expected a PyCObject, didn't get one");
1126 proc = PyCObject_AsVoidPtr(plproc);
1127 if (proc->me != plproc)
1128 elog(FATAL, "proc->me != plproc");
1129 /* did we find an up-to-date cache entry? */
1130 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
1131 !ItemPointerEquals(&proc->fn_tid, &procTup->t_self))
1139 proc = PLy_procedure_create(procTup, tgreloid, key);
1141 if (OidIsValid(tgreloid))
1144 * Input/output conversion for trigger tuples. Use the result
1145 * TypeInfo variable to store the tuple conversion info. We
1146 * do this over again on each call to cover the possibility that
1147 * the relation's tupdesc changed since the trigger was last called.
1148 * PLy_input_tuple_funcs and PLy_output_tuple_funcs are responsible
1149 * for not doing repetitive work.
1151 TriggerData *tdata = (TriggerData *) fcinfo->context;
1153 Assert(CALLED_AS_TRIGGER(fcinfo));
1154 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1155 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1158 ReleaseSysCache(procTup);
1163 static PLyProcedure *
1164 PLy_procedure_create(HeapTuple procTup, Oid tgreloid, char *key)
1166 char procName[NAMEDATALEN + 256];
1167 Form_pg_proc procStruct;
1168 PLyProcedure *volatile proc;
1169 char *volatile procSource = NULL;
1175 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1177 if (OidIsValid(tgreloid))
1178 rv = snprintf(procName, sizeof(procName),
1179 "__plpython_procedure_%s_%u_trigger_%u",
1180 NameStr(procStruct->proname),
1181 HeapTupleGetOid(procTup),
1184 rv = snprintf(procName, sizeof(procName),
1185 "__plpython_procedure_%s_%u",
1186 NameStr(procStruct->proname),
1187 HeapTupleGetOid(procTup));
1188 if (rv >= sizeof(procName) || rv < 0)
1189 elog(ERROR, "procedure name would overrun buffer");
1191 proc = PLy_malloc(sizeof(PLyProcedure));
1192 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1193 proc->pyname = PLy_strdup(procName);
1194 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1195 proc->fn_tid = procTup->t_self;
1196 /* Remember if function is STABLE/IMMUTABLE */
1198 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1199 PLy_typeinfo_init(&proc->result);
1200 for (i = 0; i < FUNC_MAX_ARGS; i++)
1201 PLy_typeinfo_init(&proc->args[i]);
1203 proc->code = proc->statics = NULL;
1204 proc->globals = proc->me = NULL;
1205 proc->is_setof = procStruct->proretset;
1207 proc->argnames = NULL;
1212 * get information required for output conversion of the return value,
1213 * but only if this isn't a trigger.
1215 if (!OidIsValid(tgreloid))
1217 HeapTuple rvTypeTup;
1218 Form_pg_type rvTypeStruct;
1220 rvTypeTup = SearchSysCache(TYPEOID,
1221 ObjectIdGetDatum(procStruct->prorettype),
1223 if (!HeapTupleIsValid(rvTypeTup))
1224 elog(ERROR, "cache lookup failed for type %u",
1225 procStruct->prorettype);
1226 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1228 /* Disallow pseudotype result, except for void */
1229 if (rvTypeStruct->typtype == TYPTYPE_PSEUDO &&
1230 procStruct->prorettype != VOIDOID)
1232 if (procStruct->prorettype == TRIGGEROID)
1234 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1235 errmsg("trigger functions can only be called as triggers")));
1238 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1239 errmsg("PL/Python functions cannot return type %s",
1240 format_type_be(procStruct->prorettype))));
1243 if (rvTypeStruct->typtype == TYPTYPE_COMPOSITE)
1246 * Tuple: set up later, during first call to
1247 * PLy_function_handler
1249 proc->result.out.d.typoid = procStruct->prorettype;
1250 proc->result.is_rowtype = 2;
1253 PLy_output_datum_func(&proc->result, rvTypeTup);
1255 ReleaseSysCache(rvTypeTup);
1259 * Now get information required for input conversion of the
1260 * procedure's arguments. Note that we ignore output arguments
1261 * here --- since we don't support returning record, and that was
1262 * already checked above, there's no need to worry about multiple
1265 if (procStruct->pronargs)
1274 /* extract argument type info from the pg_proc tuple */
1275 total = get_func_arg_info(procTup, &types, &names, &modes);
1277 /* count number of in+inout args into proc->nargs */
1279 proc->nargs = total;
1282 /* proc->nargs was initialized to 0 above */
1283 for (i = 0; i < total; i++)
1285 if (modes[i] != PROARGMODE_OUT &&
1286 modes[i] != PROARGMODE_TABLE)
1291 proc->argnames = (char **) PLy_malloc0(sizeof(char *) * proc->nargs);
1292 for (i = pos = 0; i < total; i++)
1294 HeapTuple argTypeTup;
1295 Form_pg_type argTypeStruct;
1298 (modes[i] == PROARGMODE_OUT ||
1299 modes[i] == PROARGMODE_TABLE))
1300 continue; /* skip OUT arguments */
1302 Assert(types[i] == procStruct->proargtypes.values[pos]);
1304 argTypeTup = SearchSysCache(TYPEOID,
1305 ObjectIdGetDatum(types[i]),
1307 if (!HeapTupleIsValid(argTypeTup))
1308 elog(ERROR, "cache lookup failed for type %u", types[i]);
1309 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1311 /* check argument type is OK, set up I/O function info */
1312 switch (argTypeStruct->typtype)
1314 case TYPTYPE_PSEUDO:
1315 /* Disallow pseudotype argument */
1317 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1318 errmsg("PL/Python functions cannot accept type %s",
1319 format_type_be(types[i]))));
1321 case TYPTYPE_COMPOSITE:
1322 /* we'll set IO funcs at first call */
1323 proc->args[pos].is_rowtype = 2;
1326 PLy_input_datum_func(&(proc->args[pos]),
1332 /* get argument name */
1333 proc->argnames[pos] = names ? PLy_strdup(names[i]) : NULL;
1335 ReleaseSysCache(argTypeTup);
1342 * get the text of the function.
1344 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1345 Anum_pg_proc_prosrc, &isnull);
1347 elog(ERROR, "null prosrc");
1348 procSource = TextDatumGetCString(prosrcdatum);
1350 PLy_procedure_compile(proc, procSource);
1354 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1355 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1359 PLy_procedure_delete(proc);
1371 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1373 PyObject *crv = NULL;
1376 proc->globals = PyDict_Copy(PLy_interp_globals);
1379 * SD is private preserved data between calls. GD is global data shared by
1382 proc->statics = PyDict_New();
1383 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1386 * insert the function code into the interpreter
1388 msrc = PLy_procedure_munge_source(proc->pyname, src);
1389 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1392 if (crv != NULL && (!PyErr_Occurred()))
1395 char call[NAMEDATALEN + 256];
1400 * compile a call to the function
1402 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1403 if (clen < 0 || clen >= sizeof(call))
1404 elog(ERROR, "string would overflow buffer");
1405 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1406 if (proc->code != NULL && (!PyErr_Occurred()))
1412 PLy_elog(ERROR, "could not compile PL/Python function \"%s\"", proc->proname);
1416 PLy_procedure_munge_source(const char *name, const char *src)
1425 * room for function source and the def statement
1427 mlen = (strlen(src) * 2) + strlen(name) + 16;
1429 mrc = PLy_malloc(mlen);
1430 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1431 Assert(plen >= 0 && plen < mlen);
1438 if (*sp == '\r' && *(sp + 1) == '\n')
1441 if (*sp == '\n' || *sp == '\r')
1454 if (mp > (mrc + mlen))
1455 elog(FATAL, "buffer overrun in PLy_munge_source");
1461 PLy_procedure_delete(PLyProcedure * proc)
1465 Py_XDECREF(proc->code);
1466 Py_XDECREF(proc->statics);
1467 Py_XDECREF(proc->globals);
1468 Py_XDECREF(proc->me);
1470 PLy_free(proc->proname);
1472 PLy_free(proc->pyname);
1473 for (i = 0; i < proc->nargs; i++)
1475 if (proc->args[i].is_rowtype == 1)
1477 if (proc->args[i].in.r.atts)
1478 PLy_free(proc->args[i].in.r.atts);
1479 if (proc->args[i].out.r.atts)
1480 PLy_free(proc->args[i].out.r.atts);
1482 if (proc->argnames && proc->argnames[i])
1483 PLy_free(proc->argnames[i]);
1486 PLy_free(proc->argnames);
1490 * Conversion functions. Remember output from Python is input to
1491 * PostgreSQL, and vice versa.
1494 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1498 if (arg->is_rowtype == 0)
1499 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1500 arg->is_rowtype = 1;
1502 if (arg->in.r.natts != desc->natts)
1505 PLy_free(arg->in.r.atts);
1506 arg->in.r.natts = desc->natts;
1507 arg->in.r.atts = PLy_malloc0(desc->natts * sizeof(PLyDatumToOb));
1510 for (i = 0; i < desc->natts; i++)
1514 if (desc->attrs[i]->attisdropped)
1517 if (arg->in.r.atts[i].typoid == desc->attrs[i]->atttypid)
1518 continue; /* already set up this entry */
1520 typeTup = SearchSysCache(TYPEOID,
1521 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1523 if (!HeapTupleIsValid(typeTup))
1524 elog(ERROR, "cache lookup failed for type %u",
1525 desc->attrs[i]->atttypid);
1527 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1528 desc->attrs[i]->atttypid,
1531 ReleaseSysCache(typeTup);
1536 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1540 if (arg->is_rowtype == 0)
1541 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1542 arg->is_rowtype = 1;
1544 if (arg->out.r.natts != desc->natts)
1546 if (arg->out.r.atts)
1547 PLy_free(arg->out.r.atts);
1548 arg->out.r.natts = desc->natts;
1549 arg->out.r.atts = PLy_malloc0(desc->natts * sizeof(PLyDatumToOb));
1552 for (i = 0; i < desc->natts; i++)
1556 if (desc->attrs[i]->attisdropped)
1559 if (arg->out.r.atts[i].typoid == desc->attrs[i]->atttypid)
1560 continue; /* already set up this entry */
1562 typeTup = SearchSysCache(TYPEOID,
1563 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1565 if (!HeapTupleIsValid(typeTup))
1566 elog(ERROR, "cache lookup failed for type %u",
1567 desc->attrs[i]->atttypid);
1569 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1571 ReleaseSysCache(typeTup);
1576 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1578 if (arg->is_rowtype > 0)
1579 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1580 arg->is_rowtype = 0;
1581 PLy_output_datum_func2(&(arg->out.d), typeTup);
1585 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1587 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1589 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1590 arg->typoid = HeapTupleGetOid(typeTup);
1591 arg->typioparam = getTypeIOParam(typeTup);
1592 arg->typbyval = typeStruct->typbyval;
1596 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1598 if (arg->is_rowtype > 0)
1599 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1600 arg->is_rowtype = 0;
1601 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1605 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1607 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1609 /* Get the type's conversion information */
1610 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1611 arg->typoid = HeapTupleGetOid(typeTup);
1612 arg->typioparam = getTypeIOParam(typeTup);
1613 arg->typbyval = typeStruct->typbyval;
1615 /* Determine which kind of Python object we will convert to */
1619 arg->func = PLyBool_FromString;
1624 arg->func = PLyFloat_FromString;
1628 arg->func = PLyInt_FromString;
1631 arg->func = PLyLong_FromString;
1634 arg->func = PLyString_FromString;
1640 PLy_typeinfo_init(PLyTypeInfo * arg)
1642 arg->is_rowtype = -1;
1643 arg->in.r.natts = arg->out.r.natts = 0;
1644 arg->in.r.atts = NULL;
1645 arg->out.r.atts = NULL;
1649 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1651 if (arg->is_rowtype == 1)
1654 PLy_free(arg->in.r.atts);
1655 if (arg->out.r.atts)
1656 PLy_free(arg->out.r.atts);
1660 /* assumes that a bool is always returned as a 't' or 'f' */
1662 PLyBool_FromString(const char *src)
1665 * We would like to use Py_RETURN_TRUE and Py_RETURN_FALSE here for
1666 * generating SQL from trigger functions, but those are only supported in
1667 * Python >= 2.3, and we support older versions.
1668 * http://docs.python.org/api/boolObjects.html
1671 return PyBool_FromLong(1);
1672 return PyBool_FromLong(0);
1676 PLyFloat_FromString(const char *src)
1682 v = strtod(src, &eptr);
1683 if (*eptr != '\0' || errno)
1685 return PyFloat_FromDouble(v);
1689 PLyInt_FromString(const char *src)
1695 v = strtol(src, &eptr, 0);
1696 if (*eptr != '\0' || errno)
1698 return PyInt_FromLong(v);
1702 PLyLong_FromString(const char *src)
1704 return PyLong_FromString((char *) src, NULL, 0);
1708 PLyString_FromString(const char *src)
1710 return PyString_FromString(src);
1714 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1716 PyObject *volatile dict;
1719 if (info->is_rowtype != 1)
1720 elog(ERROR, "PLyTypeInfo structure describes a datum");
1722 dict = PyDict_New();
1724 PLy_elog(ERROR, "could not create new dictionary");
1728 for (i = 0; i < info->in.r.natts; i++)
1736 if (desc->attrs[i]->attisdropped)
1739 key = NameStr(desc->attrs[i]->attname);
1740 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1742 if (is_null || info->in.r.atts[i].func == NULL)
1743 PyDict_SetItemString(dict, key, Py_None);
1746 vsrc = OutputFunctionCall(&info->in.r.atts[i].typfunc,
1750 * no exceptions allowed
1752 value = info->in.r.atts[i].func(vsrc);
1754 PyDict_SetItemString(dict, key, value);
1771 PLyMapping_ToTuple(PLyTypeInfo * info, PyObject * mapping)
1779 Assert(PyMapping_Check(mapping));
1781 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1782 if (info->is_rowtype == 2)
1783 PLy_output_tuple_funcs(info, desc);
1784 Assert(info->is_rowtype == 1);
1787 values = palloc(sizeof(Datum) * desc->natts);
1788 nulls = palloc(sizeof(bool) * desc->natts);
1789 for (i = 0; i < desc->natts; ++i)
1792 PyObject *volatile value,
1795 key = NameStr(desc->attrs[i]->attname);
1799 value = PyMapping_GetItemString(mapping, key);
1800 if (value == Py_None)
1802 values[i] = (Datum) NULL;
1809 so = PyObject_Str(value);
1811 PLy_elog(ERROR, "could not compute string representation of Python object");
1812 valuestr = PyString_AsString(so);
1814 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1816 ,info->out.r.atts[i].typioparam
1824 (errcode(ERRCODE_UNDEFINED_COLUMN),
1825 errmsg("key \"%s\" not found in mapping", key),
1826 errhint("To return null in a column, "
1827 "add the value None to the mapping with the key named after the column.")));
1841 tuple = heap_form_tuple(desc, values, nulls);
1842 ReleaseTupleDesc(desc);
1851 PLySequence_ToTuple(PLyTypeInfo * info, PyObject * sequence)
1859 Assert(PySequence_Check(sequence));
1862 * Check that sequence length is exactly same as PG tuple's. We actually
1863 * can ignore exceeding items or assume missing ones as null but to avoid
1864 * plpython developer's errors we are strict here
1866 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1867 if (PySequence_Length(sequence) != desc->natts)
1869 (errcode(ERRCODE_DATATYPE_MISMATCH),
1870 errmsg("length of returned sequence did not match number of columns in row")));
1872 if (info->is_rowtype == 2)
1873 PLy_output_tuple_funcs(info, desc);
1874 Assert(info->is_rowtype == 1);
1877 values = palloc(sizeof(Datum) * desc->natts);
1878 nulls = palloc(sizeof(bool) * desc->natts);
1879 for (i = 0; i < desc->natts; ++i)
1881 PyObject *volatile value,
1887 value = PySequence_GetItem(sequence, i);
1889 if (value == Py_None)
1891 values[i] = (Datum) NULL;
1898 so = PyObject_Str(value);
1900 PLy_elog(ERROR, "could not compute string representation of Python object");
1901 valuestr = PyString_AsString(so);
1902 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1904 ,info->out.r.atts[i].typioparam
1923 tuple = heap_form_tuple(desc, values, nulls);
1924 ReleaseTupleDesc(desc);
1933 PLyObject_ToTuple(PLyTypeInfo * info, PyObject * object)
1941 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1942 if (info->is_rowtype == 2)
1943 PLy_output_tuple_funcs(info, desc);
1944 Assert(info->is_rowtype == 1);
1947 values = palloc(sizeof(Datum) * desc->natts);
1948 nulls = palloc(sizeof(bool) * desc->natts);
1949 for (i = 0; i < desc->natts; ++i)
1952 PyObject *volatile value,
1955 key = NameStr(desc->attrs[i]->attname);
1959 value = PyObject_GetAttrString(object, key);
1960 if (value == Py_None)
1962 values[i] = (Datum) NULL;
1969 so = PyObject_Str(value);
1971 PLy_elog(ERROR, "could not compute string representation of Python object");
1972 valuestr = PyString_AsString(so);
1973 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1975 ,info->out.r.atts[i].typioparam
1983 (errcode(ERRCODE_UNDEFINED_COLUMN),
1984 errmsg("attribute \"%s\" does not exist in Python object", key),
1985 errhint("To return null in a column, "
1986 "let the returned object have an attribute named "
1987 "after column with value None.")));
2001 tuple = heap_form_tuple(desc, values, nulls);
2002 ReleaseTupleDesc(desc);
2010 /* initialization, some python variables function declared here */
2012 /* interface to postgresql elog */
2013 static PyObject *PLy_debug(PyObject *, PyObject *);
2014 static PyObject *PLy_log(PyObject *, PyObject *);
2015 static PyObject *PLy_info(PyObject *, PyObject *);
2016 static PyObject *PLy_notice(PyObject *, PyObject *);
2017 static PyObject *PLy_warning(PyObject *, PyObject *);
2018 static PyObject *PLy_error(PyObject *, PyObject *);
2019 static PyObject *PLy_fatal(PyObject *, PyObject *);
2021 /* PLyPlanObject, PLyResultObject and SPI interface */
2022 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
2023 static PyObject *PLy_plan_new(void);
2024 static void PLy_plan_dealloc(PyObject *);
2025 static PyObject *PLy_plan_getattr(PyObject *, char *);
2026 static PyObject *PLy_plan_status(PyObject *, PyObject *);
2028 static PyObject *PLy_result_new(void);
2029 static void PLy_result_dealloc(PyObject *);
2030 static PyObject *PLy_result_getattr(PyObject *, char *);
2031 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
2032 static PyObject *PLy_result_status(PyObject *, PyObject *);
2033 static Py_ssize_t PLy_result_length(PyObject *);
2034 static PyObject *PLy_result_item(PyObject *, Py_ssize_t);
2035 static PyObject *PLy_result_slice(PyObject *, Py_ssize_t, Py_ssize_t);
2036 static int PLy_result_ass_item(PyObject *, Py_ssize_t, PyObject *);
2037 static int PLy_result_ass_slice(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
2040 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
2041 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
2042 static PyObject *PLy_spi_execute_query(char *query, long limit);
2043 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
2044 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
2047 static PyTypeObject PLy_PlanType = {
2048 PyObject_HEAD_INIT(NULL)
2050 "PLyPlan", /* tp_name */
2051 sizeof(PLyPlanObject), /* tp_size */
2052 0, /* tp_itemsize */
2057 PLy_plan_dealloc, /* tp_dealloc */
2059 PLy_plan_getattr, /* tp_getattr */
2063 0, /* tp_as_number */
2064 0, /* tp_as_sequence */
2065 0, /* tp_as_mapping */
2069 0, /* tp_getattro */
2070 0, /* tp_setattro */
2071 0, /* tp_as_buffer */
2072 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2073 PLy_plan_doc, /* tp_doc */
2076 static PyMethodDef PLy_plan_methods[] = {
2077 {"status", PLy_plan_status, METH_VARARGS, NULL},
2078 {NULL, NULL, 0, NULL}
2081 static PySequenceMethods PLy_result_as_sequence = {
2082 PLy_result_length, /* sq_length */
2083 NULL, /* sq_concat */
2084 NULL, /* sq_repeat */
2085 PLy_result_item, /* sq_item */
2086 PLy_result_slice, /* sq_slice */
2087 PLy_result_ass_item, /* sq_ass_item */
2088 PLy_result_ass_slice, /* sq_ass_slice */
2091 static PyTypeObject PLy_ResultType = {
2092 PyObject_HEAD_INIT(NULL)
2094 "PLyResult", /* tp_name */
2095 sizeof(PLyResultObject), /* tp_size */
2096 0, /* tp_itemsize */
2101 PLy_result_dealloc, /* tp_dealloc */
2103 PLy_result_getattr, /* tp_getattr */
2107 0, /* tp_as_number */
2108 &PLy_result_as_sequence, /* tp_as_sequence */
2109 0, /* tp_as_mapping */
2113 0, /* tp_getattro */
2114 0, /* tp_setattro */
2115 0, /* tp_as_buffer */
2116 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2117 PLy_result_doc, /* tp_doc */
2120 static PyMethodDef PLy_result_methods[] = {
2121 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
2122 {"status", PLy_result_status, METH_VARARGS, NULL},
2123 {NULL, NULL, 0, NULL}
2126 static PyMethodDef PLy_methods[] = {
2130 {"debug", PLy_debug, METH_VARARGS, NULL},
2131 {"log", PLy_log, METH_VARARGS, NULL},
2132 {"info", PLy_info, METH_VARARGS, NULL},
2133 {"notice", PLy_notice, METH_VARARGS, NULL},
2134 {"warning", PLy_warning, METH_VARARGS, NULL},
2135 {"error", PLy_error, METH_VARARGS, NULL},
2136 {"fatal", PLy_fatal, METH_VARARGS, NULL},
2139 * create a stored plan
2141 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
2144 * execute a plan or query
2146 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
2148 {NULL, NULL, 0, NULL}
2152 /* plan object methods */
2158 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
2166 return (PyObject *) ob;
2171 PLy_plan_dealloc(PyObject * arg)
2173 PLyPlanObject *ob = (PLyPlanObject *) arg;
2176 SPI_freeplan(ob->plan);
2178 PLy_free(ob->types);
2183 for (i = 0; i < ob->nargs; i++)
2184 PLy_typeinfo_dealloc(&ob->args[i]);
2188 arg->ob_type->tp_free(arg);
2193 PLy_plan_getattr(PyObject * self, char *name)
2195 return Py_FindMethod(PLy_plan_methods, self, name);
2199 PLy_plan_status(PyObject * self, PyObject * args)
2201 if (PyArg_ParseTuple(args, ""))
2205 /* return PyInt_FromLong(self->status); */
2207 PLy_exception_set(PLy_exc_error, "plan.status takes no arguments");
2213 /* result object methods */
2216 PLy_result_new(void)
2218 PLyResultObject *ob;
2220 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
2223 /* ob->tuples = NULL; */
2226 ob->status = Py_None;
2227 ob->nrows = PyInt_FromLong(-1);
2228 ob->rows = PyList_New(0);
2230 return (PyObject *) ob;
2234 PLy_result_dealloc(PyObject * arg)
2236 PLyResultObject *ob = (PLyResultObject *) arg;
2238 Py_XDECREF(ob->nrows);
2239 Py_XDECREF(ob->rows);
2240 Py_XDECREF(ob->status);
2242 arg->ob_type->tp_free(arg);
2246 PLy_result_getattr(PyObject * self, char *name)
2248 return Py_FindMethod(PLy_result_methods, self, name);
2252 PLy_result_nrows(PyObject * self, PyObject * args)
2254 PLyResultObject *ob = (PLyResultObject *) self;
2256 Py_INCREF(ob->nrows);
2261 PLy_result_status(PyObject * self, PyObject * args)
2263 PLyResultObject *ob = (PLyResultObject *) self;
2265 Py_INCREF(ob->status);
2270 PLy_result_length(PyObject * arg)
2272 PLyResultObject *ob = (PLyResultObject *) arg;
2274 return PyList_Size(ob->rows);
2278 PLy_result_item(PyObject * arg, Py_ssize_t idx)
2281 PLyResultObject *ob = (PLyResultObject *) arg;
2283 rv = PyList_GetItem(ob->rows, idx);
2290 PLy_result_ass_item(PyObject * arg, Py_ssize_t idx, PyObject * item)
2293 PLyResultObject *ob = (PLyResultObject *) arg;
2296 rv = PyList_SetItem(ob->rows, idx, item);
2301 PLy_result_slice(PyObject * arg, Py_ssize_t lidx, Py_ssize_t hidx)
2304 PLyResultObject *ob = (PLyResultObject *) arg;
2306 rv = PyList_GetSlice(ob->rows, lidx, hidx);
2314 PLy_result_ass_slice(PyObject * arg, Py_ssize_t lidx, Py_ssize_t hidx, PyObject * slice)
2317 PLyResultObject *ob = (PLyResultObject *) arg;
2319 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
2325 PLy_spi_prepare(PyObject * self, PyObject * args)
2327 PLyPlanObject *plan;
2328 PyObject *list = NULL;
2329 PyObject *volatile optr = NULL;
2332 MemoryContext oldcontext;
2334 /* Can't execute more if we have an unhandled error */
2335 if (PLy_error_in_progress)
2337 PLy_exception_set(PLy_exc_error, "transaction aborted");
2341 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
2343 PLy_exception_set(PLy_exc_spi_error,
2344 "invalid arguments for plpy.prepare");
2348 if (list && (!PySequence_Check(list)))
2350 PLy_exception_set(PLy_exc_spi_error,
2351 "second argument of plpy.prepare must be a sequence");
2355 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
2358 oldcontext = CurrentMemoryContext;
2366 nargs = PySequence_Length(list);
2369 plan->nargs = nargs;
2370 plan->types = PLy_malloc(sizeof(Oid) * nargs);
2371 plan->values = PLy_malloc(sizeof(Datum) * nargs);
2372 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
2375 * the other loop might throw an exception, if PLyTypeInfo
2376 * member isn't properly initialized the Py_DECREF(plan) will
2379 for (i = 0; i < nargs; i++)
2381 PLy_typeinfo_init(&plan->args[i]);
2382 plan->values[i] = PointerGetDatum(NULL);
2385 for (i = 0; i < nargs; i++)
2391 Form_pg_type typeStruct;
2393 optr = PySequence_GetItem(list, i);
2394 if (!PyString_Check(optr))
2396 (errmsg("plpy.prepare: type name at ordinal position %d is not a string", i)));
2397 sptr = PyString_AsString(optr);
2399 /********************************************************
2400 * Resolve argument type names and then look them up by
2401 * oid in the system cache, and remember the required
2402 *information for input conversion.
2403 ********************************************************/
2405 parseTypeString(sptr, &typeId, &typmod);
2407 typeTup = SearchSysCache(TYPEOID,
2408 ObjectIdGetDatum(typeId),
2410 if (!HeapTupleIsValid(typeTup))
2411 elog(ERROR, "cache lookup failed for type %u", typeId);
2414 optr = NULL; /* this is important */
2416 plan->types[i] = typeId;
2417 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2418 if (typeStruct->typtype != TYPTYPE_COMPOSITE)
2419 PLy_output_datum_func(&plan->args[i], typeTup);
2422 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2423 errmsg("plpy.prepare does not support composite types")));
2424 ReleaseSysCache(typeTup);
2429 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2430 if (plan->plan == NULL)
2431 elog(ERROR, "SPI_prepare failed: %s",
2432 SPI_result_code_string(SPI_result));
2434 /* transfer plan from procCxt to topCxt */
2435 tmpplan = plan->plan;
2436 plan->plan = SPI_saveplan(tmpplan);
2437 SPI_freeplan(tmpplan);
2438 if (plan->plan == NULL)
2439 elog(ERROR, "SPI_saveplan failed: %s",
2440 SPI_result_code_string(SPI_result));
2444 MemoryContextSwitchTo(oldcontext);
2445 PLy_error_in_progress = CopyErrorData();
2449 if (!PyErr_Occurred())
2450 PLy_exception_set(PLy_exc_spi_error,
2451 "unrecognized error in PLy_spi_prepare");
2452 /* XXX this oughta be replaced with errcontext mechanism */
2453 PLy_elog(WARNING, "in PL/Python function \"%s\"",
2454 PLy_procedure_name(PLy_curr_procedure));
2459 return (PyObject *) plan;
2462 /* execute(query="select * from foo", limit=5)
2463 * execute(plan=plan, values=(foo, bar), limit=5)
2466 PLy_spi_execute(PyObject * self, PyObject * args)
2470 PyObject *list = NULL;
2473 /* Can't execute more if we have an unhandled error */
2474 if (PLy_error_in_progress)
2476 PLy_exception_set(PLy_exc_error, "transaction aborted");
2480 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
2481 return PLy_spi_execute_query(query, limit);
2485 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
2486 is_PLyPlanObject(plan))
2487 return PLy_spi_execute_plan(plan, list, limit);
2489 PLy_exception_set(PLy_exc_error, "plpy.execute expected a query or a plan");
2494 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
2499 PLyPlanObject *plan;
2500 MemoryContext oldcontext;
2504 if (!PySequence_Check(list) || PyString_Check(list))
2506 PLy_exception_set(PLy_exc_spi_error, "plpy.execute takes a sequence as its second argument");
2509 nargs = PySequence_Length(list);
2514 plan = (PLyPlanObject *) ob;
2516 if (nargs != plan->nargs)
2519 PyObject *so = PyObject_Str(list);
2522 PLy_elog(ERROR, "PL/Python function \"%s\" could not execute plan",
2523 PLy_procedure_name(PLy_curr_procedure));
2524 sv = PyString_AsString(so);
2525 PLy_exception_set(PLy_exc_spi_error,
2526 dngettext(TEXTDOMAIN, "Expected sequence of %d argument, got %d: %s", "Expected sequence of %d arguments, got %d: %s", plan->nargs),
2527 plan->nargs, nargs, sv);
2533 oldcontext = CurrentMemoryContext;
2536 char *nulls = palloc(nargs * sizeof(char));
2539 for (j = 0; j < nargs; j++)
2544 elem = PySequence_GetItem(list, j);
2545 if (elem != Py_None)
2547 so = PyObject_Str(elem);
2549 PLy_elog(ERROR, "PL/Python function \"%s\" could not execute plan",
2550 PLy_procedure_name(PLy_curr_procedure));
2555 char *sv = PyString_AsString(so);
2558 InputFunctionCall(&(plan->args[j].out.d.typfunc),
2560 plan->args[j].out.d.typioparam,
2577 InputFunctionCall(&(plan->args[j].out.d.typfunc),
2579 plan->args[j].out.d.typioparam,
2585 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2586 PLy_curr_procedure->fn_readonly, limit);
2594 MemoryContextSwitchTo(oldcontext);
2595 PLy_error_in_progress = CopyErrorData();
2599 * cleanup plan->values array
2601 for (k = 0; k < nargs; k++)
2603 if (!plan->args[k].out.d.typbyval &&
2604 (plan->values[k] != PointerGetDatum(NULL)))
2606 pfree(DatumGetPointer(plan->values[k]));
2607 plan->values[k] = PointerGetDatum(NULL);
2611 if (!PyErr_Occurred())
2612 PLy_exception_set(PLy_exc_error,
2613 "unrecognized error in PLy_spi_execute_plan");
2614 /* XXX this oughta be replaced with errcontext mechanism */
2615 PLy_elog(WARNING, "in PL/Python function \"%s\"",
2616 PLy_procedure_name(PLy_curr_procedure));
2621 for (i = 0; i < nargs; i++)
2623 if (!plan->args[i].out.d.typbyval &&
2624 (plan->values[i] != PointerGetDatum(NULL)))
2626 pfree(DatumGetPointer(plan->values[i]));
2627 plan->values[i] = PointerGetDatum(NULL);
2633 PLy_exception_set(PLy_exc_spi_error,
2634 "SPI_execute_plan failed: %s",
2635 SPI_result_code_string(rv));
2639 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2643 PLy_spi_execute_query(char *query, long limit)
2646 MemoryContext oldcontext;
2648 oldcontext = CurrentMemoryContext;
2651 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2655 MemoryContextSwitchTo(oldcontext);
2656 PLy_error_in_progress = CopyErrorData();
2658 if (!PyErr_Occurred())
2659 PLy_exception_set(PLy_exc_spi_error,
2660 "unrecognized error in PLy_spi_execute_query");
2661 /* XXX this oughta be replaced with errcontext mechanism */
2662 PLy_elog(WARNING, "in PL/Python function \"%s\"",
2663 PLy_procedure_name(PLy_curr_procedure));
2670 PLy_exception_set(PLy_exc_spi_error,
2671 "SPI_execute failed: %s",
2672 SPI_result_code_string(rv));
2676 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2680 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2682 PLyResultObject *result;
2683 MemoryContext oldcontext;
2685 result = (PLyResultObject *) PLy_result_new();
2686 Py_DECREF(result->status);
2687 result->status = PyInt_FromLong(status);
2689 if (status > 0 && tuptable == NULL)
2691 Py_DECREF(result->nrows);
2692 result->nrows = PyInt_FromLong(rows);
2694 else if (status > 0 && tuptable != NULL)
2699 Py_DECREF(result->nrows);
2700 result->nrows = PyInt_FromLong(rows);
2701 PLy_typeinfo_init(&args);
2703 oldcontext = CurrentMemoryContext;
2708 Py_DECREF(result->rows);
2709 result->rows = PyList_New(rows);
2711 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2712 for (i = 0; i < rows; i++)
2714 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2717 PyList_SetItem(result->rows, i, row);
2719 PLy_typeinfo_dealloc(&args);
2721 SPI_freetuptable(tuptable);
2726 MemoryContextSwitchTo(oldcontext);
2727 PLy_error_in_progress = CopyErrorData();
2729 if (!PyErr_Occurred())
2730 PLy_exception_set(PLy_exc_error,
2731 "unrecognized error in PLy_spi_execute_fetch_result");
2733 PLy_typeinfo_dealloc(&args);
2739 return (PyObject *) result;
2744 * language handler and interpreter initialization
2748 * _PG_init() - library load-time initialization
2750 * DO NOT make this static nor change its name!
2755 /* Be sure we do initialization only once (should be redundant now) */
2756 static bool inited = false;
2761 pg_bindtextdomain(TEXTDOMAIN);
2766 if (PyErr_Occurred())
2767 PLy_elog(FATAL, "untrapped error in initialization");
2768 PLy_procedure_cache = PyDict_New();
2769 if (PLy_procedure_cache == NULL)
2770 PLy_elog(ERROR, "could not create procedure cache");
2776 PLy_init_interp(void)
2780 mainmod = PyImport_AddModule("__main__");
2781 if (mainmod == NULL || PyErr_Occurred())
2782 PLy_elog(ERROR, "could not import \"__main__\" module");
2784 PLy_interp_globals = PyModule_GetDict(mainmod);
2785 PLy_interp_safe_globals = PyDict_New();
2786 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2788 if (PLy_interp_globals == NULL || PyErr_Occurred())
2789 PLy_elog(ERROR, "could not initialize globals");
2802 * initialize plpy module
2804 if (PyType_Ready(&PLy_PlanType) < 0)
2805 elog(ERROR, "could not initialize PLy_PlanType");
2806 if (PyType_Ready(&PLy_ResultType) < 0)
2807 elog(ERROR, "could not initialize PLy_ResultType");
2809 plpy = Py_InitModule("plpy", PLy_methods);
2810 plpy_dict = PyModule_GetDict(plpy);
2812 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2814 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2815 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2816 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2817 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2818 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2819 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2822 * initialize main module, and add plpy
2824 main_mod = PyImport_AddModule("__main__");
2825 main_dict = PyModule_GetDict(main_mod);
2826 plpy_mod = PyImport_AddModule("plpy");
2827 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2828 if (PyErr_Occurred())
2829 elog(ERROR, "could not initialize plpy");
2832 /* the python interface to the elog function
2833 * don't confuse these with PLy_elog
2835 static PyObject *PLy_output(volatile int, PyObject *, PyObject *);
2838 PLy_debug(PyObject * self, PyObject * args)
2840 return PLy_output(DEBUG2, self, args);
2844 PLy_log(PyObject * self, PyObject * args)
2846 return PLy_output(LOG, self, args);
2850 PLy_info(PyObject * self, PyObject * args)
2852 return PLy_output(INFO, self, args);
2856 PLy_notice(PyObject * self, PyObject * args)
2858 return PLy_output(NOTICE, self, args);
2862 PLy_warning(PyObject * self, PyObject * args)
2864 return PLy_output(WARNING, self, args);
2868 PLy_error(PyObject * self, PyObject * args)
2870 return PLy_output(ERROR, self, args);
2874 PLy_fatal(PyObject * self, PyObject * args)
2876 return PLy_output(FATAL, self, args);
2881 PLy_output(volatile int level, PyObject * self, PyObject * args)
2885 MemoryContext oldcontext;
2887 so = PyObject_Str(args);
2888 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2891 sv = dgettext(TEXTDOMAIN, "could not parse error message in plpy.elog");
2894 oldcontext = CurrentMemoryContext;
2897 elog(level, "%s", sv);
2901 MemoryContextSwitchTo(oldcontext);
2902 PLy_error_in_progress = CopyErrorData();
2907 * returning NULL here causes the python interpreter to bail. when
2908 * control passes back to PLy_procedure_call, we check for PG
2909 * exceptions and re-throw the error.
2911 PyErr_SetString(PLy_exc_error, sv);
2919 * return a legal object so the interpreter will continue on its merry way
2927 * Get the name of the last procedure called by the backend (the
2928 * innermost, if a plpython procedure call calls the backend and the
2929 * backend calls another plpython procedure).
2931 * NB: this returns the SQL name, not the internal Python procedure name
2934 PLy_procedure_name(PLyProcedure * proc)
2937 return "<unknown procedure>";
2938 return proc->proname;
2941 /* output a python traceback/exception via the postgresql elog
2942 * function. not pretty.
2945 PLy_exception_set(PyObject * exc, const char *fmt,...)
2951 vsnprintf(buf, sizeof(buf), dgettext(TEXTDOMAIN, fmt), ap);
2954 PyErr_SetString(exc, buf);
2957 /* Emit a PG error or notice, together with any available info about the
2958 * current Python error. This should be used to propagate Python errors
2962 PLy_elog(int elevel, const char *fmt,...)
2966 StringInfoData emsg;
2968 xmsg = PLy_traceback(&xlevel);
2970 initStringInfo(&emsg);
2977 success = appendStringInfoVA(&emsg, dgettext(TEXTDOMAIN, fmt), ap);
2981 enlargeStringInfo(&emsg, emsg.maxlen);
2987 (errmsg("PL/Python: %s", emsg.data),
2988 (xmsg) ? errdetail("%s", xmsg) : 0));
3005 PLy_traceback(int *xlevel)
3014 StringInfoData xstr;
3017 * get the current exception
3019 PyErr_Fetch(&e, &v, &tb);
3022 * oops, no exception, return
3030 PyErr_NormalizeException(&e, &v, &tb);
3033 eob = PyObject_Str(e);
3034 if (v && ((vob = PyObject_Str(v)) != NULL))
3035 vstr = PyString_AsString(vob);
3040 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
3041 * because that function calls us, so we could end up with infinite
3042 * recursion. I'm not even sure if eob could be NULL here -- would an
3043 * Assert() be more appropriate?
3045 estr = eob ? PyString_AsString(eob) : "unrecognized exception";
3046 initStringInfo(&xstr);
3047 appendStringInfo(&xstr, "%s: %s", estr, vstr);
3054 * intuit an appropriate error level based on the exception type
3056 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
3058 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
3067 /* python module code */
3069 /* some dumb utility functions */
3071 PLy_malloc(size_t bytes)
3073 void *ptr = malloc(bytes);
3077 (errcode(ERRCODE_OUT_OF_MEMORY),
3078 errmsg("out of memory")));
3083 PLy_malloc0(size_t bytes)
3085 void *ptr = PLy_malloc(bytes);
3087 MemSet(ptr, 0, bytes);
3092 PLy_strdup(const char *str)
3097 len = strlen(str) + 1;
3098 result = PLy_malloc(len);
3099 memcpy(result, str, len);
3104 /* define this away */