1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.88 2006/09/16 13:35:49 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,
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);
765 /* SETOF function parameters will be deleted when last row is returned */
766 PLy_function_delete_args(proc);
767 Assert(plrv != NULL);
768 Assert(!PLy_error_in_progress);
772 * Disconnect from SPI manager and then create the return values datum
773 * (if the input function does a palloc for it this must not be
774 * allocated in the SPI memory context because SPI_finish would free
777 if (SPI_finish() != SPI_OK_FINISH)
778 elog(ERROR, "SPI_finish failed");
782 bool has_error = false;
783 ReturnSetInfo *rsi = (ReturnSetInfo *)fcinfo->resultinfo;
785 if (proc->setof == NULL)
787 /* first time -- do checks and setup */
788 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
789 (rsi->allowedModes & SFRM_ValuePerCall) == 0)
792 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
793 errmsg("only value per call is allowed")));
795 rsi->returnMode = SFRM_ValuePerCall;
797 /* Make iterator out of returned object */
798 proc->setof = PyObject_GetIter(plrv);
802 if (proc->setof == NULL)
804 (errcode(ERRCODE_DATATYPE_MISMATCH),
805 errmsg("returned object can not be iterated"),
806 errdetail("SETOF must be returned as iterable object")));
809 /* Fetch next from iterator */
810 plrv = PyIter_Next(proc->setof);
812 rsi->isDone = ExprMultipleResult;
815 rsi->isDone = ExprEndResult;
816 has_error = PyErr_Occurred() != NULL;
819 if (rsi->isDone == ExprEndResult)
821 /* Iterator is exhausted or error happened */
822 Py_DECREF(proc->setof);
829 PLy_function_delete_args(proc);
833 (errcode(ERRCODE_DATA_EXCEPTION),
834 errmsg("error fetching next item from iterator")));
836 fcinfo->isnull = true;
842 * If the function is declared to return void, the Python
843 * return value must be None. For void-returning functions, we
844 * also treat a None return value as a special "void datum"
845 * rather than NULL (as is the case for non-void-returning
848 if (proc->result.out.d.typoid == VOIDOID)
852 (errcode(ERRCODE_DATATYPE_MISMATCH),
853 errmsg("invalid return value from plpython function"),
854 errdetail("Functions returning type \"void\" must return None.")));
856 fcinfo->isnull = false;
859 else if (plrv == Py_None)
861 fcinfo->isnull = true;
862 if (proc->result.is_rowtype < 1)
863 rv = InputFunctionCall(&proc->result.out.d.typfunc,
865 proc->result.out.d.typioparam,
871 else if (proc->result.is_rowtype >= 1)
873 HeapTuple tuple = NULL;
875 if (PySequence_Check(plrv))
876 /* composite type as sequence (tuple, list etc) */
877 tuple = PLySequence_ToTuple(&proc->result, plrv);
878 else if (PyMapping_Check(plrv))
879 /* composite type as mapping (currently only dict) */
880 tuple = PLyMapping_ToTuple(&proc->result, plrv);
882 /* returned as smth, must provide method __getattr__(name) */
883 tuple = PLyObject_ToTuple(&proc->result, plrv);
887 fcinfo->isnull = false;
888 rv = HeapTupleGetDatum(tuple);
892 fcinfo->isnull = true;
898 fcinfo->isnull = false;
899 plrv_so = PyObject_Str(plrv);
901 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
902 plrv_sc = PyString_AsString(plrv_so);
903 rv = InputFunctionCall(&proc->result.out.d.typfunc,
905 proc->result.out.d.typioparam,
927 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
931 PyDict_SetItemString(proc->globals, kargs, vargs);
932 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
933 proc->globals, proc->globals);
936 * If there was an error in a PG callback, propagate that no matter what
937 * Python claims about its success.
939 if (PLy_error_in_progress)
941 ErrorData *edata = PLy_error_in_progress;
943 PLy_error_in_progress = NULL;
947 if (rv == NULL || PyErr_Occurred())
950 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
957 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
959 PyObject *volatile arg = NULL;
960 PyObject *volatile args = NULL;
965 args = PyList_New(proc->nargs);
966 for (i = 0; i < proc->nargs; i++)
968 if (proc->args[i].is_rowtype > 0)
970 if (fcinfo->argnull[i])
978 HeapTupleData tmptup;
980 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
981 /* Extract rowtype info and find a tupdesc */
982 tupType = HeapTupleHeaderGetTypeId(td);
983 tupTypmod = HeapTupleHeaderGetTypMod(td);
984 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
986 /* Set up I/O funcs if not done yet */
987 if (proc->args[i].is_rowtype != 1)
988 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
990 /* Build a temporary HeapTuple control structure */
991 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
994 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
995 ReleaseTupleDesc(tupdesc);
1000 if (fcinfo->argnull[i])
1006 ct = OutputFunctionCall(&(proc->args[i].in.d.typfunc),
1008 arg = (proc->args[i].in.d.func) (ct);
1019 if (PyList_SetItem(args, i, arg) == -1 ||
1021 PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1))
1022 PLy_elog(ERROR, "problem setting up arguments for \"%s\"", proc->proname);
1040 PLy_function_delete_args(PLyProcedure *proc)
1044 if (!proc->argnames)
1047 for (i = 0; i < proc->nargs; i++)
1048 PyDict_DelItemString(proc->globals, proc->argnames[i]);
1053 * PLyProcedure functions
1056 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
1057 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
1058 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
1061 static PLyProcedure *
1062 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
1068 PLyProcedure *proc = NULL;
1071 fn_oid = fcinfo->flinfo->fn_oid;
1072 procTup = SearchSysCache(PROCOID,
1073 ObjectIdGetDatum(fn_oid),
1075 if (!HeapTupleIsValid(procTup))
1076 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1078 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
1079 if (rv >= sizeof(key) || rv < 0)
1080 elog(ERROR, "key too long");
1082 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
1087 if (!PyCObject_Check(plproc))
1088 elog(FATAL, "expected a PyCObject, didn't get one");
1090 proc = PyCObject_AsVoidPtr(plproc);
1091 if (proc->me != plproc)
1092 elog(FATAL, "proc->me != plproc");
1093 /* did we find an up-to-date cache entry? */
1094 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
1095 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
1103 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
1105 ReleaseSysCache(procTup);
1110 static PLyProcedure *
1111 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
1112 HeapTuple procTup, char *key)
1114 char procName[NAMEDATALEN + 256];
1115 Form_pg_proc procStruct;
1116 PLyProcedure *volatile proc;
1117 char *volatile procSource = NULL;
1126 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1128 if (OidIsValid(tgreloid))
1129 rv = snprintf(procName, sizeof(procName),
1130 "__plpython_procedure_%s_%u_trigger_%u",
1131 NameStr(procStruct->proname),
1132 fcinfo->flinfo->fn_oid,
1135 rv = snprintf(procName, sizeof(procName),
1136 "__plpython_procedure_%s_%u",
1137 NameStr(procStruct->proname),
1138 fcinfo->flinfo->fn_oid);
1139 if (rv >= sizeof(procName) || rv < 0)
1140 elog(ERROR, "procedure name would overrun buffer");
1142 proc = PLy_malloc(sizeof(PLyProcedure));
1143 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1144 proc->pyname = PLy_strdup(procName);
1145 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1146 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1147 /* Remember if function is STABLE/IMMUTABLE */
1149 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1150 PLy_typeinfo_init(&proc->result);
1151 for (i = 0; i < FUNC_MAX_ARGS; i++)
1152 PLy_typeinfo_init(&proc->args[i]);
1154 proc->code = proc->statics = NULL;
1155 proc->globals = proc->me = NULL;
1156 proc->is_setof = procStruct->proretset;
1158 proc->argnames = NULL;
1163 * get information required for output conversion of the return value,
1164 * but only if this isn't a trigger.
1166 if (!CALLED_AS_TRIGGER(fcinfo))
1168 HeapTuple rvTypeTup;
1169 Form_pg_type rvTypeStruct;
1171 rvTypeTup = SearchSysCache(TYPEOID,
1172 ObjectIdGetDatum(procStruct->prorettype),
1174 if (!HeapTupleIsValid(rvTypeTup))
1175 elog(ERROR, "cache lookup failed for type %u",
1176 procStruct->prorettype);
1177 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1179 /* Disallow pseudotype result, except for void */
1180 if (rvTypeStruct->typtype == 'p' &&
1181 procStruct->prorettype != VOIDOID)
1183 if (procStruct->prorettype == TRIGGEROID)
1185 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1186 errmsg("trigger functions may only be called as triggers")));
1189 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1190 errmsg("plpython functions cannot return type %s",
1191 format_type_be(procStruct->prorettype))));
1194 if (rvTypeStruct->typtype == 'c')
1196 /* Tuple: set up later, during first call to PLy_function_handler */
1197 proc->result.out.d.typoid = procStruct->prorettype;
1198 proc->result.is_rowtype = 2;
1201 PLy_output_datum_func(&proc->result, rvTypeTup);
1203 ReleaseSysCache(rvTypeTup);
1208 * input/output conversion for trigger tuples. use the result
1209 * TypeInfo variable to store the tuple conversion info.
1211 TriggerData *tdata = (TriggerData *) fcinfo->context;
1213 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1214 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1218 * now get information required for input conversion of the procedure's
1221 proc->nargs = fcinfo->nargs;
1224 argnames = SysCacheGetAttr(PROCOID, procTup, Anum_pg_proc_proargnames, &isnull);
1227 deconstruct_array(DatumGetArrayTypeP(argnames), TEXTOID, -1, false, 'i',
1228 &elems, NULL, &nelems);
1229 if (nelems != proc->nargs)
1231 "proargnames must have the same number of elements "
1232 "as the function has arguments");
1233 proc->argnames = (char **) PLy_malloc(sizeof(char *)*proc->nargs);
1236 for (i = 0; i < fcinfo->nargs; i++)
1238 HeapTuple argTypeTup;
1239 Form_pg_type argTypeStruct;
1241 argTypeTup = SearchSysCache(TYPEOID,
1242 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1244 if (!HeapTupleIsValid(argTypeTup))
1245 elog(ERROR, "cache lookup failed for type %u",
1246 procStruct->proargtypes.values[i]);
1247 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1249 /* Disallow pseudotype argument */
1250 if (argTypeStruct->typtype == 'p')
1252 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1253 errmsg("plpython functions cannot take type %s",
1254 format_type_be(procStruct->proargtypes.values[i]))));
1256 if (argTypeStruct->typtype != 'c')
1257 PLy_input_datum_func(&(proc->args[i]),
1258 procStruct->proargtypes.values[i],
1261 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1263 ReleaseSysCache(argTypeTup);
1265 /* Fetch argument name */
1267 proc->argnames[i] = PLy_strdup(DatumGetCString(DirectFunctionCall1(textout, elems[i])));
1271 * get the text of the function.
1273 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1274 Anum_pg_proc_prosrc, &isnull);
1276 elog(ERROR, "null prosrc");
1277 procSource = DatumGetCString(DirectFunctionCall1(textout,
1280 PLy_procedure_compile(proc, procSource);
1284 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1285 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1289 PLy_procedure_delete(proc);
1301 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1303 PyObject *crv = NULL;
1306 proc->globals = PyDict_Copy(PLy_interp_globals);
1309 * SD is private preserved data between calls. GD is global data
1310 * shared by all functions
1312 proc->statics = PyDict_New();
1313 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1316 * insert the function code into the interpreter
1318 msrc = PLy_procedure_munge_source(proc->pyname, src);
1319 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1322 if (crv != NULL && (!PyErr_Occurred()))
1325 char call[NAMEDATALEN + 256];
1330 * compile a call to the function
1332 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1333 if (clen < 0 || clen >= sizeof(call))
1334 elog(ERROR, "string would overflow buffer");
1335 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1336 if (proc->code != NULL && (!PyErr_Occurred()))
1342 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1346 PLy_procedure_munge_source(const char *name, const char *src)
1355 * room for function source and the def statement
1357 mlen = (strlen(src) * 2) + strlen(name) + 16;
1359 mrc = PLy_malloc(mlen);
1360 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1361 Assert(plen >= 0 && plen < mlen);
1368 if (*sp == '\r' && *(sp + 1) == '\n')
1371 if (*sp == '\n' || *sp == '\r')
1384 if (mp > (mrc + mlen))
1385 elog(FATAL, "buffer overrun in PLy_munge_source");
1391 PLy_procedure_delete(PLyProcedure * proc)
1395 Py_XDECREF(proc->code);
1396 Py_XDECREF(proc->statics);
1397 Py_XDECREF(proc->globals);
1398 Py_XDECREF(proc->me);
1400 PLy_free(proc->proname);
1402 PLy_free(proc->pyname);
1403 for (i = 0; i < proc->nargs; i++)
1405 if (proc->args[i].is_rowtype == 1)
1407 if (proc->args[i].in.r.atts)
1408 PLy_free(proc->args[i].in.r.atts);
1409 if (proc->args[i].out.r.atts)
1410 PLy_free(proc->args[i].out.r.atts);
1412 if (proc->argnames && proc->argnames[i])
1413 PLy_free(proc->argnames[i]);
1416 PLy_free(proc->argnames);
1419 /* conversion functions. remember output from python is
1420 * input to postgresql, and vis versa.
1423 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1427 if (arg->is_rowtype == 0)
1428 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1430 arg->is_rowtype = 1;
1431 arg->in.r.natts = desc->natts;
1432 arg->in.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1434 for (i = 0; i < desc->natts; i++)
1438 if (desc->attrs[i]->attisdropped)
1441 typeTup = SearchSysCache(TYPEOID,
1442 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1444 if (!HeapTupleIsValid(typeTup))
1445 elog(ERROR, "cache lookup failed for type %u",
1446 desc->attrs[i]->atttypid);
1448 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1449 desc->attrs[i]->atttypid,
1452 ReleaseSysCache(typeTup);
1457 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1461 if (arg->is_rowtype == 0)
1462 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1464 arg->is_rowtype = 1;
1465 arg->out.r.natts = desc->natts;
1466 arg->out.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1468 for (i = 0; i < desc->natts; i++)
1472 if (desc->attrs[i]->attisdropped)
1475 typeTup = SearchSysCache(TYPEOID,
1476 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1478 if (!HeapTupleIsValid(typeTup))
1479 elog(ERROR, "cache lookup failed for type %u",
1480 desc->attrs[i]->atttypid);
1482 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1484 ReleaseSysCache(typeTup);
1489 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1491 if (arg->is_rowtype > 0)
1492 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1493 arg->is_rowtype = 0;
1494 PLy_output_datum_func2(&(arg->out.d), typeTup);
1498 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1500 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1502 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1503 arg->typoid = HeapTupleGetOid(typeTup);
1504 arg->typioparam = getTypeIOParam(typeTup);
1505 arg->typbyval = typeStruct->typbyval;
1509 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1511 if (arg->is_rowtype > 0)
1512 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1513 arg->is_rowtype = 0;
1514 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1518 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1520 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1522 /* Get the type's conversion information */
1523 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1524 arg->typioparam = getTypeIOParam(typeTup);
1525 arg->typbyval = typeStruct->typbyval;
1527 /* Determine which kind of Python object we will convert to */
1531 arg->func = PLyBool_FromString;
1536 arg->func = PLyFloat_FromString;
1540 arg->func = PLyInt_FromString;
1543 arg->func = PLyLong_FromString;
1546 arg->func = PLyString_FromString;
1552 PLy_typeinfo_init(PLyTypeInfo * arg)
1554 arg->is_rowtype = -1;
1555 arg->in.r.natts = arg->out.r.natts = 0;
1556 arg->in.r.atts = NULL;
1557 arg->out.r.atts = NULL;
1561 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1563 if (arg->is_rowtype == 1)
1566 PLy_free(arg->in.r.atts);
1567 if (arg->out.r.atts)
1568 PLy_free(arg->out.r.atts);
1572 /* assumes that a bool is always returned as a 't' or 'f' */
1574 PLyBool_FromString(const char *src)
1577 return PyInt_FromLong(1);
1578 return PyInt_FromLong(0);
1582 PLyFloat_FromString(const char *src)
1588 v = strtod(src, &eptr);
1589 if (*eptr != '\0' || errno)
1591 return PyFloat_FromDouble(v);
1595 PLyInt_FromString(const char *src)
1601 v = strtol(src, &eptr, 0);
1602 if (*eptr != '\0' || errno)
1604 return PyInt_FromLong(v);
1608 PLyLong_FromString(const char *src)
1610 return PyLong_FromString((char *) src, NULL, 0);
1614 PLyString_FromString(const char *src)
1616 return PyString_FromString(src);
1620 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1622 PyObject *volatile dict;
1625 if (info->is_rowtype != 1)
1626 elog(ERROR, "PLyTypeInfo structure describes a datum");
1628 dict = PyDict_New();
1630 PLy_elog(ERROR, "could not create tuple dictionary");
1634 for (i = 0; i < info->in.r.natts; i++)
1642 if (desc->attrs[i]->attisdropped)
1645 key = NameStr(desc->attrs[i]->attname);
1646 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1648 if (is_null || info->in.r.atts[i].func == NULL)
1649 PyDict_SetItemString(dict, key, Py_None);
1652 vsrc = OutputFunctionCall(&info->in.r.atts[i].typfunc,
1656 * no exceptions allowed
1658 value = info->in.r.atts[i].func(vsrc);
1660 PyDict_SetItemString(dict, key, value);
1677 PLyMapping_ToTuple(PLyTypeInfo *info, PyObject *mapping)
1685 Assert(PyMapping_Check(mapping));
1687 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1688 if (info->is_rowtype == 2)
1689 PLy_output_tuple_funcs(info, desc);
1690 Assert(info->is_rowtype == 1);
1693 values = palloc(sizeof(Datum)*desc->natts);
1694 nulls = palloc(sizeof(char)*desc->natts);
1695 for (i = 0; i < desc->natts; ++i)
1701 key = NameStr(desc->attrs[i]->attname);
1705 value = PyMapping_GetItemString(mapping, key);
1706 if (value == Py_None)
1708 values[i] = (Datum) NULL;
1715 so = PyObject_Str(value);
1717 PLy_elog(ERROR, "can't convert mapping type");
1718 valuestr = PyString_AsString(so);
1720 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1722 , info->out.r.atts[i].typioparam
1730 (errcode(ERRCODE_UNDEFINED_COLUMN),
1731 errmsg("no mapping found with key \"%s\"", key),
1732 errhint("to return null in specific column, "
1733 "add value None to map with key named after column")));
1747 tuple = heap_formtuple(desc, values, nulls);
1748 ReleaseTupleDesc(desc);
1757 PLySequence_ToTuple(PLyTypeInfo *info, PyObject *sequence)
1765 Assert(PySequence_Check(sequence));
1768 * Check that sequence length is exactly same as PG tuple's. We actually
1769 * can ignore exceeding items or assume missing ones as null but to
1770 * avoid plpython developer's errors we are strict here
1772 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1773 if (PySequence_Length(sequence) != desc->natts)
1775 (errcode(ERRCODE_DATATYPE_MISMATCH),
1776 errmsg("returned sequence's length must be same as tuple's length")));
1778 if (info->is_rowtype == 2)
1779 PLy_output_tuple_funcs(info, desc);
1780 Assert(info->is_rowtype == 1);
1783 values = palloc(sizeof(Datum)*desc->natts);
1784 nulls = palloc(sizeof(char)*desc->natts);
1785 for (i = 0; i < desc->natts; ++i)
1793 value = PySequence_GetItem(sequence, i);
1795 if (value == Py_None)
1797 values[i] = (Datum) NULL;
1804 so = PyObject_Str(value);
1806 PLy_elog(ERROR, "can't convert sequence type");
1807 valuestr = PyString_AsString(so);
1808 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1810 , info->out.r.atts[i].typioparam
1829 tuple = heap_formtuple(desc, values, nulls);
1830 ReleaseTupleDesc(desc);
1839 PLyObject_ToTuple(PLyTypeInfo *info, PyObject *object)
1847 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1848 if (info->is_rowtype == 2)
1849 PLy_output_tuple_funcs(info, desc);
1850 Assert(info->is_rowtype == 1);
1853 values = palloc(sizeof(Datum)*desc->natts);
1854 nulls = palloc(sizeof(char)*desc->natts);
1855 for (i = 0; i < desc->natts; ++i)
1861 key = NameStr(desc->attrs[i]->attname);
1865 value = PyObject_GetAttrString(object, key);
1866 if (value == Py_None)
1868 values[i] = (Datum) NULL;
1875 so = PyObject_Str(value);
1877 PLy_elog(ERROR, "can't convert object type");
1878 valuestr = PyString_AsString(so);
1879 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1881 , info->out.r.atts[i].typioparam
1889 (errcode(ERRCODE_UNDEFINED_COLUMN),
1890 errmsg("no attribute named \"%s\"", key),
1891 errhint("to return null in specific column, "
1892 "let returned object to have attribute named "
1893 "after column with value None")));
1907 tuple = heap_formtuple(desc, values, nulls);
1908 ReleaseTupleDesc(desc);
1916 /* initialization, some python variables function declared here */
1918 /* interface to postgresql elog */
1919 static PyObject *PLy_debug(PyObject *, PyObject *);
1920 static PyObject *PLy_log(PyObject *, PyObject *);
1921 static PyObject *PLy_info(PyObject *, PyObject *);
1922 static PyObject *PLy_notice(PyObject *, PyObject *);
1923 static PyObject *PLy_warning(PyObject *, PyObject *);
1924 static PyObject *PLy_error(PyObject *, PyObject *);
1925 static PyObject *PLy_fatal(PyObject *, PyObject *);
1927 /* PLyPlanObject, PLyResultObject and SPI interface */
1928 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1929 static PyObject *PLy_plan_new(void);
1930 static void PLy_plan_dealloc(PyObject *);
1931 static PyObject *PLy_plan_getattr(PyObject *, char *);
1932 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1934 static PyObject *PLy_result_new(void);
1935 static void PLy_result_dealloc(PyObject *);
1936 static PyObject *PLy_result_getattr(PyObject *, char *);
1937 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1938 static PyObject *PLy_result_status(PyObject *, PyObject *);
1939 static int PLy_result_length(PyObject *);
1940 static PyObject *PLy_result_item(PyObject *, int);
1941 static PyObject *PLy_result_slice(PyObject *, int, int);
1942 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1943 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1946 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1947 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1948 static PyObject *PLy_spi_execute_query(char *query, long limit);
1949 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1950 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1953 static PyTypeObject PLy_PlanType = {
1954 PyObject_HEAD_INIT(NULL)
1956 "PLyPlan", /* tp_name */
1957 sizeof(PLyPlanObject), /* tp_size */
1958 0, /* tp_itemsize */
1963 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1965 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1969 0, /* tp_as_number */
1970 0, /* tp_as_sequence */
1971 0, /* tp_as_mapping */
1975 0, /* tp_getattro */
1976 0, /* tp_setattro */
1977 0, /* tp_as_buffer */
1979 PLy_plan_doc, /* tp_doc */
1982 static PyMethodDef PLy_plan_methods[] = {
1983 {"status", PLy_plan_status, METH_VARARGS, NULL},
1984 {NULL, NULL, 0, NULL}
1988 static PySequenceMethods PLy_result_as_sequence = {
1989 (inquiry) PLy_result_length, /* sq_length */
1990 (binaryfunc) 0, /* sq_concat */
1991 (intargfunc) 0, /* sq_repeat */
1992 (intargfunc) PLy_result_item, /* sq_item */
1993 (intintargfunc) PLy_result_slice, /* sq_slice */
1994 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1995 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1998 static PyTypeObject PLy_ResultType = {
1999 PyObject_HEAD_INIT(NULL)
2001 "PLyResult", /* tp_name */
2002 sizeof(PLyResultObject), /* tp_size */
2003 0, /* tp_itemsize */
2008 (destructor) PLy_result_dealloc, /* tp_dealloc */
2010 (getattrfunc) PLy_result_getattr, /* tp_getattr */
2014 0, /* tp_as_number */
2015 &PLy_result_as_sequence, /* tp_as_sequence */
2016 0, /* tp_as_mapping */
2020 0, /* tp_getattro */
2021 0, /* tp_setattro */
2022 0, /* tp_as_buffer */
2024 PLy_result_doc, /* tp_doc */
2027 static PyMethodDef PLy_result_methods[] = {
2028 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
2029 {"status", PLy_result_status, METH_VARARGS, NULL},
2030 {NULL, NULL, 0, NULL}
2033 static PyMethodDef PLy_methods[] = {
2037 {"debug", PLy_debug, METH_VARARGS, NULL},
2038 {"log", PLy_log, METH_VARARGS, NULL},
2039 {"info", PLy_info, METH_VARARGS, NULL},
2040 {"notice", PLy_notice, METH_VARARGS, NULL},
2041 {"warning", PLy_warning, METH_VARARGS, NULL},
2042 {"error", PLy_error, METH_VARARGS, NULL},
2043 {"fatal", PLy_fatal, METH_VARARGS, NULL},
2046 * create a stored plan
2048 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
2051 * execute a plan or query
2053 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
2055 {NULL, NULL, 0, NULL}
2059 /* plan object methods */
2065 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
2073 return (PyObject *) ob;
2078 PLy_plan_dealloc(PyObject * arg)
2080 PLyPlanObject *ob = (PLyPlanObject *) arg;
2083 SPI_freeplan(ob->plan);
2085 PLy_free(ob->types);
2090 for (i = 0; i < ob->nargs; i++)
2091 PLy_typeinfo_dealloc(&ob->args[i]);
2100 PLy_plan_getattr(PyObject * self, char *name)
2102 return Py_FindMethod(PLy_plan_methods, self, name);
2106 PLy_plan_status(PyObject * self, PyObject * args)
2108 if (PyArg_ParseTuple(args, ""))
2112 /* return PyInt_FromLong(self->status); */
2114 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
2120 /* result object methods */
2123 PLy_result_new(void)
2125 PLyResultObject *ob;
2127 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
2130 /* ob->tuples = NULL; */
2133 ob->status = Py_None;
2134 ob->nrows = PyInt_FromLong(-1);
2135 ob->rows = PyList_New(0);
2137 return (PyObject *) ob;
2141 PLy_result_dealloc(PyObject * arg)
2143 PLyResultObject *ob = (PLyResultObject *) arg;
2145 Py_XDECREF(ob->nrows);
2146 Py_XDECREF(ob->rows);
2147 Py_XDECREF(ob->status);
2153 PLy_result_getattr(PyObject * self, char *name)
2155 return Py_FindMethod(PLy_result_methods, self, name);
2159 PLy_result_nrows(PyObject * self, PyObject * args)
2161 PLyResultObject *ob = (PLyResultObject *) self;
2163 Py_INCREF(ob->nrows);
2168 PLy_result_status(PyObject * self, PyObject * args)
2170 PLyResultObject *ob = (PLyResultObject *) self;
2172 Py_INCREF(ob->status);
2177 PLy_result_length(PyObject * arg)
2179 PLyResultObject *ob = (PLyResultObject *) arg;
2181 return PyList_Size(ob->rows);
2185 PLy_result_item(PyObject * arg, int idx)
2188 PLyResultObject *ob = (PLyResultObject *) arg;
2190 rv = PyList_GetItem(ob->rows, idx);
2197 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
2200 PLyResultObject *ob = (PLyResultObject *) arg;
2203 rv = PyList_SetItem(ob->rows, idx, item);
2208 PLy_result_slice(PyObject * arg, int lidx, int hidx)
2211 PLyResultObject *ob = (PLyResultObject *) arg;
2213 rv = PyList_GetSlice(ob->rows, lidx, hidx);
2221 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
2224 PLyResultObject *ob = (PLyResultObject *) arg;
2226 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
2232 PLy_spi_prepare(PyObject * self, PyObject * args)
2234 PLyPlanObject *plan;
2235 PyObject *list = NULL;
2236 PyObject *volatile optr = NULL;
2239 MemoryContext oldcontext;
2241 /* Can't execute more if we have an unhandled error */
2242 if (PLy_error_in_progress)
2244 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2248 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
2250 PyErr_SetString(PLy_exc_spi_error,
2251 "Invalid arguments for plpy.prepare()");
2255 if (list && (!PySequence_Check(list)))
2257 PyErr_SetString(PLy_exc_spi_error,
2258 "Second argument in plpy.prepare() must be a sequence");
2262 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
2265 oldcontext = CurrentMemoryContext;
2273 nargs = PySequence_Length(list);
2276 plan->nargs = nargs;
2277 plan->types = PLy_malloc(sizeof(Oid) * nargs);
2278 plan->values = PLy_malloc(sizeof(Datum) * nargs);
2279 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
2282 * the other loop might throw an exception, if PLyTypeInfo
2283 * member isn't properly initialized the Py_DECREF(plan) will
2286 for (i = 0; i < nargs; i++)
2288 PLy_typeinfo_init(&plan->args[i]);
2289 plan->values[i] = PointerGetDatum(NULL);
2292 for (i = 0; i < nargs; i++)
2297 Form_pg_type typeStruct;
2299 optr = PySequence_GetItem(list, i);
2300 if (!PyString_Check(optr))
2301 elog(ERROR, "Type names must be strings.");
2302 sptr = PyString_AsString(optr);
2305 * Parse possibly-qualified type name and look it up in
2308 names = stringToQualifiedNameList(sptr,
2310 typeTup = typenameType(NULL,
2311 makeTypeNameFromNameList(names));
2313 optr = NULL; /* this is important */
2315 plan->types[i] = HeapTupleGetOid(typeTup);
2316 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2317 if (typeStruct->typtype != 'c')
2318 PLy_output_datum_func(&plan->args[i], typeTup);
2320 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
2321 ReleaseSysCache(typeTup);
2326 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2327 if (plan->plan == NULL)
2328 elog(ERROR, "SPI_prepare failed: %s",
2329 SPI_result_code_string(SPI_result));
2331 /* transfer plan from procCxt to topCxt */
2332 tmpplan = plan->plan;
2333 plan->plan = SPI_saveplan(tmpplan);
2334 SPI_freeplan(tmpplan);
2335 if (plan->plan == NULL)
2336 elog(ERROR, "SPI_saveplan failed: %s",
2337 SPI_result_code_string(SPI_result));
2341 MemoryContextSwitchTo(oldcontext);
2342 PLy_error_in_progress = CopyErrorData();
2346 if (!PyErr_Occurred())
2347 PyErr_SetString(PLy_exc_spi_error,
2348 "Unknown error in PLy_spi_prepare");
2349 /* XXX this oughta be replaced with errcontext mechanism */
2350 PLy_elog(WARNING, "in function %s:",
2351 PLy_procedure_name(PLy_curr_procedure));
2356 return (PyObject *) plan;
2359 /* execute(query="select * from foo", limit=5)
2360 * execute(plan=plan, values=(foo, bar), limit=5)
2363 PLy_spi_execute(PyObject * self, PyObject * args)
2367 PyObject *list = NULL;
2370 /* Can't execute more if we have an unhandled error */
2371 if (PLy_error_in_progress)
2373 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2377 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
2378 return PLy_spi_execute_query(query, limit);
2382 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
2383 is_PLyPlanObject(plan))
2384 return PLy_spi_execute_plan(plan, list, limit);
2386 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2391 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
2396 PLyPlanObject *plan;
2397 MemoryContext oldcontext;
2401 if (!PySequence_Check(list) || PyString_Check(list))
2403 char *msg = "plpy.execute() takes a sequence as its second argument";
2405 PyErr_SetString(PLy_exc_spi_error, msg);
2408 nargs = PySequence_Length(list);
2413 plan = (PLyPlanObject *) ob;
2415 if (nargs != plan->nargs)
2418 PyObject *so = PyObject_Str(list);
2421 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2422 PLy_procedure_name(PLy_curr_procedure));
2423 sv = PyString_AsString(so);
2424 PLy_exception_set(PLy_exc_spi_error,
2425 "Expected sequence of %d arguments, got %d. %s",
2426 plan->nargs, nargs, sv);
2432 oldcontext = CurrentMemoryContext;
2435 char *nulls = palloc(nargs * sizeof(char));
2437 for (i = 0; i < nargs; i++)
2442 elem = PySequence_GetItem(list, i);
2443 if (elem != Py_None)
2445 so = PyObject_Str(elem);
2447 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2448 PLy_procedure_name(PLy_curr_procedure));
2453 char *sv = PyString_AsString(so);
2456 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2458 plan->args[i].out.d.typioparam,
2475 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2477 plan->args[i].out.d.typioparam,
2483 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2484 PLy_curr_procedure->fn_readonly, limit);
2490 MemoryContextSwitchTo(oldcontext);
2491 PLy_error_in_progress = CopyErrorData();
2495 * cleanup plan->values array
2497 for (i = 0; i < nargs; i++)
2499 if (!plan->args[i].out.d.typbyval &&
2500 (plan->values[i] != PointerGetDatum(NULL)))
2502 pfree(DatumGetPointer(plan->values[i]));
2503 plan->values[i] = PointerGetDatum(NULL);
2507 if (!PyErr_Occurred())
2508 PyErr_SetString(PLy_exc_error,
2509 "Unknown error in PLy_spi_execute_plan");
2510 /* XXX this oughta be replaced with errcontext mechanism */
2511 PLy_elog(WARNING, "in function %s:",
2512 PLy_procedure_name(PLy_curr_procedure));
2517 for (i = 0; i < nargs; i++)
2519 if (!plan->args[i].out.d.typbyval &&
2520 (plan->values[i] != PointerGetDatum(NULL)))
2522 pfree(DatumGetPointer(plan->values[i]));
2523 plan->values[i] = PointerGetDatum(NULL);
2529 PLy_exception_set(PLy_exc_spi_error,
2530 "SPI_execute_plan failed: %s",
2531 SPI_result_code_string(rv));
2535 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2539 PLy_spi_execute_query(char *query, long limit)
2542 MemoryContext oldcontext;
2544 oldcontext = CurrentMemoryContext;
2547 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2551 MemoryContextSwitchTo(oldcontext);
2552 PLy_error_in_progress = CopyErrorData();
2554 if (!PyErr_Occurred())
2555 PyErr_SetString(PLy_exc_spi_error,
2556 "Unknown error in PLy_spi_execute_query");
2557 /* XXX this oughta be replaced with errcontext mechanism */
2558 PLy_elog(WARNING, "in function %s:",
2559 PLy_procedure_name(PLy_curr_procedure));
2566 PLy_exception_set(PLy_exc_spi_error,
2567 "SPI_execute failed: %s",
2568 SPI_result_code_string(rv));
2572 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2576 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2578 PLyResultObject *result;
2579 MemoryContext oldcontext;
2581 result = (PLyResultObject *) PLy_result_new();
2582 Py_DECREF(result->status);
2583 result->status = PyInt_FromLong(status);
2585 if (status > 0 && tuptable == NULL)
2587 Py_DECREF(result->nrows);
2588 result->nrows = PyInt_FromLong(rows);
2590 else if (status > 0 && tuptable != NULL)
2595 Py_DECREF(result->nrows);
2596 result->nrows = PyInt_FromLong(rows);
2597 PLy_typeinfo_init(&args);
2599 oldcontext = CurrentMemoryContext;
2604 Py_DECREF(result->rows);
2605 result->rows = PyList_New(rows);
2607 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2608 for (i = 0; i < rows; i++)
2610 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2613 PyList_SetItem(result->rows, i, row);
2615 PLy_typeinfo_dealloc(&args);
2617 SPI_freetuptable(tuptable);
2622 MemoryContextSwitchTo(oldcontext);
2623 PLy_error_in_progress = CopyErrorData();
2625 if (!PyErr_Occurred())
2626 PyErr_SetString(PLy_exc_error,
2627 "Unknown error in PLy_spi_execute_fetch_result");
2629 PLy_typeinfo_dealloc(&args);
2635 return (PyObject *) result;
2640 * language handler and interpreter initialization
2644 * _PG_init() - library load-time initialization
2646 * DO NOT make this static nor change its name!
2651 /* Be sure we do initialization only once (should be redundant now) */
2652 static bool inited = false;
2660 if (PyErr_Occurred())
2661 PLy_elog(FATAL, "untrapped error in initialization");
2662 PLy_procedure_cache = PyDict_New();
2663 if (PLy_procedure_cache == NULL)
2664 PLy_elog(ERROR, "could not create procedure cache");
2670 PLy_init_interp(void)
2674 mainmod = PyImport_AddModule("__main__");
2675 if (mainmod == NULL || PyErr_Occurred())
2676 PLy_elog(ERROR, "could not import \"__main__\" module.");
2678 PLy_interp_globals = PyModule_GetDict(mainmod);
2679 PLy_interp_safe_globals = PyDict_New();
2680 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2682 if (PLy_interp_globals == NULL || PyErr_Occurred())
2683 PLy_elog(ERROR, "could not initialize globals");
2696 * initialize plpy module
2698 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2699 plpy = Py_InitModule("plpy", PLy_methods);
2700 plpy_dict = PyModule_GetDict(plpy);
2702 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2704 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2705 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2706 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2707 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2708 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2709 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2712 * initialize main module, and add plpy
2714 main_mod = PyImport_AddModule("__main__");
2715 main_dict = PyModule_GetDict(main_mod);
2716 plpy_mod = PyImport_AddModule("plpy");
2717 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2718 if (PyErr_Occurred())
2719 elog(ERROR, "could not init plpy");
2722 /* the python interface to the elog function
2723 * don't confuse these with PLy_elog
2725 static PyObject *PLy_output(volatile int, PyObject *, PyObject *);
2728 PLy_debug(PyObject * self, PyObject * args)
2730 return PLy_output(DEBUG2, self, args);
2734 PLy_log(PyObject * self, PyObject * args)
2736 return PLy_output(LOG, self, args);
2740 PLy_info(PyObject * self, PyObject * args)
2742 return PLy_output(INFO, self, args);
2746 PLy_notice(PyObject * self, PyObject * args)
2748 return PLy_output(NOTICE, self, args);
2752 PLy_warning(PyObject * self, PyObject * args)
2754 return PLy_output(WARNING, self, args);
2758 PLy_error(PyObject * self, PyObject * args)
2760 return PLy_output(ERROR, self, args);
2764 PLy_fatal(PyObject * self, PyObject * args)
2766 return PLy_output(FATAL, self, args);
2771 PLy_output(volatile int level, PyObject * self, PyObject * args)
2775 MemoryContext oldcontext;
2777 so = PyObject_Str(args);
2778 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2781 sv = "Unable to parse error message in `plpy.elog'";
2784 oldcontext = CurrentMemoryContext;
2787 elog(level, "%s", sv);
2791 MemoryContextSwitchTo(oldcontext);
2792 PLy_error_in_progress = CopyErrorData();
2797 * returning NULL here causes the python interpreter to bail. when
2798 * control passes back to PLy_procedure_call, we check for PG
2799 * exceptions and re-throw the error.
2801 PyErr_SetString(PLy_exc_error, sv);
2809 * return a legal object so the interpreter will continue on its merry way
2817 * Get the name of the last procedure called by the backend (the
2818 * innermost, if a plpython procedure call calls the backend and the
2819 * backend calls another plpython procedure).
2821 * NB: this returns the SQL name, not the internal Python procedure name
2824 PLy_procedure_name(PLyProcedure * proc)
2827 return "<unknown procedure>";
2828 return proc->proname;
2831 /* output a python traceback/exception via the postgresql elog
2832 * function. not pretty.
2835 PLy_exception_set(PyObject * exc, const char *fmt,...)
2841 vsnprintf(buf, sizeof(buf), fmt, ap);
2844 PyErr_SetString(exc, buf);
2847 /* Emit a PG error or notice, together with any available info about the
2848 * current Python error. This should be used to propagate Python errors
2852 PLy_elog(int elevel, const char *fmt,...)
2859 xmsg = PLy_traceback(&xlevel);
2862 emsg = PLy_vprintf(fmt, ap);
2868 (errmsg("plpython: %s", emsg),
2869 (xmsg) ? errdetail("%s", xmsg) : 0));
2886 PLy_traceback(int *xlevel)
2898 * get the current exception
2900 PyErr_Fetch(&e, &v, &tb);
2903 * oops, no exception, return
2911 PyErr_NormalizeException(&e, &v, &tb);
2914 eob = PyObject_Str(e);
2915 if (v && ((vob = PyObject_Str(v)) != NULL))
2916 vstr = PyString_AsString(vob);
2921 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
2922 * because that function calls us, so we could end up with infinite
2923 * recursion. I'm not even sure if eob could be NULL here -- would an
2924 * Assert() be more appropriate?
2926 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
2927 xstr = PLy_printf("%s: %s", estr, vstr);
2934 * intuit an appropriate error level based on the exception type
2936 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
2938 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
2948 PLy_printf(const char *fmt,...)
2954 emsg = PLy_vprintf(fmt, ap);
2960 PLy_vprintf(const char *fmt, va_list ap)
2967 blen = strlen(fmt) * 2;
2970 buf = PLy_malloc(blen * sizeof(char));
2974 bchar = vsnprintf(buf, blen, fmt, ap);
2975 if (bchar > 0 && bchar < blen)
2983 buf = PLy_realloc(buf, blen);
2989 /* python module code */
2991 /* some dumb utility functions */
2993 PLy_malloc(size_t bytes)
2995 void *ptr = malloc(bytes);
2999 (errcode(ERRCODE_OUT_OF_MEMORY),
3000 errmsg("out of memory")));
3005 PLy_realloc(void *optr, size_t bytes)
3007 void *nptr = realloc(optr, bytes);
3011 (errcode(ERRCODE_OUT_OF_MEMORY),
3012 errmsg("out of memory")));
3017 PLy_strdup(const char *str)
3022 len = strlen(str) + 1;
3023 result = PLy_malloc(len);
3024 memcpy(result, str, len);
3029 /* define this away */