1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.90 2006/11/21 21:51:05 tgl 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
27 /* postgreSQL stuff */
28 #include "access/heapam.h"
29 #include "catalog/pg_proc.h"
30 #include "catalog/pg_type.h"
31 #include "commands/trigger.h"
32 #include "executor/spi.h"
35 #include "nodes/makefuncs.h"
36 #include "parser/parse_type.h"
37 #include "tcop/tcopprot.h"
38 #include "utils/builtins.h"
39 #include "utils/lsyscache.h"
40 #include "utils/memutils.h"
41 #include "utils/syscache.h"
42 #include "utils/typcache.h"
49 /* convert Postgresql Datum or tuple into a PyObject.
50 * input to Python. Tuples are converted to dictionary
54 typedef PyObject *(*PLyDatumToObFunc) (const char *);
56 typedef struct PLyDatumToOb
58 PLyDatumToObFunc func;
64 typedef struct PLyTupleToOb
70 typedef union PLyTypeInput
76 /* convert PyObject to a Postgresql Datum or tuple.
79 typedef struct PLyObToDatum
81 FmgrInfo typfunc; /* The type's input function */
82 Oid typoid; /* The OID of the type */
87 typedef struct PLyObToTuple
93 typedef union PLyTypeOutput
99 /* all we need to move Postgresql data to Python objects,
102 typedef struct PLyTypeInfo
109 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
110 * 1 rowtype 2 rowtype, but I/O functions not set up yet
115 /* cached procedure data */
116 typedef struct PLyProcedure
118 char *proname; /* SQL name of procedure */
119 char *pyname; /* Python name of procedure */
120 TransactionId fn_xmin;
123 PLyTypeInfo result; /* also used to store info for trigger tuple
125 bool is_setof; /* true, if procedure returns result set */
126 PyObject *setof; /* contents of result set. */
127 char **argnames; /* Argument names */
128 PLyTypeInfo args[FUNC_MAX_ARGS];
130 PyObject *code; /* compiled procedure code */
131 PyObject *statics; /* data saved across calls, local scope */
132 PyObject *globals; /* data saved across calls, global scope */
133 PyObject *me; /* PyCObject containing pointer to this
139 typedef struct PLyPlanObject
142 void *plan; /* return of an SPI_saveplan */
149 typedef struct PLyResultObject
152 /* HeapTuple *tuples; */
153 PyObject * nrows; /* number of rows returned by query */
154 PyObject *rows; /* data rows, or None if no data returned */
155 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
159 /* function declarations */
161 /* Two exported functions: first is the magic telling Postgresql
162 * what function call interface it implements. Second is for
163 * initialization of the interpreter during library load.
165 Datum plpython_call_handler(PG_FUNCTION_ARGS);
168 PG_FUNCTION_INFO_V1(plpython_call_handler);
170 /* most of the remaining of the declarations, all static */
172 /* these should only be called once at the first call
173 * of plpython_call_handler. initialize the python interpreter
176 static void PLy_init_interp(void);
177 static void PLy_init_plpy(void);
179 /* call PyErr_SetString with a vprint interface */
181 PLy_exception_set(PyObject *, const char *,...)
182 __attribute__((format(printf, 2, 3)));
184 /* Get the innermost python procedure called from the backend */
185 static char *PLy_procedure_name(PLyProcedure *);
187 /* some utility functions */
188 static void PLy_elog(int, const char *,...);
189 static char *PLy_traceback(int *);
190 static char *PLy_vprintf(const char *fmt, va_list ap);
191 static char *PLy_printf(const char *fmt,...);
193 static void *PLy_malloc(size_t);
194 static void *PLy_realloc(void *, size_t);
195 static char *PLy_strdup(const char *);
196 static void PLy_free(void *);
198 /* sub handlers for functions and triggers */
199 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
200 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
202 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
203 static void PLy_function_delete_args(PLyProcedure *);
204 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
206 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
207 TriggerData *, HeapTuple);
209 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
211 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
214 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
216 HeapTuple procTup, char *key);
218 static void PLy_procedure_compile(PLyProcedure *, const char *);
219 static char *PLy_procedure_munge_source(const char *, const char *);
220 static void PLy_procedure_delete(PLyProcedure *);
222 static void PLy_typeinfo_init(PLyTypeInfo *);
223 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
224 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
225 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
226 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
227 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
228 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
229 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
231 /* conversion functions */
232 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
233 static PyObject *PLyBool_FromString(const char *);
234 static PyObject *PLyFloat_FromString(const char *);
235 static PyObject *PLyInt_FromString(const char *);
236 static PyObject *PLyLong_FromString(const char *);
237 static PyObject *PLyString_FromString(const char *);
239 static HeapTuple PLyMapping_ToTuple(PLyTypeInfo *, PyObject *);
240 static HeapTuple PLySequence_ToTuple(PLyTypeInfo *, PyObject *);
241 static HeapTuple PLyObject_ToTuple(PLyTypeInfo *, PyObject *);
244 * Currently active plpython function
246 static PLyProcedure *PLy_curr_procedure = NULL;
249 * When a callback from Python into PG incurs an error, we temporarily store
250 * the error information here, and return NULL to the Python interpreter.
251 * Any further callback attempts immediately fail, and when the Python
252 * interpreter returns to the calling function, we re-throw the error (even if
253 * Python thinks it trapped the error and doesn't return NULL). Eventually
254 * this ought to be improved to let Python code really truly trap the error,
255 * but that's more of a change from the pre-8.0 semantics than I have time for
256 * now --- it will only be possible if the callback query is executed inside a
259 static ErrorData *PLy_error_in_progress = NULL;
261 static PyObject *PLy_interp_globals = NULL;
262 static PyObject *PLy_interp_safe_globals = NULL;
263 static PyObject *PLy_procedure_cache = NULL;
265 /* Python exceptions */
266 static PyObject *PLy_exc_error = NULL;
267 static PyObject *PLy_exc_fatal = NULL;
268 static PyObject *PLy_exc_spi_error = NULL;
270 /* some globals for the python module */
271 static char PLy_plan_doc[] = {
272 "Store a PostgreSQL plan"
275 static char PLy_result_doc[] = {
276 "Results of a PostgreSQL query"
281 * the function definitions
285 * This routine is a crock, and so is everyplace that calls it. The problem
286 * is that the cached form of plpython functions/queries is allocated permanently
287 * (mostly via malloc()) and never released until backend exit. Subsidiary
288 * data structures such as fmgr info records therefore must live forever
289 * as well. A better implementation would store all this stuff in a per-
290 * function memory context that could be reclaimed at need. In the meantime,
291 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
292 * it might allocate, and whatever the eventual function might allocate using
293 * fn_mcxt, will live forever too.
296 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
298 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
302 plpython_call_handler(PG_FUNCTION_ARGS)
305 PLyProcedure *save_curr_proc;
306 PLyProcedure *volatile proc = NULL;
308 if (SPI_connect() != SPI_OK_CONNECT)
309 elog(ERROR, "could not connect to SPI manager");
311 save_curr_proc = PLy_curr_procedure;
315 if (CALLED_AS_TRIGGER(fcinfo))
317 TriggerData *tdata = (TriggerData *) fcinfo->context;
320 proc = PLy_procedure_get(fcinfo,
321 RelationGetRelid(tdata->tg_relation));
322 PLy_curr_procedure = proc;
323 trv = PLy_trigger_handler(fcinfo, proc);
324 retval = PointerGetDatum(trv);
328 proc = PLy_procedure_get(fcinfo, InvalidOid);
329 PLy_curr_procedure = proc;
330 retval = PLy_function_handler(fcinfo, proc);
335 PLy_curr_procedure = save_curr_proc;
338 /* note: Py_DECREF needs braces around it, as of 2003/08 */
346 PLy_curr_procedure = save_curr_proc;
353 /* trigger and function sub handlers
355 * the python function is expected to return Py_None if the tuple is
356 * acceptable and unmodified. Otherwise it should return a PyString
357 * object who's value is SKIP, or MODIFY. SKIP means don't perform
358 * this action. MODIFY means the tuple has been modified, so update
359 * tuple and perform action. SKIP and MODIFY assume the trigger fires
360 * BEFORE the event and is ROW level. postgres expects the function
361 * to take no arguments and return an argument of type trigger.
364 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
367 PyObject *volatile plargs = NULL;
368 PyObject *volatile plrv = NULL;
372 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
373 plrv = PLy_procedure_call(proc, "TD", plargs);
375 Assert(plrv != NULL);
376 Assert(!PLy_error_in_progress);
379 * Disconnect from SPI manager
381 if (SPI_finish() != SPI_OK_FINISH)
382 elog(ERROR, "SPI_finish failed");
385 * return of None means we're happy with the tuple
391 if (!PyString_Check(plrv))
393 (errcode(ERRCODE_DATA_EXCEPTION),
394 errmsg("unexpected return value from trigger procedure"),
395 errdetail("Expected None or a String.")));
397 srv = PyString_AsString(plrv);
398 if (pg_strcasecmp(srv, "SKIP") == 0)
400 else if (pg_strcasecmp(srv, "MODIFY") == 0)
402 TriggerData *tdata = (TriggerData *) fcinfo->context;
404 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
405 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
406 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
408 elog(WARNING, "ignoring modified tuple in DELETE trigger");
410 else if (pg_strcasecmp(srv, "OK") != 0)
413 * accept "OK" as an alternative to None; otherwise, raise an
417 (errcode(ERRCODE_DATA_EXCEPTION),
418 errmsg("unexpected return value from trigger procedure"),
419 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
439 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
442 PyObject *volatile plntup;
443 PyObject *volatile plkeys;
444 PyObject *volatile platt;
445 PyObject *volatile plval;
446 PyObject *volatile plstr;
452 int *volatile modattrs;
453 Datum *volatile modvalues;
454 char *volatile modnulls;
457 plntup = plkeys = platt = plval = plstr = NULL;
464 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
465 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
466 if (!PyDict_Check(plntup))
467 elog(ERROR, "TD[\"new\"] is not a dictionary object");
470 plkeys = PyDict_Keys(plntup);
471 natts = PyList_Size(plkeys);
473 modattrs = (int *) palloc(natts * sizeof(int));
474 modvalues = (Datum *) palloc(natts * sizeof(Datum));
475 modnulls = (char *) palloc(natts * sizeof(char));
477 tupdesc = tdata->tg_relation->rd_att;
479 for (i = 0; i < natts; i++)
483 platt = PyList_GetItem(plkeys, i);
484 if (!PyString_Check(platt))
485 elog(ERROR, "attribute name is not a string");
486 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
487 if (attn == SPI_ERROR_NOATTRIBUTE)
488 elog(ERROR, "invalid attribute \"%s\" in tuple",
489 PyString_AsString(platt));
492 plval = PyDict_GetItem(plntup, platt);
494 elog(FATAL, "python interpreter is probably corrupted");
500 if (tupdesc->attrs[atti]->attisdropped)
502 modvalues[i] = (Datum) 0;
505 else if (plval != Py_None)
507 plstr = PyObject_Str(plval);
509 PLy_elog(ERROR, "function \"%s\" could not modify tuple",
511 src = PyString_AsString(plstr);
514 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
516 proc->result.out.r.atts[atti].typioparam,
517 tupdesc->attrs[atti]->atttypmod);
526 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
528 proc->result.out.r.atts[atti].typioparam,
529 tupdesc->attrs[atti]->atttypmod);
537 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
538 modattrs, modvalues, modnulls);
540 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
571 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
573 TriggerData *tdata = (TriggerData *) fcinfo->context;
584 PyObject *volatile pltdata = NULL;
589 pltdata = PyDict_New();
591 PLy_elog(ERROR, "could not build arguments for trigger procedure");
593 pltname = PyString_FromString(tdata->tg_trigger->tgname);
594 PyDict_SetItemString(pltdata, "name", pltname);
597 stroid = DatumGetCString(DirectFunctionCall1(oidout,
598 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
599 pltrelid = PyString_FromString(stroid);
600 PyDict_SetItemString(pltdata, "relid", pltrelid);
604 stroid = SPI_getrelname(tdata->tg_relation);
605 plttablename = PyString_FromString(stroid);
606 PyDict_SetItemString(pltdata, "table_name", plttablename);
607 Py_DECREF(plttablename);
610 stroid = SPI_getnspname(tdata->tg_relation);
611 plttableschema = PyString_FromString(stroid);
612 PyDict_SetItemString(pltdata, "table_schema", plttableschema);
613 Py_DECREF(plttableschema);
617 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
618 pltwhen = PyString_FromString("BEFORE");
619 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
620 pltwhen = PyString_FromString("AFTER");
623 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
624 pltwhen = NULL; /* keep compiler quiet */
626 PyDict_SetItemString(pltdata, "when", pltwhen);
629 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
631 pltlevel = PyString_FromString("ROW");
632 PyDict_SetItemString(pltdata, "level", pltlevel);
635 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
637 pltevent = PyString_FromString("INSERT");
639 PyDict_SetItemString(pltdata, "old", Py_None);
640 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
641 tdata->tg_relation->rd_att);
642 PyDict_SetItemString(pltdata, "new", pytnew);
644 *rv = tdata->tg_trigtuple;
646 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
648 pltevent = PyString_FromString("DELETE");
650 PyDict_SetItemString(pltdata, "new", Py_None);
651 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
652 tdata->tg_relation->rd_att);
653 PyDict_SetItemString(pltdata, "old", pytold);
655 *rv = tdata->tg_trigtuple;
657 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
659 pltevent = PyString_FromString("UPDATE");
661 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
662 tdata->tg_relation->rd_att);
663 PyDict_SetItemString(pltdata, "new", pytnew);
665 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
666 tdata->tg_relation->rd_att);
667 PyDict_SetItemString(pltdata, "old", pytold);
669 *rv = tdata->tg_newtuple;
673 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
674 pltevent = NULL; /* keep compiler quiet */
677 PyDict_SetItemString(pltdata, "event", pltevent);
680 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
682 pltlevel = PyString_FromString("STATEMENT");
683 PyDict_SetItemString(pltdata, "level", pltlevel);
686 PyDict_SetItemString(pltdata, "old", Py_None);
687 PyDict_SetItemString(pltdata, "new", Py_None);
690 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
691 pltevent = PyString_FromString("INSERT");
692 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
693 pltevent = PyString_FromString("DELETE");
694 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
695 pltevent = PyString_FromString("UPDATE");
698 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
699 pltevent = NULL; /* keep compiler quiet */
702 PyDict_SetItemString(pltdata, "event", pltevent);
706 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
708 if (tdata->tg_trigger->tgnargs)
716 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
717 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
719 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
722 * stolen, don't Py_DECREF
724 PyList_SetItem(pltargs, i, pltarg);
732 PyDict_SetItemString(pltdata, "args", pltargs);
747 /* function handler and friends */
749 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
752 PyObject *volatile plargs = NULL;
753 PyObject *volatile plrv = NULL;
754 PyObject *volatile plrv_so = NULL;
759 if (!proc->is_setof || proc->setof == NULL)
761 /* Simple type returning function or first time for SETOF function */
762 plargs = PLy_function_build_args(fcinfo, proc);
763 plrv = PLy_procedure_call(proc, "args", plargs);
767 * SETOF function parameters will be deleted when last row is
770 PLy_function_delete_args(proc);
771 Assert(plrv != NULL);
772 Assert(!PLy_error_in_progress);
776 * Disconnect from SPI manager and then create the return values datum
777 * (if the input function does a palloc for it this must not be
778 * allocated in the SPI memory context because SPI_finish would free
781 if (SPI_finish() != SPI_OK_FINISH)
782 elog(ERROR, "SPI_finish failed");
786 bool has_error = false;
787 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
789 if (proc->setof == NULL)
791 /* first time -- do checks and setup */
792 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
793 (rsi->allowedModes & SFRM_ValuePerCall) == 0)
796 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
797 errmsg("only value per call is allowed")));
799 rsi->returnMode = SFRM_ValuePerCall;
801 /* Make iterator out of returned object */
802 proc->setof = PyObject_GetIter(plrv);
806 if (proc->setof == NULL)
808 (errcode(ERRCODE_DATATYPE_MISMATCH),
809 errmsg("returned object can not be iterated"),
810 errdetail("SETOF must be returned as iterable object")));
813 /* Fetch next from iterator */
814 plrv = PyIter_Next(proc->setof);
816 rsi->isDone = ExprMultipleResult;
819 rsi->isDone = ExprEndResult;
820 has_error = PyErr_Occurred() != NULL;
823 if (rsi->isDone == ExprEndResult)
825 /* Iterator is exhausted or error happened */
826 Py_DECREF(proc->setof);
833 PLy_function_delete_args(proc);
837 (errcode(ERRCODE_DATA_EXCEPTION),
838 errmsg("error fetching next item from iterator")));
840 fcinfo->isnull = true;
846 * If the function is declared to return void, the Python return value
847 * must be None. For void-returning functions, we also treat a None
848 * return value as a special "void datum" rather than NULL (as is the
849 * case for non-void-returning functions).
851 if (proc->result.out.d.typoid == VOIDOID)
855 (errcode(ERRCODE_DATATYPE_MISMATCH),
856 errmsg("invalid return value from plpython function"),
857 errdetail("Functions returning type \"void\" must return None.")));
859 fcinfo->isnull = false;
862 else if (plrv == Py_None)
864 fcinfo->isnull = true;
865 if (proc->result.is_rowtype < 1)
866 rv = InputFunctionCall(&proc->result.out.d.typfunc,
868 proc->result.out.d.typioparam,
874 else if (proc->result.is_rowtype >= 1)
876 HeapTuple tuple = NULL;
878 if (PySequence_Check(plrv))
879 /* composite type as sequence (tuple, list etc) */
880 tuple = PLySequence_ToTuple(&proc->result, plrv);
881 else if (PyMapping_Check(plrv))
882 /* composite type as mapping (currently only dict) */
883 tuple = PLyMapping_ToTuple(&proc->result, plrv);
885 /* returned as smth, must provide method __getattr__(name) */
886 tuple = PLyObject_ToTuple(&proc->result, plrv);
890 fcinfo->isnull = false;
891 rv = HeapTupleGetDatum(tuple);
895 fcinfo->isnull = true;
901 fcinfo->isnull = false;
902 plrv_so = PyObject_Str(plrv);
904 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
905 plrv_sc = PyString_AsString(plrv_so);
906 rv = InputFunctionCall(&proc->result.out.d.typfunc,
908 proc->result.out.d.typioparam,
930 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
934 PyDict_SetItemString(proc->globals, kargs, vargs);
935 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
936 proc->globals, proc->globals);
939 * If there was an error in a PG callback, propagate that no matter what
940 * Python claims about its success.
942 if (PLy_error_in_progress)
944 ErrorData *edata = PLy_error_in_progress;
946 PLy_error_in_progress = NULL;
950 if (rv == NULL || PyErr_Occurred())
953 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
960 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
962 PyObject *volatile arg = NULL;
963 PyObject *volatile args = NULL;
968 args = PyList_New(proc->nargs);
969 for (i = 0; i < proc->nargs; i++)
971 if (proc->args[i].is_rowtype > 0)
973 if (fcinfo->argnull[i])
981 HeapTupleData tmptup;
983 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
984 /* Extract rowtype info and find a tupdesc */
985 tupType = HeapTupleHeaderGetTypeId(td);
986 tupTypmod = HeapTupleHeaderGetTypMod(td);
987 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
989 /* Set up I/O funcs if not done yet */
990 if (proc->args[i].is_rowtype != 1)
991 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
993 /* Build a temporary HeapTuple control structure */
994 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
997 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
998 ReleaseTupleDesc(tupdesc);
1003 if (fcinfo->argnull[i])
1009 ct = OutputFunctionCall(&(proc->args[i].in.d.typfunc),
1011 arg = (proc->args[i].in.d.func) (ct);
1022 if (PyList_SetItem(args, i, arg) == -1 ||
1024 PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1))
1025 PLy_elog(ERROR, "problem setting up arguments for \"%s\"", proc->proname);
1043 PLy_function_delete_args(PLyProcedure * proc)
1047 if (!proc->argnames)
1050 for (i = 0; i < proc->nargs; i++)
1051 PyDict_DelItemString(proc->globals, proc->argnames[i]);
1056 * PLyProcedure functions
1059 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
1060 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
1061 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
1064 static PLyProcedure *
1065 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
1071 PLyProcedure *proc = NULL;
1074 fn_oid = fcinfo->flinfo->fn_oid;
1075 procTup = SearchSysCache(PROCOID,
1076 ObjectIdGetDatum(fn_oid),
1078 if (!HeapTupleIsValid(procTup))
1079 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1081 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
1082 if (rv >= sizeof(key) || rv < 0)
1083 elog(ERROR, "key too long");
1085 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
1090 if (!PyCObject_Check(plproc))
1091 elog(FATAL, "expected a PyCObject, didn't get one");
1093 proc = PyCObject_AsVoidPtr(plproc);
1094 if (proc->me != plproc)
1095 elog(FATAL, "proc->me != plproc");
1096 /* did we find an up-to-date cache entry? */
1097 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
1098 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
1106 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
1108 ReleaseSysCache(procTup);
1113 static PLyProcedure *
1114 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
1115 HeapTuple procTup, char *key)
1117 char procName[NAMEDATALEN + 256];
1118 Form_pg_proc procStruct;
1119 PLyProcedure *volatile proc;
1120 char *volatile procSource = NULL;
1129 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1131 if (OidIsValid(tgreloid))
1132 rv = snprintf(procName, sizeof(procName),
1133 "__plpython_procedure_%s_%u_trigger_%u",
1134 NameStr(procStruct->proname),
1135 fcinfo->flinfo->fn_oid,
1138 rv = snprintf(procName, sizeof(procName),
1139 "__plpython_procedure_%s_%u",
1140 NameStr(procStruct->proname),
1141 fcinfo->flinfo->fn_oid);
1142 if (rv >= sizeof(procName) || rv < 0)
1143 elog(ERROR, "procedure name would overrun buffer");
1145 proc = PLy_malloc(sizeof(PLyProcedure));
1146 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1147 proc->pyname = PLy_strdup(procName);
1148 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1149 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1150 /* Remember if function is STABLE/IMMUTABLE */
1152 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1153 PLy_typeinfo_init(&proc->result);
1154 for (i = 0; i < FUNC_MAX_ARGS; i++)
1155 PLy_typeinfo_init(&proc->args[i]);
1157 proc->code = proc->statics = NULL;
1158 proc->globals = proc->me = NULL;
1159 proc->is_setof = procStruct->proretset;
1161 proc->argnames = NULL;
1166 * get information required for output conversion of the return value,
1167 * but only if this isn't a trigger.
1169 if (!CALLED_AS_TRIGGER(fcinfo))
1171 HeapTuple rvTypeTup;
1172 Form_pg_type rvTypeStruct;
1174 rvTypeTup = SearchSysCache(TYPEOID,
1175 ObjectIdGetDatum(procStruct->prorettype),
1177 if (!HeapTupleIsValid(rvTypeTup))
1178 elog(ERROR, "cache lookup failed for type %u",
1179 procStruct->prorettype);
1180 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1182 /* Disallow pseudotype result, except for void */
1183 if (rvTypeStruct->typtype == 'p' &&
1184 procStruct->prorettype != VOIDOID)
1186 if (procStruct->prorettype == TRIGGEROID)
1188 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1189 errmsg("trigger functions may only be called as triggers")));
1192 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1193 errmsg("plpython functions cannot return type %s",
1194 format_type_be(procStruct->prorettype))));
1197 if (rvTypeStruct->typtype == 'c')
1200 * Tuple: set up later, during first call to
1201 * PLy_function_handler
1203 proc->result.out.d.typoid = procStruct->prorettype;
1204 proc->result.is_rowtype = 2;
1207 PLy_output_datum_func(&proc->result, rvTypeTup);
1209 ReleaseSysCache(rvTypeTup);
1214 * input/output conversion for trigger tuples. use the result
1215 * TypeInfo variable to store the tuple conversion info.
1217 TriggerData *tdata = (TriggerData *) fcinfo->context;
1219 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1220 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1224 * now get information required for input conversion of the
1225 * procedure's arguments.
1227 proc->nargs = fcinfo->nargs;
1230 argnames = SysCacheGetAttr(PROCOID, procTup, Anum_pg_proc_proargnames, &isnull);
1233 deconstruct_array(DatumGetArrayTypeP(argnames), TEXTOID, -1, false, 'i',
1234 &elems, NULL, &nelems);
1235 if (nelems != proc->nargs)
1237 "proargnames must have the same number of elements "
1238 "as the function has arguments");
1239 proc->argnames = (char **) PLy_malloc(sizeof(char *) * proc->nargs);
1242 for (i = 0; i < fcinfo->nargs; i++)
1244 HeapTuple argTypeTup;
1245 Form_pg_type argTypeStruct;
1247 argTypeTup = SearchSysCache(TYPEOID,
1248 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1250 if (!HeapTupleIsValid(argTypeTup))
1251 elog(ERROR, "cache lookup failed for type %u",
1252 procStruct->proargtypes.values[i]);
1253 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1255 /* Disallow pseudotype argument */
1256 if (argTypeStruct->typtype == 'p')
1258 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1259 errmsg("plpython functions cannot take type %s",
1260 format_type_be(procStruct->proargtypes.values[i]))));
1262 if (argTypeStruct->typtype != 'c')
1263 PLy_input_datum_func(&(proc->args[i]),
1264 procStruct->proargtypes.values[i],
1267 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1269 ReleaseSysCache(argTypeTup);
1271 /* Fetch argument name */
1273 proc->argnames[i] = PLy_strdup(DatumGetCString(DirectFunctionCall1(textout, elems[i])));
1277 * get the text of the function.
1279 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1280 Anum_pg_proc_prosrc, &isnull);
1282 elog(ERROR, "null prosrc");
1283 procSource = DatumGetCString(DirectFunctionCall1(textout,
1286 PLy_procedure_compile(proc, procSource);
1290 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1291 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1295 PLy_procedure_delete(proc);
1307 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1309 PyObject *crv = NULL;
1312 proc->globals = PyDict_Copy(PLy_interp_globals);
1315 * SD is private preserved data between calls. GD is global data shared by
1318 proc->statics = PyDict_New();
1319 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1322 * insert the function code into the interpreter
1324 msrc = PLy_procedure_munge_source(proc->pyname, src);
1325 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1328 if (crv != NULL && (!PyErr_Occurred()))
1331 char call[NAMEDATALEN + 256];
1336 * compile a call to the function
1338 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1339 if (clen < 0 || clen >= sizeof(call))
1340 elog(ERROR, "string would overflow buffer");
1341 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1342 if (proc->code != NULL && (!PyErr_Occurred()))
1348 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1352 PLy_procedure_munge_source(const char *name, const char *src)
1361 * room for function source and the def statement
1363 mlen = (strlen(src) * 2) + strlen(name) + 16;
1365 mrc = PLy_malloc(mlen);
1366 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1367 Assert(plen >= 0 && plen < mlen);
1374 if (*sp == '\r' && *(sp + 1) == '\n')
1377 if (*sp == '\n' || *sp == '\r')
1390 if (mp > (mrc + mlen))
1391 elog(FATAL, "buffer overrun in PLy_munge_source");
1397 PLy_procedure_delete(PLyProcedure * proc)
1401 Py_XDECREF(proc->code);
1402 Py_XDECREF(proc->statics);
1403 Py_XDECREF(proc->globals);
1404 Py_XDECREF(proc->me);
1406 PLy_free(proc->proname);
1408 PLy_free(proc->pyname);
1409 for (i = 0; i < proc->nargs; i++)
1411 if (proc->args[i].is_rowtype == 1)
1413 if (proc->args[i].in.r.atts)
1414 PLy_free(proc->args[i].in.r.atts);
1415 if (proc->args[i].out.r.atts)
1416 PLy_free(proc->args[i].out.r.atts);
1418 if (proc->argnames && proc->argnames[i])
1419 PLy_free(proc->argnames[i]);
1422 PLy_free(proc->argnames);
1425 /* conversion functions. remember output from python is
1426 * input to postgresql, and vis versa.
1429 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1433 if (arg->is_rowtype == 0)
1434 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1436 arg->is_rowtype = 1;
1437 arg->in.r.natts = desc->natts;
1438 arg->in.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1440 for (i = 0; i < desc->natts; i++)
1444 if (desc->attrs[i]->attisdropped)
1447 typeTup = SearchSysCache(TYPEOID,
1448 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1450 if (!HeapTupleIsValid(typeTup))
1451 elog(ERROR, "cache lookup failed for type %u",
1452 desc->attrs[i]->atttypid);
1454 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1455 desc->attrs[i]->atttypid,
1458 ReleaseSysCache(typeTup);
1463 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1467 if (arg->is_rowtype == 0)
1468 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1470 arg->is_rowtype = 1;
1471 arg->out.r.natts = desc->natts;
1472 arg->out.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1474 for (i = 0; i < desc->natts; i++)
1478 if (desc->attrs[i]->attisdropped)
1481 typeTup = SearchSysCache(TYPEOID,
1482 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1484 if (!HeapTupleIsValid(typeTup))
1485 elog(ERROR, "cache lookup failed for type %u",
1486 desc->attrs[i]->atttypid);
1488 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1490 ReleaseSysCache(typeTup);
1495 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1497 if (arg->is_rowtype > 0)
1498 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1499 arg->is_rowtype = 0;
1500 PLy_output_datum_func2(&(arg->out.d), typeTup);
1504 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1506 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1508 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1509 arg->typoid = HeapTupleGetOid(typeTup);
1510 arg->typioparam = getTypeIOParam(typeTup);
1511 arg->typbyval = typeStruct->typbyval;
1515 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1517 if (arg->is_rowtype > 0)
1518 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1519 arg->is_rowtype = 0;
1520 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1524 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1526 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1528 /* Get the type's conversion information */
1529 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1530 arg->typioparam = getTypeIOParam(typeTup);
1531 arg->typbyval = typeStruct->typbyval;
1533 /* Determine which kind of Python object we will convert to */
1537 arg->func = PLyBool_FromString;
1542 arg->func = PLyFloat_FromString;
1546 arg->func = PLyInt_FromString;
1549 arg->func = PLyLong_FromString;
1552 arg->func = PLyString_FromString;
1558 PLy_typeinfo_init(PLyTypeInfo * arg)
1560 arg->is_rowtype = -1;
1561 arg->in.r.natts = arg->out.r.natts = 0;
1562 arg->in.r.atts = NULL;
1563 arg->out.r.atts = NULL;
1567 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1569 if (arg->is_rowtype == 1)
1572 PLy_free(arg->in.r.atts);
1573 if (arg->out.r.atts)
1574 PLy_free(arg->out.r.atts);
1578 /* assumes that a bool is always returned as a 't' or 'f' */
1580 PLyBool_FromString(const char *src)
1583 return PyInt_FromLong(1);
1584 return PyInt_FromLong(0);
1588 PLyFloat_FromString(const char *src)
1594 v = strtod(src, &eptr);
1595 if (*eptr != '\0' || errno)
1597 return PyFloat_FromDouble(v);
1601 PLyInt_FromString(const char *src)
1607 v = strtol(src, &eptr, 0);
1608 if (*eptr != '\0' || errno)
1610 return PyInt_FromLong(v);
1614 PLyLong_FromString(const char *src)
1616 return PyLong_FromString((char *) src, NULL, 0);
1620 PLyString_FromString(const char *src)
1622 return PyString_FromString(src);
1626 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1628 PyObject *volatile dict;
1631 if (info->is_rowtype != 1)
1632 elog(ERROR, "PLyTypeInfo structure describes a datum");
1634 dict = PyDict_New();
1636 PLy_elog(ERROR, "could not create tuple dictionary");
1640 for (i = 0; i < info->in.r.natts; i++)
1648 if (desc->attrs[i]->attisdropped)
1651 key = NameStr(desc->attrs[i]->attname);
1652 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1654 if (is_null || info->in.r.atts[i].func == NULL)
1655 PyDict_SetItemString(dict, key, Py_None);
1658 vsrc = OutputFunctionCall(&info->in.r.atts[i].typfunc,
1662 * no exceptions allowed
1664 value = info->in.r.atts[i].func(vsrc);
1666 PyDict_SetItemString(dict, key, value);
1683 PLyMapping_ToTuple(PLyTypeInfo * info, PyObject * mapping)
1691 Assert(PyMapping_Check(mapping));
1693 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1694 if (info->is_rowtype == 2)
1695 PLy_output_tuple_funcs(info, desc);
1696 Assert(info->is_rowtype == 1);
1699 values = palloc(sizeof(Datum) * desc->natts);
1700 nulls = palloc(sizeof(char) * desc->natts);
1701 for (i = 0; i < desc->natts; ++i)
1707 key = NameStr(desc->attrs[i]->attname);
1711 value = PyMapping_GetItemString(mapping, key);
1712 if (value == Py_None)
1714 values[i] = (Datum) NULL;
1721 so = PyObject_Str(value);
1723 PLy_elog(ERROR, "can't convert mapping type");
1724 valuestr = PyString_AsString(so);
1726 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1728 ,info->out.r.atts[i].typioparam
1736 (errcode(ERRCODE_UNDEFINED_COLUMN),
1737 errmsg("no mapping found with key \"%s\"", key),
1738 errhint("to return null in specific column, "
1739 "add value None to map with key named after column")));
1753 tuple = heap_formtuple(desc, values, nulls);
1754 ReleaseTupleDesc(desc);
1763 PLySequence_ToTuple(PLyTypeInfo * info, PyObject * sequence)
1771 Assert(PySequence_Check(sequence));
1774 * Check that sequence length is exactly same as PG tuple's. We actually
1775 * can ignore exceeding items or assume missing ones as null but to avoid
1776 * plpython developer's errors we are strict here
1778 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1779 if (PySequence_Length(sequence) != desc->natts)
1781 (errcode(ERRCODE_DATATYPE_MISMATCH),
1782 errmsg("returned sequence's length must be same as tuple's length")));
1784 if (info->is_rowtype == 2)
1785 PLy_output_tuple_funcs(info, desc);
1786 Assert(info->is_rowtype == 1);
1789 values = palloc(sizeof(Datum) * desc->natts);
1790 nulls = palloc(sizeof(char) * desc->natts);
1791 for (i = 0; i < desc->natts; ++i)
1799 value = PySequence_GetItem(sequence, i);
1801 if (value == Py_None)
1803 values[i] = (Datum) NULL;
1810 so = PyObject_Str(value);
1812 PLy_elog(ERROR, "can't convert sequence type");
1813 valuestr = PyString_AsString(so);
1814 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1816 ,info->out.r.atts[i].typioparam
1835 tuple = heap_formtuple(desc, values, nulls);
1836 ReleaseTupleDesc(desc);
1845 PLyObject_ToTuple(PLyTypeInfo * info, PyObject * object)
1853 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1854 if (info->is_rowtype == 2)
1855 PLy_output_tuple_funcs(info, desc);
1856 Assert(info->is_rowtype == 1);
1859 values = palloc(sizeof(Datum) * desc->natts);
1860 nulls = palloc(sizeof(char) * desc->natts);
1861 for (i = 0; i < desc->natts; ++i)
1867 key = NameStr(desc->attrs[i]->attname);
1871 value = PyObject_GetAttrString(object, key);
1872 if (value == Py_None)
1874 values[i] = (Datum) NULL;
1881 so = PyObject_Str(value);
1883 PLy_elog(ERROR, "can't convert object type");
1884 valuestr = PyString_AsString(so);
1885 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1887 ,info->out.r.atts[i].typioparam
1895 (errcode(ERRCODE_UNDEFINED_COLUMN),
1896 errmsg("no attribute named \"%s\"", key),
1897 errhint("to return null in specific column, "
1898 "let returned object to have attribute named "
1899 "after column with value None")));
1913 tuple = heap_formtuple(desc, values, nulls);
1914 ReleaseTupleDesc(desc);
1922 /* initialization, some python variables function declared here */
1924 /* interface to postgresql elog */
1925 static PyObject *PLy_debug(PyObject *, PyObject *);
1926 static PyObject *PLy_log(PyObject *, PyObject *);
1927 static PyObject *PLy_info(PyObject *, PyObject *);
1928 static PyObject *PLy_notice(PyObject *, PyObject *);
1929 static PyObject *PLy_warning(PyObject *, PyObject *);
1930 static PyObject *PLy_error(PyObject *, PyObject *);
1931 static PyObject *PLy_fatal(PyObject *, PyObject *);
1933 /* PLyPlanObject, PLyResultObject and SPI interface */
1934 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1935 static PyObject *PLy_plan_new(void);
1936 static void PLy_plan_dealloc(PyObject *);
1937 static PyObject *PLy_plan_getattr(PyObject *, char *);
1938 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1940 static PyObject *PLy_result_new(void);
1941 static void PLy_result_dealloc(PyObject *);
1942 static PyObject *PLy_result_getattr(PyObject *, char *);
1943 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1944 static PyObject *PLy_result_status(PyObject *, PyObject *);
1945 static int PLy_result_length(PyObject *);
1946 static PyObject *PLy_result_item(PyObject *, int);
1947 static PyObject *PLy_result_slice(PyObject *, int, int);
1948 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1949 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1952 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1953 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1954 static PyObject *PLy_spi_execute_query(char *query, long limit);
1955 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1956 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1959 static PyTypeObject PLy_PlanType = {
1960 PyObject_HEAD_INIT(NULL)
1962 "PLyPlan", /* tp_name */
1963 sizeof(PLyPlanObject), /* tp_size */
1964 0, /* tp_itemsize */
1969 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1971 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1975 0, /* tp_as_number */
1976 0, /* tp_as_sequence */
1977 0, /* tp_as_mapping */
1981 0, /* tp_getattro */
1982 0, /* tp_setattro */
1983 0, /* tp_as_buffer */
1984 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1985 PLy_plan_doc, /* tp_doc */
1988 static PyMethodDef PLy_plan_methods[] = {
1989 {"status", PLy_plan_status, METH_VARARGS, NULL},
1990 {NULL, NULL, 0, NULL}
1994 static PySequenceMethods PLy_result_as_sequence = {
1995 (inquiry) PLy_result_length, /* sq_length */
1996 (binaryfunc) 0, /* sq_concat */
1997 (intargfunc) 0, /* sq_repeat */
1998 (intargfunc) PLy_result_item, /* sq_item */
1999 (intintargfunc) PLy_result_slice, /* sq_slice */
2000 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
2001 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
2004 static PyTypeObject PLy_ResultType = {
2005 PyObject_HEAD_INIT(NULL)
2007 "PLyResult", /* tp_name */
2008 sizeof(PLyResultObject), /* tp_size */
2009 0, /* tp_itemsize */
2014 (destructor) PLy_result_dealloc, /* tp_dealloc */
2016 (getattrfunc) PLy_result_getattr, /* tp_getattr */
2020 0, /* tp_as_number */
2021 &PLy_result_as_sequence, /* tp_as_sequence */
2022 0, /* tp_as_mapping */
2026 0, /* tp_getattro */
2027 0, /* tp_setattro */
2028 0, /* tp_as_buffer */
2029 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2030 PLy_result_doc, /* tp_doc */
2033 static PyMethodDef PLy_result_methods[] = {
2034 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
2035 {"status", PLy_result_status, METH_VARARGS, NULL},
2036 {NULL, NULL, 0, NULL}
2039 static PyMethodDef PLy_methods[] = {
2043 {"debug", PLy_debug, METH_VARARGS, NULL},
2044 {"log", PLy_log, METH_VARARGS, NULL},
2045 {"info", PLy_info, METH_VARARGS, NULL},
2046 {"notice", PLy_notice, METH_VARARGS, NULL},
2047 {"warning", PLy_warning, METH_VARARGS, NULL},
2048 {"error", PLy_error, METH_VARARGS, NULL},
2049 {"fatal", PLy_fatal, METH_VARARGS, NULL},
2052 * create a stored plan
2054 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
2057 * execute a plan or query
2059 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
2061 {NULL, NULL, 0, NULL}
2065 /* plan object methods */
2071 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
2079 return (PyObject *) ob;
2084 PLy_plan_dealloc(PyObject * arg)
2086 PLyPlanObject *ob = (PLyPlanObject *) arg;
2089 SPI_freeplan(ob->plan);
2091 PLy_free(ob->types);
2096 for (i = 0; i < ob->nargs; i++)
2097 PLy_typeinfo_dealloc(&ob->args[i]);
2101 arg->ob_type->tp_free(arg);
2106 PLy_plan_getattr(PyObject * self, char *name)
2108 return Py_FindMethod(PLy_plan_methods, self, name);
2112 PLy_plan_status(PyObject * self, PyObject * args)
2114 if (PyArg_ParseTuple(args, ""))
2118 /* return PyInt_FromLong(self->status); */
2120 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
2126 /* result object methods */
2129 PLy_result_new(void)
2131 PLyResultObject *ob;
2133 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
2136 /* ob->tuples = NULL; */
2139 ob->status = Py_None;
2140 ob->nrows = PyInt_FromLong(-1);
2141 ob->rows = PyList_New(0);
2143 return (PyObject *) ob;
2147 PLy_result_dealloc(PyObject * arg)
2149 PLyResultObject *ob = (PLyResultObject *) arg;
2151 Py_XDECREF(ob->nrows);
2152 Py_XDECREF(ob->rows);
2153 Py_XDECREF(ob->status);
2155 arg->ob_type->tp_free(arg);
2159 PLy_result_getattr(PyObject * self, char *name)
2161 return Py_FindMethod(PLy_result_methods, self, name);
2165 PLy_result_nrows(PyObject * self, PyObject * args)
2167 PLyResultObject *ob = (PLyResultObject *) self;
2169 Py_INCREF(ob->nrows);
2174 PLy_result_status(PyObject * self, PyObject * args)
2176 PLyResultObject *ob = (PLyResultObject *) self;
2178 Py_INCREF(ob->status);
2183 PLy_result_length(PyObject * arg)
2185 PLyResultObject *ob = (PLyResultObject *) arg;
2187 return PyList_Size(ob->rows);
2191 PLy_result_item(PyObject * arg, int idx)
2194 PLyResultObject *ob = (PLyResultObject *) arg;
2196 rv = PyList_GetItem(ob->rows, idx);
2203 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
2206 PLyResultObject *ob = (PLyResultObject *) arg;
2209 rv = PyList_SetItem(ob->rows, idx, item);
2214 PLy_result_slice(PyObject * arg, int lidx, int hidx)
2217 PLyResultObject *ob = (PLyResultObject *) arg;
2219 rv = PyList_GetSlice(ob->rows, lidx, hidx);
2227 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
2230 PLyResultObject *ob = (PLyResultObject *) arg;
2232 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
2238 PLy_spi_prepare(PyObject * self, PyObject * args)
2240 PLyPlanObject *plan;
2241 PyObject *list = NULL;
2242 PyObject *volatile optr = NULL;
2245 MemoryContext oldcontext;
2247 /* Can't execute more if we have an unhandled error */
2248 if (PLy_error_in_progress)
2250 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2254 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
2256 PyErr_SetString(PLy_exc_spi_error,
2257 "Invalid arguments for plpy.prepare()");
2261 if (list && (!PySequence_Check(list)))
2263 PyErr_SetString(PLy_exc_spi_error,
2264 "Second argument in plpy.prepare() must be a sequence");
2268 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
2271 oldcontext = CurrentMemoryContext;
2279 nargs = PySequence_Length(list);
2282 plan->nargs = nargs;
2283 plan->types = PLy_malloc(sizeof(Oid) * nargs);
2284 plan->values = PLy_malloc(sizeof(Datum) * nargs);
2285 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
2288 * the other loop might throw an exception, if PLyTypeInfo
2289 * member isn't properly initialized the Py_DECREF(plan) will
2292 for (i = 0; i < nargs; i++)
2294 PLy_typeinfo_init(&plan->args[i]);
2295 plan->values[i] = PointerGetDatum(NULL);
2298 for (i = 0; i < nargs; i++)
2303 Form_pg_type typeStruct;
2305 optr = PySequence_GetItem(list, i);
2306 if (!PyString_Check(optr))
2307 elog(ERROR, "Type names must be strings.");
2308 sptr = PyString_AsString(optr);
2311 * Parse possibly-qualified type name and look it up in
2314 names = stringToQualifiedNameList(sptr,
2316 typeTup = typenameType(NULL,
2317 makeTypeNameFromNameList(names));
2319 optr = NULL; /* this is important */
2321 plan->types[i] = HeapTupleGetOid(typeTup);
2322 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2323 if (typeStruct->typtype != 'c')
2324 PLy_output_datum_func(&plan->args[i], typeTup);
2326 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
2327 ReleaseSysCache(typeTup);
2332 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2333 if (plan->plan == NULL)
2334 elog(ERROR, "SPI_prepare failed: %s",
2335 SPI_result_code_string(SPI_result));
2337 /* transfer plan from procCxt to topCxt */
2338 tmpplan = plan->plan;
2339 plan->plan = SPI_saveplan(tmpplan);
2340 SPI_freeplan(tmpplan);
2341 if (plan->plan == NULL)
2342 elog(ERROR, "SPI_saveplan failed: %s",
2343 SPI_result_code_string(SPI_result));
2347 MemoryContextSwitchTo(oldcontext);
2348 PLy_error_in_progress = CopyErrorData();
2352 if (!PyErr_Occurred())
2353 PyErr_SetString(PLy_exc_spi_error,
2354 "Unknown error in PLy_spi_prepare");
2355 /* XXX this oughta be replaced with errcontext mechanism */
2356 PLy_elog(WARNING, "in function %s:",
2357 PLy_procedure_name(PLy_curr_procedure));
2362 return (PyObject *) plan;
2365 /* execute(query="select * from foo", limit=5)
2366 * execute(plan=plan, values=(foo, bar), limit=5)
2369 PLy_spi_execute(PyObject * self, PyObject * args)
2373 PyObject *list = NULL;
2376 /* Can't execute more if we have an unhandled error */
2377 if (PLy_error_in_progress)
2379 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2383 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
2384 return PLy_spi_execute_query(query, limit);
2388 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
2389 is_PLyPlanObject(plan))
2390 return PLy_spi_execute_plan(plan, list, limit);
2392 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2397 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
2402 PLyPlanObject *plan;
2403 MemoryContext oldcontext;
2407 if (!PySequence_Check(list) || PyString_Check(list))
2409 char *msg = "plpy.execute() takes a sequence as its second argument";
2411 PyErr_SetString(PLy_exc_spi_error, msg);
2414 nargs = PySequence_Length(list);
2419 plan = (PLyPlanObject *) ob;
2421 if (nargs != plan->nargs)
2424 PyObject *so = PyObject_Str(list);
2427 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2428 PLy_procedure_name(PLy_curr_procedure));
2429 sv = PyString_AsString(so);
2430 PLy_exception_set(PLy_exc_spi_error,
2431 "Expected sequence of %d arguments, got %d. %s",
2432 plan->nargs, nargs, sv);
2438 oldcontext = CurrentMemoryContext;
2441 char *nulls = palloc(nargs * sizeof(char));
2443 for (i = 0; i < nargs; i++)
2448 elem = PySequence_GetItem(list, i);
2449 if (elem != Py_None)
2451 so = PyObject_Str(elem);
2453 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2454 PLy_procedure_name(PLy_curr_procedure));
2459 char *sv = PyString_AsString(so);
2462 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2464 plan->args[i].out.d.typioparam,
2481 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2483 plan->args[i].out.d.typioparam,
2489 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2490 PLy_curr_procedure->fn_readonly, limit);
2496 MemoryContextSwitchTo(oldcontext);
2497 PLy_error_in_progress = CopyErrorData();
2501 * cleanup plan->values array
2503 for (i = 0; i < nargs; i++)
2505 if (!plan->args[i].out.d.typbyval &&
2506 (plan->values[i] != PointerGetDatum(NULL)))
2508 pfree(DatumGetPointer(plan->values[i]));
2509 plan->values[i] = PointerGetDatum(NULL);
2513 if (!PyErr_Occurred())
2514 PyErr_SetString(PLy_exc_error,
2515 "Unknown error in PLy_spi_execute_plan");
2516 /* XXX this oughta be replaced with errcontext mechanism */
2517 PLy_elog(WARNING, "in function %s:",
2518 PLy_procedure_name(PLy_curr_procedure));
2523 for (i = 0; i < nargs; i++)
2525 if (!plan->args[i].out.d.typbyval &&
2526 (plan->values[i] != PointerGetDatum(NULL)))
2528 pfree(DatumGetPointer(plan->values[i]));
2529 plan->values[i] = PointerGetDatum(NULL);
2535 PLy_exception_set(PLy_exc_spi_error,
2536 "SPI_execute_plan failed: %s",
2537 SPI_result_code_string(rv));
2541 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2545 PLy_spi_execute_query(char *query, long limit)
2548 MemoryContext oldcontext;
2550 oldcontext = CurrentMemoryContext;
2553 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2557 MemoryContextSwitchTo(oldcontext);
2558 PLy_error_in_progress = CopyErrorData();
2560 if (!PyErr_Occurred())
2561 PyErr_SetString(PLy_exc_spi_error,
2562 "Unknown error in PLy_spi_execute_query");
2563 /* XXX this oughta be replaced with errcontext mechanism */
2564 PLy_elog(WARNING, "in function %s:",
2565 PLy_procedure_name(PLy_curr_procedure));
2572 PLy_exception_set(PLy_exc_spi_error,
2573 "SPI_execute failed: %s",
2574 SPI_result_code_string(rv));
2578 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2582 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2584 PLyResultObject *result;
2585 MemoryContext oldcontext;
2587 result = (PLyResultObject *) PLy_result_new();
2588 Py_DECREF(result->status);
2589 result->status = PyInt_FromLong(status);
2591 if (status > 0 && tuptable == NULL)
2593 Py_DECREF(result->nrows);
2594 result->nrows = PyInt_FromLong(rows);
2596 else if (status > 0 && tuptable != NULL)
2601 Py_DECREF(result->nrows);
2602 result->nrows = PyInt_FromLong(rows);
2603 PLy_typeinfo_init(&args);
2605 oldcontext = CurrentMemoryContext;
2610 Py_DECREF(result->rows);
2611 result->rows = PyList_New(rows);
2613 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2614 for (i = 0; i < rows; i++)
2616 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2619 PyList_SetItem(result->rows, i, row);
2621 PLy_typeinfo_dealloc(&args);
2623 SPI_freetuptable(tuptable);
2628 MemoryContextSwitchTo(oldcontext);
2629 PLy_error_in_progress = CopyErrorData();
2631 if (!PyErr_Occurred())
2632 PyErr_SetString(PLy_exc_error,
2633 "Unknown error in PLy_spi_execute_fetch_result");
2635 PLy_typeinfo_dealloc(&args);
2641 return (PyObject *) result;
2646 * language handler and interpreter initialization
2650 * _PG_init() - library load-time initialization
2652 * DO NOT make this static nor change its name!
2657 /* Be sure we do initialization only once (should be redundant now) */
2658 static bool inited = false;
2666 if (PyErr_Occurred())
2667 PLy_elog(FATAL, "untrapped error in initialization");
2668 PLy_procedure_cache = PyDict_New();
2669 if (PLy_procedure_cache == NULL)
2670 PLy_elog(ERROR, "could not create procedure cache");
2676 PLy_init_interp(void)
2680 mainmod = PyImport_AddModule("__main__");
2681 if (mainmod == NULL || PyErr_Occurred())
2682 PLy_elog(ERROR, "could not import \"__main__\" module.");
2684 PLy_interp_globals = PyModule_GetDict(mainmod);
2685 PLy_interp_safe_globals = PyDict_New();
2686 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2688 if (PLy_interp_globals == NULL || PyErr_Occurred())
2689 PLy_elog(ERROR, "could not initialize globals");
2702 * initialize plpy module
2704 if (PyType_Ready(&PLy_PlanType) < 0)
2705 elog(ERROR, "could not init PLy_PlanType");
2706 if (PyType_Ready(&PLy_ResultType) < 0)
2707 elog(ERROR, "could not init PLy_ResultType");
2709 plpy = Py_InitModule("plpy", PLy_methods);
2710 plpy_dict = PyModule_GetDict(plpy);
2712 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2714 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2715 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2716 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2717 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2718 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2719 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2722 * initialize main module, and add plpy
2724 main_mod = PyImport_AddModule("__main__");
2725 main_dict = PyModule_GetDict(main_mod);
2726 plpy_mod = PyImport_AddModule("plpy");
2727 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2728 if (PyErr_Occurred())
2729 elog(ERROR, "could not init plpy");
2732 /* the python interface to the elog function
2733 * don't confuse these with PLy_elog
2735 static PyObject *PLy_output(volatile int, PyObject *, PyObject *);
2738 PLy_debug(PyObject * self, PyObject * args)
2740 return PLy_output(DEBUG2, self, args);
2744 PLy_log(PyObject * self, PyObject * args)
2746 return PLy_output(LOG, self, args);
2750 PLy_info(PyObject * self, PyObject * args)
2752 return PLy_output(INFO, self, args);
2756 PLy_notice(PyObject * self, PyObject * args)
2758 return PLy_output(NOTICE, self, args);
2762 PLy_warning(PyObject * self, PyObject * args)
2764 return PLy_output(WARNING, self, args);
2768 PLy_error(PyObject * self, PyObject * args)
2770 return PLy_output(ERROR, self, args);
2774 PLy_fatal(PyObject * self, PyObject * args)
2776 return PLy_output(FATAL, self, args);
2781 PLy_output(volatile int level, PyObject * self, PyObject * args)
2785 MemoryContext oldcontext;
2787 so = PyObject_Str(args);
2788 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2791 sv = "Unable to parse error message in `plpy.elog'";
2794 oldcontext = CurrentMemoryContext;
2797 elog(level, "%s", sv);
2801 MemoryContextSwitchTo(oldcontext);
2802 PLy_error_in_progress = CopyErrorData();
2807 * returning NULL here causes the python interpreter to bail. when
2808 * control passes back to PLy_procedure_call, we check for PG
2809 * exceptions and re-throw the error.
2811 PyErr_SetString(PLy_exc_error, sv);
2819 * return a legal object so the interpreter will continue on its merry way
2827 * Get the name of the last procedure called by the backend (the
2828 * innermost, if a plpython procedure call calls the backend and the
2829 * backend calls another plpython procedure).
2831 * NB: this returns the SQL name, not the internal Python procedure name
2834 PLy_procedure_name(PLyProcedure * proc)
2837 return "<unknown procedure>";
2838 return proc->proname;
2841 /* output a python traceback/exception via the postgresql elog
2842 * function. not pretty.
2845 PLy_exception_set(PyObject * exc, const char *fmt,...)
2851 vsnprintf(buf, sizeof(buf), fmt, ap);
2854 PyErr_SetString(exc, buf);
2857 /* Emit a PG error or notice, together with any available info about the
2858 * current Python error. This should be used to propagate Python errors
2862 PLy_elog(int elevel, const char *fmt,...)
2869 xmsg = PLy_traceback(&xlevel);
2872 emsg = PLy_vprintf(fmt, ap);
2878 (errmsg("plpython: %s", emsg),
2879 (xmsg) ? errdetail("%s", xmsg) : 0));
2896 PLy_traceback(int *xlevel)
2908 * get the current exception
2910 PyErr_Fetch(&e, &v, &tb);
2913 * oops, no exception, return
2921 PyErr_NormalizeException(&e, &v, &tb);
2924 eob = PyObject_Str(e);
2925 if (v && ((vob = PyObject_Str(v)) != NULL))
2926 vstr = PyString_AsString(vob);
2931 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
2932 * because that function calls us, so we could end up with infinite
2933 * recursion. I'm not even sure if eob could be NULL here -- would an
2934 * Assert() be more appropriate?
2936 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
2937 xstr = PLy_printf("%s: %s", estr, vstr);
2944 * intuit an appropriate error level based on the exception type
2946 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
2948 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
2958 PLy_printf(const char *fmt,...)
2964 emsg = PLy_vprintf(fmt, ap);
2970 PLy_vprintf(const char *fmt, va_list ap)
2977 blen = strlen(fmt) * 2;
2980 buf = PLy_malloc(blen * sizeof(char));
2984 bchar = vsnprintf(buf, blen, fmt, ap);
2985 if (bchar > 0 && bchar < blen)
2993 buf = PLy_realloc(buf, blen);
2999 /* python module code */
3001 /* some dumb utility functions */
3003 PLy_malloc(size_t bytes)
3005 void *ptr = malloc(bytes);
3009 (errcode(ERRCODE_OUT_OF_MEMORY),
3010 errmsg("out of memory")));
3015 PLy_realloc(void *optr, size_t bytes)
3017 void *nptr = realloc(optr, bytes);
3021 (errcode(ERRCODE_OUT_OF_MEMORY),
3022 errmsg("out of memory")));
3027 PLy_strdup(const char *str)
3032 len = strlen(str) + 1;
3033 result = PLy_malloc(len);
3034 memcpy(result, str, len);
3039 /* define this away */