1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.85 2006/08/08 19:15:09 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 __vc_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"
34 #include "nodes/makefuncs.h"
35 #include "parser/parse_type.h"
36 #include "tcop/tcopprot.h"
37 #include "utils/builtins.h"
38 #include "utils/lsyscache.h"
39 #include "utils/memutils.h"
40 #include "utils/syscache.h"
41 #include "utils/typcache.h"
48 /* convert Postgresql Datum or tuple into a PyObject.
49 * input to Python. Tuples are converted to dictionary
53 typedef PyObject *(*PLyDatumToObFunc) (const char *);
55 typedef struct PLyDatumToOb
57 PLyDatumToObFunc func;
63 typedef struct PLyTupleToOb
69 typedef union PLyTypeInput
75 /* convert PyObject to a Postgresql Datum or tuple.
78 typedef struct PLyObToDatum
80 FmgrInfo typfunc; /* The type's input function */
81 Oid typoid; /* The OID of the type */
86 typedef struct PLyObToTuple
92 typedef union PLyTypeOutput
98 /* all we need to move Postgresql data to Python objects,
101 typedef struct PLyTypeInfo
108 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
109 * 1 rowtype 2 rowtype, but I/O functions not set up yet
114 /* cached procedure data */
115 typedef struct PLyProcedure
117 char *proname; /* SQL name of procedure */
118 char *pyname; /* Python name of procedure */
119 TransactionId fn_xmin;
122 PLyTypeInfo result; /* also used to store info for trigger tuple
124 PLyTypeInfo args[FUNC_MAX_ARGS];
126 PyObject *code; /* compiled procedure code */
127 PyObject *statics; /* data saved across calls, local scope */
128 PyObject *globals; /* data saved across calls, global scope */
129 PyObject *me; /* PyCObject containing pointer to this
135 typedef struct PLyPlanObject
138 void *plan; /* return of an SPI_saveplan */
145 typedef struct PLyResultObject
148 /* HeapTuple *tuples; */
149 PyObject *nrows; /* number of rows returned by query */
150 PyObject *rows; /* data rows, or None if no data returned */
151 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
155 /* function declarations */
157 /* Two exported functions: first is the magic telling Postgresql
158 * what function call interface it implements. Second is for
159 * initialization of the interpreter during library load.
161 Datum plpython_call_handler(PG_FUNCTION_ARGS);
164 PG_FUNCTION_INFO_V1(plpython_call_handler);
166 /* most of the remaining of the declarations, all static */
168 /* these should only be called once at the first call
169 * of plpython_call_handler. initialize the python interpreter
172 static void PLy_init_interp(void);
173 static void PLy_init_plpy(void);
175 /* call PyErr_SetString with a vprint interface */
177 PLy_exception_set(PyObject *, const char *,...)
178 __attribute__((format(printf, 2, 3)));
180 /* Get the innermost python procedure called from the backend */
181 static char *PLy_procedure_name(PLyProcedure *);
183 /* some utility functions */
184 static void PLy_elog(int, const char *,...);
185 static char *PLy_traceback(int *);
186 static char *PLy_vprintf(const char *fmt, va_list ap);
187 static char *PLy_printf(const char *fmt,...);
189 static void *PLy_malloc(size_t);
190 static void *PLy_realloc(void *, size_t);
191 static char *PLy_strdup(const char *);
192 static void PLy_free(void *);
194 /* sub handlers for functions and triggers */
195 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
196 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
198 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
199 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
201 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
202 TriggerData *, HeapTuple);
204 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
206 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
209 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
211 HeapTuple procTup, char *key);
213 static void PLy_procedure_compile(PLyProcedure *, const char *);
214 static char *PLy_procedure_munge_source(const char *, const char *);
215 static void PLy_procedure_delete(PLyProcedure *);
217 static void PLy_typeinfo_init(PLyTypeInfo *);
218 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
219 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
220 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
221 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
222 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
223 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
224 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
226 /* conversion functions */
227 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
228 static PyObject *PLyBool_FromString(const char *);
229 static PyObject *PLyFloat_FromString(const char *);
230 static PyObject *PLyInt_FromString(const char *);
231 static PyObject *PLyLong_FromString(const char *);
232 static PyObject *PLyString_FromString(const char *);
236 * Currently active plpython function
238 static PLyProcedure *PLy_curr_procedure = NULL;
241 * When a callback from Python into PG incurs an error, we temporarily store
242 * the error information here, and return NULL to the Python interpreter.
243 * Any further callback attempts immediately fail, and when the Python
244 * interpreter returns to the calling function, we re-throw the error (even if
245 * Python thinks it trapped the error and doesn't return NULL). Eventually
246 * this ought to be improved to let Python code really truly trap the error,
247 * but that's more of a change from the pre-8.0 semantics than I have time for
248 * now --- it will only be possible if the callback query is executed inside a
251 static ErrorData *PLy_error_in_progress = NULL;
253 static PyObject *PLy_interp_globals = NULL;
254 static PyObject *PLy_interp_safe_globals = NULL;
255 static PyObject *PLy_procedure_cache = NULL;
257 /* Python exceptions */
258 static PyObject *PLy_exc_error = NULL;
259 static PyObject *PLy_exc_fatal = NULL;
260 static PyObject *PLy_exc_spi_error = NULL;
262 /* some globals for the python module */
263 static char PLy_plan_doc[] = {
264 "Store a PostgreSQL plan"
267 static char PLy_result_doc[] = {
268 "Results of a PostgreSQL query"
273 * the function definitions
277 * This routine is a crock, and so is everyplace that calls it. The problem
278 * is that the cached form of plpython functions/queries is allocated permanently
279 * (mostly via malloc()) and never released until backend exit. Subsidiary
280 * data structures such as fmgr info records therefore must live forever
281 * as well. A better implementation would store all this stuff in a per-
282 * function memory context that could be reclaimed at need. In the meantime,
283 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
284 * it might allocate, and whatever the eventual function might allocate using
285 * fn_mcxt, will live forever too.
288 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
290 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
294 plpython_call_handler(PG_FUNCTION_ARGS)
297 PLyProcedure *save_curr_proc;
298 PLyProcedure *volatile proc = NULL;
300 if (SPI_connect() != SPI_OK_CONNECT)
301 elog(ERROR, "could not connect to SPI manager");
303 save_curr_proc = PLy_curr_procedure;
307 if (CALLED_AS_TRIGGER(fcinfo))
309 TriggerData *tdata = (TriggerData *) fcinfo->context;
312 proc = PLy_procedure_get(fcinfo,
313 RelationGetRelid(tdata->tg_relation));
314 PLy_curr_procedure = proc;
315 trv = PLy_trigger_handler(fcinfo, proc);
316 retval = PointerGetDatum(trv);
320 proc = PLy_procedure_get(fcinfo, InvalidOid);
321 PLy_curr_procedure = proc;
322 retval = PLy_function_handler(fcinfo, proc);
327 PLy_curr_procedure = save_curr_proc;
330 /* note: Py_DECREF needs braces around it, as of 2003/08 */
338 PLy_curr_procedure = save_curr_proc;
345 /* trigger and function sub handlers
347 * the python function is expected to return Py_None if the tuple is
348 * acceptable and unmodified. Otherwise it should return a PyString
349 * object who's value is SKIP, or MODIFY. SKIP means don't perform
350 * this action. MODIFY means the tuple has been modified, so update
351 * tuple and perform action. SKIP and MODIFY assume the trigger fires
352 * BEFORE the event and is ROW level. postgres expects the function
353 * to take no arguments and return an argument of type trigger.
356 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
359 PyObject *volatile plargs = NULL;
360 PyObject *volatile plrv = NULL;
364 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
365 plrv = PLy_procedure_call(proc, "TD", plargs);
367 Assert(plrv != NULL);
368 Assert(!PLy_error_in_progress);
371 * Disconnect from SPI manager
373 if (SPI_finish() != SPI_OK_FINISH)
374 elog(ERROR, "SPI_finish failed");
377 * return of None means we're happy with the tuple
383 if (!PyString_Check(plrv))
385 (errcode(ERRCODE_DATA_EXCEPTION),
386 errmsg("unexpected return value from trigger procedure"),
387 errdetail("Expected None or a String.")));
389 srv = PyString_AsString(plrv);
390 if (pg_strcasecmp(srv, "SKIP") == 0)
392 else if (pg_strcasecmp(srv, "MODIFY") == 0)
394 TriggerData *tdata = (TriggerData *) fcinfo->context;
396 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
397 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
398 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
400 elog(WARNING, "ignoring modified tuple in DELETE trigger");
402 else if (pg_strcasecmp(srv, "OK") != 0)
405 * accept "OK" as an alternative to None; otherwise,
409 (errcode(ERRCODE_DATA_EXCEPTION),
410 errmsg("unexpected return value from trigger procedure"),
411 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
431 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
434 PyObject *volatile plntup;
435 PyObject *volatile plkeys;
436 PyObject *volatile platt;
437 PyObject *volatile plval;
438 PyObject *volatile plstr;
444 int *volatile modattrs;
445 Datum *volatile modvalues;
446 char *volatile modnulls;
449 plntup = plkeys = platt = plval = plstr = NULL;
456 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
457 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
458 if (!PyDict_Check(plntup))
459 elog(ERROR, "TD[\"new\"] is not a dictionary object");
462 plkeys = PyDict_Keys(plntup);
463 natts = PyList_Size(plkeys);
465 modattrs = (int *) palloc(natts * sizeof(int));
466 modvalues = (Datum *) palloc(natts * sizeof(Datum));
467 modnulls = (char *) palloc(natts * sizeof(char));
469 tupdesc = tdata->tg_relation->rd_att;
471 for (i = 0; i < natts; i++)
475 platt = PyList_GetItem(plkeys, i);
476 if (!PyString_Check(platt))
477 elog(ERROR, "attribute name is not a string");
478 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
479 if (attn == SPI_ERROR_NOATTRIBUTE)
480 elog(ERROR, "invalid attribute \"%s\" in tuple",
481 PyString_AsString(platt));
484 plval = PyDict_GetItem(plntup, platt);
486 elog(FATAL, "python interpreter is probably corrupted");
492 if (tupdesc->attrs[atti]->attisdropped)
494 modvalues[i] = (Datum) 0;
497 else if (plval != Py_None)
499 plstr = PyObject_Str(plval);
501 PLy_elog(ERROR, "function \"%s\" could not modify tuple",
503 src = PyString_AsString(plstr);
506 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
508 proc->result.out.r.atts[atti].typioparam,
509 tupdesc->attrs[atti]->atttypmod);
518 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
520 proc->result.out.r.atts[atti].typioparam,
521 tupdesc->attrs[atti]->atttypmod);
529 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
530 modattrs, modvalues, modnulls);
532 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
563 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
565 TriggerData *tdata = (TriggerData *) fcinfo->context;
576 PyObject *volatile pltdata = NULL;
581 pltdata = PyDict_New();
583 PLy_elog(ERROR, "could not build arguments for trigger procedure");
585 pltname = PyString_FromString(tdata->tg_trigger->tgname);
586 PyDict_SetItemString(pltdata, "name", pltname);
589 stroid = DatumGetCString(DirectFunctionCall1(oidout,
590 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
591 pltrelid = PyString_FromString(stroid);
592 PyDict_SetItemString(pltdata, "relid", pltrelid);
596 stroid = SPI_getrelname(tdata->tg_relation);
597 plttablename = PyString_FromString(stroid);
598 PyDict_SetItemString(pltdata, "table_name", plttablename);
599 Py_DECREF(plttablename);
602 stroid = SPI_getnspname(tdata->tg_relation);
603 plttableschema = PyString_FromString(stroid);
604 PyDict_SetItemString(pltdata, "table_schema", plttableschema);
605 Py_DECREF(plttableschema);
609 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
610 pltwhen = PyString_FromString("BEFORE");
611 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
612 pltwhen = PyString_FromString("AFTER");
615 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
616 pltwhen = NULL; /* keep compiler quiet */
618 PyDict_SetItemString(pltdata, "when", pltwhen);
621 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
623 pltlevel = PyString_FromString("ROW");
624 PyDict_SetItemString(pltdata, "level", pltlevel);
627 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
629 pltevent = PyString_FromString("INSERT");
631 PyDict_SetItemString(pltdata, "old", Py_None);
632 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
633 tdata->tg_relation->rd_att);
634 PyDict_SetItemString(pltdata, "new", pytnew);
636 *rv = tdata->tg_trigtuple;
638 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
640 pltevent = PyString_FromString("DELETE");
642 PyDict_SetItemString(pltdata, "new", Py_None);
643 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
644 tdata->tg_relation->rd_att);
645 PyDict_SetItemString(pltdata, "old", pytold);
647 *rv = tdata->tg_trigtuple;
649 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
651 pltevent = PyString_FromString("UPDATE");
653 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
654 tdata->tg_relation->rd_att);
655 PyDict_SetItemString(pltdata, "new", pytnew);
657 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
658 tdata->tg_relation->rd_att);
659 PyDict_SetItemString(pltdata, "old", pytold);
661 *rv = tdata->tg_newtuple;
665 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
666 pltevent = NULL; /* keep compiler quiet */
669 PyDict_SetItemString(pltdata, "event", pltevent);
672 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
674 pltlevel = PyString_FromString("STATEMENT");
675 PyDict_SetItemString(pltdata, "level", pltlevel);
678 PyDict_SetItemString(pltdata, "old", Py_None);
679 PyDict_SetItemString(pltdata, "new", Py_None);
682 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
683 pltevent = PyString_FromString("INSERT");
684 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
685 pltevent = PyString_FromString("DELETE");
686 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
687 pltevent = PyString_FromString("UPDATE");
690 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
691 pltevent = NULL; /* keep compiler quiet */
694 PyDict_SetItemString(pltdata, "event", pltevent);
698 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
700 if (tdata->tg_trigger->tgnargs)
708 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
709 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
711 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
714 * stolen, don't Py_DECREF
716 PyList_SetItem(pltargs, i, pltarg);
724 PyDict_SetItemString(pltdata, "args", pltargs);
739 /* function handler and friends */
741 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
744 PyObject *volatile plargs = NULL;
745 PyObject *volatile plrv = NULL;
746 PyObject *volatile plrv_so = NULL;
751 plargs = PLy_function_build_args(fcinfo, proc);
752 plrv = PLy_procedure_call(proc, "args", plargs);
754 Assert(plrv != NULL);
755 Assert(!PLy_error_in_progress);
758 * Disconnect from SPI manager and then create the return values datum
759 * (if the input function does a palloc for it this must not be
760 * allocated in the SPI memory context because SPI_finish would free
763 if (SPI_finish() != SPI_OK_FINISH)
764 elog(ERROR, "SPI_finish failed");
767 * If the function is declared to return void, the Python
768 * return value must be None. For void-returning functions, we
769 * also treat a None return value as a special "void datum"
770 * rather than NULL (as is the case for non-void-returning
773 if (proc->result.out.d.typoid == VOIDOID)
777 (errcode(ERRCODE_DATATYPE_MISMATCH),
778 errmsg("invalid return value from plpython function"),
779 errdetail("Functions returning type \"void\" must return None.")));
781 fcinfo->isnull = false;
784 else if (plrv == Py_None)
786 fcinfo->isnull = true;
787 rv = InputFunctionCall(&proc->result.out.d.typfunc,
789 proc->result.out.d.typioparam,
794 fcinfo->isnull = false;
795 plrv_so = PyObject_Str(plrv);
797 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
798 plrv_sc = PyString_AsString(plrv_so);
799 rv = InputFunctionCall(&proc->result.out.d.typfunc,
801 proc->result.out.d.typioparam,
823 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
827 PyDict_SetItemString(proc->globals, kargs, vargs);
828 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
829 proc->globals, proc->globals);
832 * If there was an error in a PG callback, propagate that no matter what
833 * Python claims about its success.
835 if (PLy_error_in_progress)
837 ErrorData *edata = PLy_error_in_progress;
839 PLy_error_in_progress = NULL;
843 if (rv == NULL || PyErr_Occurred())
846 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
853 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
855 PyObject *volatile arg = NULL;
856 PyObject *volatile args = NULL;
861 args = PyList_New(proc->nargs);
862 for (i = 0; i < proc->nargs; i++)
864 if (proc->args[i].is_rowtype > 0)
866 if (fcinfo->argnull[i])
874 HeapTupleData tmptup;
876 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
877 /* Extract rowtype info and find a tupdesc */
878 tupType = HeapTupleHeaderGetTypeId(td);
879 tupTypmod = HeapTupleHeaderGetTypMod(td);
880 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
882 /* Set up I/O funcs if not done yet */
883 if (proc->args[i].is_rowtype != 1)
884 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
886 /* Build a temporary HeapTuple control structure */
887 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
890 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
891 ReleaseTupleDesc(tupdesc);
896 if (fcinfo->argnull[i])
902 ct = OutputFunctionCall(&(proc->args[i].in.d.typfunc),
904 arg = (proc->args[i].in.d.func) (ct);
916 * FIXME -- error check this
918 PyList_SetItem(args, i, arg);
936 * PLyProcedure functions
939 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
940 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
941 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
944 static PLyProcedure *
945 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
951 PLyProcedure *proc = NULL;
954 fn_oid = fcinfo->flinfo->fn_oid;
955 procTup = SearchSysCache(PROCOID,
956 ObjectIdGetDatum(fn_oid),
958 if (!HeapTupleIsValid(procTup))
959 elog(ERROR, "cache lookup failed for function %u", fn_oid);
961 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
962 if (rv >= sizeof(key) || rv < 0)
963 elog(ERROR, "key too long");
965 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
970 if (!PyCObject_Check(plproc))
971 elog(FATAL, "expected a PyCObject, didn't get one");
973 proc = PyCObject_AsVoidPtr(plproc);
974 if (proc->me != plproc)
975 elog(FATAL, "proc->me != plproc");
976 /* did we find an up-to-date cache entry? */
977 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
978 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
986 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
988 ReleaseSysCache(procTup);
993 static PLyProcedure *
994 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
995 HeapTuple procTup, char *key)
997 char procName[NAMEDATALEN + 256];
998 Form_pg_proc procStruct;
999 PLyProcedure *volatile proc;
1000 char *volatile procSource = NULL;
1006 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1008 if (OidIsValid(tgreloid))
1009 rv = snprintf(procName, sizeof(procName),
1010 "__plpython_procedure_%s_%u_trigger_%u",
1011 NameStr(procStruct->proname),
1012 fcinfo->flinfo->fn_oid,
1015 rv = snprintf(procName, sizeof(procName),
1016 "__plpython_procedure_%s_%u",
1017 NameStr(procStruct->proname),
1018 fcinfo->flinfo->fn_oid);
1019 if (rv >= sizeof(procName) || rv < 0)
1020 elog(ERROR, "procedure name would overrun buffer");
1022 proc = PLy_malloc(sizeof(PLyProcedure));
1023 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1024 proc->pyname = PLy_strdup(procName);
1025 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1026 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1027 /* Remember if function is STABLE/IMMUTABLE */
1029 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1030 PLy_typeinfo_init(&proc->result);
1031 for (i = 0; i < FUNC_MAX_ARGS; i++)
1032 PLy_typeinfo_init(&proc->args[i]);
1034 proc->code = proc->statics = NULL;
1035 proc->globals = proc->me = NULL;
1040 * get information required for output conversion of the return value,
1041 * but only if this isn't a trigger.
1043 if (!CALLED_AS_TRIGGER(fcinfo))
1045 HeapTuple rvTypeTup;
1046 Form_pg_type rvTypeStruct;
1048 rvTypeTup = SearchSysCache(TYPEOID,
1049 ObjectIdGetDatum(procStruct->prorettype),
1051 if (!HeapTupleIsValid(rvTypeTup))
1052 elog(ERROR, "cache lookup failed for type %u",
1053 procStruct->prorettype);
1054 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1056 /* Disallow pseudotype result, except for void */
1057 if (rvTypeStruct->typtype == 'p' &&
1058 procStruct->prorettype != VOIDOID)
1060 if (procStruct->prorettype == TRIGGEROID)
1062 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1063 errmsg("trigger functions may only be called as triggers")));
1066 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1067 errmsg("plpython functions cannot return type %s",
1068 format_type_be(procStruct->prorettype))));
1071 if (rvTypeStruct->typtype == 'c')
1073 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1074 errmsg("plpython functions cannot return tuples yet")));
1076 PLy_output_datum_func(&proc->result, rvTypeTup);
1078 ReleaseSysCache(rvTypeTup);
1083 * input/output conversion for trigger tuples. use the result
1084 * TypeInfo variable to store the tuple conversion info.
1086 TriggerData *tdata = (TriggerData *) fcinfo->context;
1088 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1089 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1093 * now get information required for input conversion of the procedure's
1096 proc->nargs = fcinfo->nargs;
1097 for (i = 0; i < fcinfo->nargs; i++)
1099 HeapTuple argTypeTup;
1100 Form_pg_type argTypeStruct;
1102 argTypeTup = SearchSysCache(TYPEOID,
1103 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1105 if (!HeapTupleIsValid(argTypeTup))
1106 elog(ERROR, "cache lookup failed for type %u",
1107 procStruct->proargtypes.values[i]);
1108 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1110 /* Disallow pseudotype argument */
1111 if (argTypeStruct->typtype == 'p')
1113 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1114 errmsg("plpython functions cannot take type %s",
1115 format_type_be(procStruct->proargtypes.values[i]))));
1117 if (argTypeStruct->typtype != 'c')
1118 PLy_input_datum_func(&(proc->args[i]),
1119 procStruct->proargtypes.values[i],
1122 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1124 ReleaseSysCache(argTypeTup);
1129 * get the text of the function.
1131 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1132 Anum_pg_proc_prosrc, &isnull);
1134 elog(ERROR, "null prosrc");
1135 procSource = DatumGetCString(DirectFunctionCall1(textout,
1138 PLy_procedure_compile(proc, procSource);
1142 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1143 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1147 PLy_procedure_delete(proc);
1159 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1161 PyObject *crv = NULL;
1164 proc->globals = PyDict_Copy(PLy_interp_globals);
1167 * SD is private preserved data between calls. GD is global data
1168 * shared by all functions
1170 proc->statics = PyDict_New();
1171 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1174 * insert the function code into the interpreter
1176 msrc = PLy_procedure_munge_source(proc->pyname, src);
1177 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1180 if (crv != NULL && (!PyErr_Occurred()))
1183 char call[NAMEDATALEN + 256];
1188 * compile a call to the function
1190 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1191 if (clen < 0 || clen >= sizeof(call))
1192 elog(ERROR, "string would overflow buffer");
1193 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1194 if (proc->code != NULL && (!PyErr_Occurred()))
1200 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1204 PLy_procedure_munge_source(const char *name, const char *src)
1213 * room for function source and the def statement
1215 mlen = (strlen(src) * 2) + strlen(name) + 16;
1217 mrc = PLy_malloc(mlen);
1218 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1219 Assert(plen >= 0 && plen < mlen);
1226 if (*sp == '\r' && *(sp + 1) == '\n')
1229 if (*sp == '\n' || *sp == '\r')
1242 if (mp > (mrc + mlen))
1243 elog(FATAL, "buffer overrun in PLy_munge_source");
1249 PLy_procedure_delete(PLyProcedure * proc)
1253 Py_XDECREF(proc->code);
1254 Py_XDECREF(proc->statics);
1255 Py_XDECREF(proc->globals);
1256 Py_XDECREF(proc->me);
1258 PLy_free(proc->proname);
1260 PLy_free(proc->pyname);
1261 for (i = 0; i < proc->nargs; i++)
1262 if (proc->args[i].is_rowtype == 1)
1264 if (proc->args[i].in.r.atts)
1265 PLy_free(proc->args[i].in.r.atts);
1266 if (proc->args[i].out.r.atts)
1267 PLy_free(proc->args[i].out.r.atts);
1271 /* conversion functions. remember output from python is
1272 * input to postgresql, and vis versa.
1275 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1279 if (arg->is_rowtype == 0)
1280 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1282 arg->is_rowtype = 1;
1283 arg->in.r.natts = desc->natts;
1284 arg->in.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1286 for (i = 0; i < desc->natts; i++)
1290 if (desc->attrs[i]->attisdropped)
1293 typeTup = SearchSysCache(TYPEOID,
1294 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1296 if (!HeapTupleIsValid(typeTup))
1297 elog(ERROR, "cache lookup failed for type %u",
1298 desc->attrs[i]->atttypid);
1300 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1301 desc->attrs[i]->atttypid,
1304 ReleaseSysCache(typeTup);
1309 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1313 if (arg->is_rowtype == 0)
1314 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1316 arg->is_rowtype = 1;
1317 arg->out.r.natts = desc->natts;
1318 arg->out.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1320 for (i = 0; i < desc->natts; i++)
1324 if (desc->attrs[i]->attisdropped)
1327 typeTup = SearchSysCache(TYPEOID,
1328 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1330 if (!HeapTupleIsValid(typeTup))
1331 elog(ERROR, "cache lookup failed for type %u",
1332 desc->attrs[i]->atttypid);
1334 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1336 ReleaseSysCache(typeTup);
1341 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1343 if (arg->is_rowtype > 0)
1344 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1345 arg->is_rowtype = 0;
1346 PLy_output_datum_func2(&(arg->out.d), typeTup);
1350 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1352 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1354 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1355 arg->typoid = HeapTupleGetOid(typeTup);
1356 arg->typioparam = getTypeIOParam(typeTup);
1357 arg->typbyval = typeStruct->typbyval;
1361 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1363 if (arg->is_rowtype > 0)
1364 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1365 arg->is_rowtype = 0;
1366 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1370 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1372 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1374 /* Get the type's conversion information */
1375 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1376 arg->typioparam = getTypeIOParam(typeTup);
1377 arg->typbyval = typeStruct->typbyval;
1379 /* Determine which kind of Python object we will convert to */
1383 arg->func = PLyBool_FromString;
1388 arg->func = PLyFloat_FromString;
1392 arg->func = PLyInt_FromString;
1395 arg->func = PLyLong_FromString;
1398 arg->func = PLyString_FromString;
1404 PLy_typeinfo_init(PLyTypeInfo * arg)
1406 arg->is_rowtype = -1;
1407 arg->in.r.natts = arg->out.r.natts = 0;
1408 arg->in.r.atts = NULL;
1409 arg->out.r.atts = NULL;
1413 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1415 if (arg->is_rowtype == 1)
1418 PLy_free(arg->in.r.atts);
1419 if (arg->out.r.atts)
1420 PLy_free(arg->out.r.atts);
1424 /* assumes that a bool is always returned as a 't' or 'f' */
1426 PLyBool_FromString(const char *src)
1429 return PyInt_FromLong(1);
1430 return PyInt_FromLong(0);
1434 PLyFloat_FromString(const char *src)
1440 v = strtod(src, &eptr);
1441 if (*eptr != '\0' || errno)
1443 return PyFloat_FromDouble(v);
1447 PLyInt_FromString(const char *src)
1453 v = strtol(src, &eptr, 0);
1454 if (*eptr != '\0' || errno)
1456 return PyInt_FromLong(v);
1460 PLyLong_FromString(const char *src)
1462 return PyLong_FromString((char *) src, NULL, 0);
1466 PLyString_FromString(const char *src)
1468 return PyString_FromString(src);
1472 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1474 PyObject *volatile dict;
1477 if (info->is_rowtype != 1)
1478 elog(ERROR, "PLyTypeInfo structure describes a datum");
1480 dict = PyDict_New();
1482 PLy_elog(ERROR, "could not create tuple dictionary");
1486 for (i = 0; i < info->in.r.natts; i++)
1494 if (desc->attrs[i]->attisdropped)
1497 key = NameStr(desc->attrs[i]->attname);
1498 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1500 if (is_null || info->in.r.atts[i].func == NULL)
1501 PyDict_SetItemString(dict, key, Py_None);
1504 vsrc = OutputFunctionCall(&info->in.r.atts[i].typfunc,
1508 * no exceptions allowed
1510 value = info->in.r.atts[i].func(vsrc);
1512 PyDict_SetItemString(dict, key, value);
1527 /* initialization, some python variables function declared here */
1529 /* interface to postgresql elog */
1530 static PyObject *PLy_debug(PyObject *, PyObject *);
1531 static PyObject *PLy_log(PyObject *, PyObject *);
1532 static PyObject *PLy_info(PyObject *, PyObject *);
1533 static PyObject *PLy_notice(PyObject *, PyObject *);
1534 static PyObject *PLy_warning(PyObject *, PyObject *);
1535 static PyObject *PLy_error(PyObject *, PyObject *);
1536 static PyObject *PLy_fatal(PyObject *, PyObject *);
1538 /* PLyPlanObject, PLyResultObject and SPI interface */
1539 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1540 static PyObject *PLy_plan_new(void);
1541 static void PLy_plan_dealloc(PyObject *);
1542 static PyObject *PLy_plan_getattr(PyObject *, char *);
1543 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1545 static PyObject *PLy_result_new(void);
1546 static void PLy_result_dealloc(PyObject *);
1547 static PyObject *PLy_result_getattr(PyObject *, char *);
1548 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1549 static PyObject *PLy_result_status(PyObject *, PyObject *);
1550 static int PLy_result_length(PyObject *);
1551 static PyObject *PLy_result_item(PyObject *, int);
1552 static PyObject *PLy_result_slice(PyObject *, int, int);
1553 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1554 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1557 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1558 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1559 static PyObject *PLy_spi_execute_query(char *query, long limit);
1560 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1561 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1564 static PyTypeObject PLy_PlanType = {
1565 PyObject_HEAD_INIT(NULL)
1567 "PLyPlan", /* tp_name */
1568 sizeof(PLyPlanObject), /* tp_size */
1569 0, /* tp_itemsize */
1574 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1576 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1580 0, /* tp_as_number */
1581 0, /* tp_as_sequence */
1582 0, /* tp_as_mapping */
1586 0, /* tp_getattro */
1587 0, /* tp_setattro */
1588 0, /* tp_as_buffer */
1590 PLy_plan_doc, /* tp_doc */
1593 static PyMethodDef PLy_plan_methods[] = {
1594 {"status", PLy_plan_status, METH_VARARGS, NULL},
1595 {NULL, NULL, 0, NULL}
1599 static PySequenceMethods PLy_result_as_sequence = {
1600 (inquiry) PLy_result_length, /* sq_length */
1601 (binaryfunc) 0, /* sq_concat */
1602 (intargfunc) 0, /* sq_repeat */
1603 (intargfunc) PLy_result_item, /* sq_item */
1604 (intintargfunc) PLy_result_slice, /* sq_slice */
1605 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1606 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1609 static PyTypeObject PLy_ResultType = {
1610 PyObject_HEAD_INIT(NULL)
1612 "PLyResult", /* tp_name */
1613 sizeof(PLyResultObject), /* tp_size */
1614 0, /* tp_itemsize */
1619 (destructor) PLy_result_dealloc, /* tp_dealloc */
1621 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1625 0, /* tp_as_number */
1626 &PLy_result_as_sequence, /* tp_as_sequence */
1627 0, /* tp_as_mapping */
1631 0, /* tp_getattro */
1632 0, /* tp_setattro */
1633 0, /* tp_as_buffer */
1635 PLy_result_doc, /* tp_doc */
1638 static PyMethodDef PLy_result_methods[] = {
1639 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
1640 {"status", PLy_result_status, METH_VARARGS, NULL},
1641 {NULL, NULL, 0, NULL}
1644 static PyMethodDef PLy_methods[] = {
1648 {"debug", PLy_debug, METH_VARARGS, NULL},
1649 {"log", PLy_log, METH_VARARGS, NULL},
1650 {"info", PLy_info, METH_VARARGS, NULL},
1651 {"notice", PLy_notice, METH_VARARGS, NULL},
1652 {"warning", PLy_warning, METH_VARARGS, NULL},
1653 {"error", PLy_error, METH_VARARGS, NULL},
1654 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1657 * create a stored plan
1659 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1662 * execute a plan or query
1664 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1666 {NULL, NULL, 0, NULL}
1670 /* plan object methods */
1676 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1684 return (PyObject *) ob;
1689 PLy_plan_dealloc(PyObject * arg)
1691 PLyPlanObject *ob = (PLyPlanObject *) arg;
1694 SPI_freeplan(ob->plan);
1696 PLy_free(ob->types);
1701 for (i = 0; i < ob->nargs; i++)
1702 PLy_typeinfo_dealloc(&ob->args[i]);
1711 PLy_plan_getattr(PyObject * self, char *name)
1713 return Py_FindMethod(PLy_plan_methods, self, name);
1717 PLy_plan_status(PyObject * self, PyObject * args)
1719 if (PyArg_ParseTuple(args, ""))
1723 /* return PyInt_FromLong(self->status); */
1725 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1731 /* result object methods */
1734 PLy_result_new(void)
1736 PLyResultObject *ob;
1738 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1741 /* ob->tuples = NULL; */
1744 ob->status = Py_None;
1745 ob->nrows = PyInt_FromLong(-1);
1746 ob->rows = PyList_New(0);
1748 return (PyObject *) ob;
1752 PLy_result_dealloc(PyObject * arg)
1754 PLyResultObject *ob = (PLyResultObject *) arg;
1756 Py_XDECREF(ob->nrows);
1757 Py_XDECREF(ob->rows);
1758 Py_XDECREF(ob->status);
1764 PLy_result_getattr(PyObject * self, char *name)
1766 return Py_FindMethod(PLy_result_methods, self, name);
1770 PLy_result_nrows(PyObject * self, PyObject * args)
1772 PLyResultObject *ob = (PLyResultObject *) self;
1774 Py_INCREF(ob->nrows);
1779 PLy_result_status(PyObject * self, PyObject * args)
1781 PLyResultObject *ob = (PLyResultObject *) self;
1783 Py_INCREF(ob->status);
1788 PLy_result_length(PyObject * arg)
1790 PLyResultObject *ob = (PLyResultObject *) arg;
1792 return PyList_Size(ob->rows);
1796 PLy_result_item(PyObject * arg, int idx)
1799 PLyResultObject *ob = (PLyResultObject *) arg;
1801 rv = PyList_GetItem(ob->rows, idx);
1808 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1811 PLyResultObject *ob = (PLyResultObject *) arg;
1814 rv = PyList_SetItem(ob->rows, idx, item);
1819 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1822 PLyResultObject *ob = (PLyResultObject *) arg;
1824 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1832 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1835 PLyResultObject *ob = (PLyResultObject *) arg;
1837 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1843 PLy_spi_prepare(PyObject * self, PyObject * args)
1845 PLyPlanObject *plan;
1846 PyObject *list = NULL;
1847 PyObject *volatile optr = NULL;
1850 MemoryContext oldcontext;
1852 /* Can't execute more if we have an unhandled error */
1853 if (PLy_error_in_progress)
1855 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1859 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1861 PyErr_SetString(PLy_exc_spi_error,
1862 "Invalid arguments for plpy.prepare()");
1866 if (list && (!PySequence_Check(list)))
1868 PyErr_SetString(PLy_exc_spi_error,
1869 "Second argument in plpy.prepare() must be a sequence");
1873 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1876 oldcontext = CurrentMemoryContext;
1884 nargs = PySequence_Length(list);
1887 plan->nargs = nargs;
1888 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1889 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1890 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1893 * the other loop might throw an exception, if PLyTypeInfo
1894 * member isn't properly initialized the Py_DECREF(plan) will
1897 for (i = 0; i < nargs; i++)
1899 PLy_typeinfo_init(&plan->args[i]);
1900 plan->values[i] = PointerGetDatum(NULL);
1903 for (i = 0; i < nargs; i++)
1908 Form_pg_type typeStruct;
1910 optr = PySequence_GetItem(list, i);
1911 if (!PyString_Check(optr))
1912 elog(ERROR, "Type names must be strings.");
1913 sptr = PyString_AsString(optr);
1916 * Parse possibly-qualified type name and look it up in
1919 names = stringToQualifiedNameList(sptr,
1921 typeTup = typenameType(NULL,
1922 makeTypeNameFromNameList(names));
1924 optr = NULL; /* this is important */
1926 plan->types[i] = HeapTupleGetOid(typeTup);
1927 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1928 if (typeStruct->typtype != 'c')
1929 PLy_output_datum_func(&plan->args[i], typeTup);
1931 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
1932 ReleaseSysCache(typeTup);
1937 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1938 if (plan->plan == NULL)
1939 elog(ERROR, "SPI_prepare failed: %s",
1940 SPI_result_code_string(SPI_result));
1942 /* transfer plan from procCxt to topCxt */
1943 tmpplan = plan->plan;
1944 plan->plan = SPI_saveplan(tmpplan);
1945 SPI_freeplan(tmpplan);
1946 if (plan->plan == NULL)
1947 elog(ERROR, "SPI_saveplan failed: %s",
1948 SPI_result_code_string(SPI_result));
1952 MemoryContextSwitchTo(oldcontext);
1953 PLy_error_in_progress = CopyErrorData();
1957 if (!PyErr_Occurred())
1958 PyErr_SetString(PLy_exc_spi_error,
1959 "Unknown error in PLy_spi_prepare");
1960 /* XXX this oughta be replaced with errcontext mechanism */
1961 PLy_elog(WARNING, "in function %s:",
1962 PLy_procedure_name(PLy_curr_procedure));
1967 return (PyObject *) plan;
1970 /* execute(query="select * from foo", limit=5)
1971 * execute(plan=plan, values=(foo, bar), limit=5)
1974 PLy_spi_execute(PyObject * self, PyObject * args)
1978 PyObject *list = NULL;
1981 /* Can't execute more if we have an unhandled error */
1982 if (PLy_error_in_progress)
1984 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1988 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
1989 return PLy_spi_execute_query(query, limit);
1993 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
1994 is_PLyPlanObject(plan))
1995 return PLy_spi_execute_plan(plan, list, limit);
1997 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2002 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
2007 PLyPlanObject *plan;
2008 MemoryContext oldcontext;
2012 if (!PySequence_Check(list) || PyString_Check(list))
2014 char *msg = "plpy.execute() takes a sequence as its second argument";
2016 PyErr_SetString(PLy_exc_spi_error, msg);
2019 nargs = PySequence_Length(list);
2024 plan = (PLyPlanObject *) ob;
2026 if (nargs != plan->nargs)
2029 PyObject *so = PyObject_Str(list);
2032 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2033 PLy_procedure_name(PLy_curr_procedure));
2034 sv = PyString_AsString(so);
2035 PLy_exception_set(PLy_exc_spi_error,
2036 "Expected sequence of %d arguments, got %d. %s",
2037 plan->nargs, nargs, sv);
2043 oldcontext = CurrentMemoryContext;
2046 char *nulls = palloc(nargs * sizeof(char));
2048 for (i = 0; i < nargs; i++)
2053 elem = PySequence_GetItem(list, i);
2054 if (elem != Py_None)
2056 so = PyObject_Str(elem);
2058 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2059 PLy_procedure_name(PLy_curr_procedure));
2064 char *sv = PyString_AsString(so);
2067 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2069 plan->args[i].out.d.typioparam,
2086 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2088 plan->args[i].out.d.typioparam,
2094 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2095 PLy_curr_procedure->fn_readonly, limit);
2101 MemoryContextSwitchTo(oldcontext);
2102 PLy_error_in_progress = CopyErrorData();
2106 * cleanup plan->values array
2108 for (i = 0; i < nargs; i++)
2110 if (!plan->args[i].out.d.typbyval &&
2111 (plan->values[i] != PointerGetDatum(NULL)))
2113 pfree(DatumGetPointer(plan->values[i]));
2114 plan->values[i] = PointerGetDatum(NULL);
2118 if (!PyErr_Occurred())
2119 PyErr_SetString(PLy_exc_error,
2120 "Unknown error in PLy_spi_execute_plan");
2121 /* XXX this oughta be replaced with errcontext mechanism */
2122 PLy_elog(WARNING, "in function %s:",
2123 PLy_procedure_name(PLy_curr_procedure));
2128 for (i = 0; i < nargs; i++)
2130 if (!plan->args[i].out.d.typbyval &&
2131 (plan->values[i] != PointerGetDatum(NULL)))
2133 pfree(DatumGetPointer(plan->values[i]));
2134 plan->values[i] = PointerGetDatum(NULL);
2140 PLy_exception_set(PLy_exc_spi_error,
2141 "SPI_execute_plan failed: %s",
2142 SPI_result_code_string(rv));
2146 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2150 PLy_spi_execute_query(char *query, long limit)
2153 MemoryContext oldcontext;
2155 oldcontext = CurrentMemoryContext;
2158 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2162 MemoryContextSwitchTo(oldcontext);
2163 PLy_error_in_progress = CopyErrorData();
2165 if (!PyErr_Occurred())
2166 PyErr_SetString(PLy_exc_spi_error,
2167 "Unknown error in PLy_spi_execute_query");
2168 /* XXX this oughta be replaced with errcontext mechanism */
2169 PLy_elog(WARNING, "in function %s:",
2170 PLy_procedure_name(PLy_curr_procedure));
2177 PLy_exception_set(PLy_exc_spi_error,
2178 "SPI_execute failed: %s",
2179 SPI_result_code_string(rv));
2183 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2187 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2189 PLyResultObject *result;
2190 MemoryContext oldcontext;
2192 result = (PLyResultObject *) PLy_result_new();
2193 Py_DECREF(result->status);
2194 result->status = PyInt_FromLong(status);
2196 if (status == SPI_OK_UTILITY)
2198 Py_DECREF(result->nrows);
2199 result->nrows = PyInt_FromLong(0);
2201 else if (status != SPI_OK_SELECT)
2203 Py_DECREF(result->nrows);
2204 result->nrows = PyInt_FromLong(rows);
2211 PLy_typeinfo_init(&args);
2212 Py_DECREF(result->nrows);
2213 result->nrows = PyInt_FromLong(rows);
2215 oldcontext = CurrentMemoryContext;
2220 Py_DECREF(result->rows);
2221 result->rows = PyList_New(rows);
2223 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2224 for (i = 0; i < rows; i++)
2226 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2229 PyList_SetItem(result->rows, i, row);
2231 PLy_typeinfo_dealloc(&args);
2233 SPI_freetuptable(tuptable);
2238 MemoryContextSwitchTo(oldcontext);
2239 PLy_error_in_progress = CopyErrorData();
2241 if (!PyErr_Occurred())
2242 PyErr_SetString(PLy_exc_error,
2243 "Unknown error in PLy_spi_execute_fetch_result");
2245 PLy_typeinfo_dealloc(&args);
2251 return (PyObject *) result;
2256 * language handler and interpreter initialization
2260 * _PG_init() - library load-time initialization
2262 * DO NOT make this static nor change its name!
2267 /* Be sure we do initialization only once (should be redundant now) */
2268 static bool inited = false;
2276 if (PyErr_Occurred())
2277 PLy_elog(FATAL, "untrapped error in initialization");
2278 PLy_procedure_cache = PyDict_New();
2279 if (PLy_procedure_cache == NULL)
2280 PLy_elog(ERROR, "could not create procedure cache");
2286 PLy_init_interp(void)
2290 mainmod = PyImport_AddModule("__main__");
2291 if (mainmod == NULL || PyErr_Occurred())
2292 PLy_elog(ERROR, "could not import \"__main__\" module.");
2294 PLy_interp_globals = PyModule_GetDict(mainmod);
2295 PLy_interp_safe_globals = PyDict_New();
2296 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2298 if (PLy_interp_globals == NULL || PyErr_Occurred())
2299 PLy_elog(ERROR, "could not initialize globals");
2312 * initialize plpy module
2314 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2315 plpy = Py_InitModule("plpy", PLy_methods);
2316 plpy_dict = PyModule_GetDict(plpy);
2318 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2320 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2321 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2322 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2323 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2324 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2325 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2328 * initialize main module, and add plpy
2330 main_mod = PyImport_AddModule("__main__");
2331 main_dict = PyModule_GetDict(main_mod);
2332 plpy_mod = PyImport_AddModule("plpy");
2333 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2334 if (PyErr_Occurred())
2335 elog(ERROR, "could not init plpy");
2338 /* the python interface to the elog function
2339 * don't confuse these with PLy_elog
2341 static PyObject *PLy_output(volatile int, PyObject *, PyObject *);
2344 PLy_debug(PyObject * self, PyObject * args)
2346 return PLy_output(DEBUG2, self, args);
2350 PLy_log(PyObject * self, PyObject * args)
2352 return PLy_output(LOG, self, args);
2356 PLy_info(PyObject * self, PyObject * args)
2358 return PLy_output(INFO, self, args);
2362 PLy_notice(PyObject * self, PyObject * args)
2364 return PLy_output(NOTICE, self, args);
2368 PLy_warning(PyObject * self, PyObject * args)
2370 return PLy_output(WARNING, self, args);
2374 PLy_error(PyObject * self, PyObject * args)
2376 return PLy_output(ERROR, self, args);
2380 PLy_fatal(PyObject * self, PyObject * args)
2382 return PLy_output(FATAL, self, args);
2387 PLy_output(volatile int level, PyObject * self, PyObject * args)
2391 MemoryContext oldcontext;
2393 so = PyObject_Str(args);
2394 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2397 sv = "Unable to parse error message in `plpy.elog'";
2400 oldcontext = CurrentMemoryContext;
2403 elog(level, "%s", sv);
2407 MemoryContextSwitchTo(oldcontext);
2408 PLy_error_in_progress = CopyErrorData();
2413 * returning NULL here causes the python interpreter to bail. when
2414 * control passes back to PLy_procedure_call, we check for PG
2415 * exceptions and re-throw the error.
2417 PyErr_SetString(PLy_exc_error, sv);
2425 * return a legal object so the interpreter will continue on its merry way
2433 * Get the name of the last procedure called by the backend (the
2434 * innermost, if a plpython procedure call calls the backend and the
2435 * backend calls another plpython procedure).
2437 * NB: this returns the SQL name, not the internal Python procedure name
2440 PLy_procedure_name(PLyProcedure * proc)
2443 return "<unknown procedure>";
2444 return proc->proname;
2447 /* output a python traceback/exception via the postgresql elog
2448 * function. not pretty.
2451 PLy_exception_set(PyObject * exc, const char *fmt,...)
2457 vsnprintf(buf, sizeof(buf), fmt, ap);
2460 PyErr_SetString(exc, buf);
2463 /* Emit a PG error or notice, together with any available info about the
2464 * current Python error. This should be used to propagate Python errors
2468 PLy_elog(int elevel, const char *fmt,...)
2475 xmsg = PLy_traceback(&xlevel);
2478 emsg = PLy_vprintf(fmt, ap);
2484 (errmsg("plpython: %s", emsg),
2485 (xmsg) ? errdetail("%s", xmsg) : 0));
2502 PLy_traceback(int *xlevel)
2514 * get the current exception
2516 PyErr_Fetch(&e, &v, &tb);
2519 * oops, no exception, return
2527 PyErr_NormalizeException(&e, &v, &tb);
2530 eob = PyObject_Str(e);
2531 if (v && ((vob = PyObject_Str(v)) != NULL))
2532 vstr = PyString_AsString(vob);
2537 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
2538 * because that function calls us, so we could end up with infinite
2539 * recursion. I'm not even sure if eob could be NULL here -- would an
2540 * Assert() be more appropriate?
2542 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
2543 xstr = PLy_printf("%s: %s", estr, vstr);
2550 * intuit an appropriate error level based on the exception type
2552 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
2554 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
2564 PLy_printf(const char *fmt,...)
2570 emsg = PLy_vprintf(fmt, ap);
2576 PLy_vprintf(const char *fmt, va_list ap)
2583 blen = strlen(fmt) * 2;
2586 buf = PLy_malloc(blen * sizeof(char));
2590 bchar = vsnprintf(buf, blen, fmt, ap);
2591 if (bchar > 0 && bchar < blen)
2599 buf = PLy_realloc(buf, blen);
2605 /* python module code */
2607 /* some dumb utility functions */
2609 PLy_malloc(size_t bytes)
2611 void *ptr = malloc(bytes);
2615 (errcode(ERRCODE_OUT_OF_MEMORY),
2616 errmsg("out of memory")));
2621 PLy_realloc(void *optr, size_t bytes)
2623 void *nptr = realloc(optr, bytes);
2627 (errcode(ERRCODE_OUT_OF_MEMORY),
2628 errmsg("out of memory")));
2633 PLy_strdup(const char *str)
2638 len = strlen(str) + 1;
2639 result = PLy_malloc(len);
2640 memcpy(result, str, len);
2645 /* define this away */