1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * This software is copyright by Andrew Bosma
5 * but is really shameless cribbed from pltcl.c by Jan Weick, and
6 * plperl.c by Mark Hollomon.
8 * The author hereby grants permission to use, copy, modify,
9 * distribute, and license this software and its documentation for any
10 * purpose, provided that existing copyright notices are retained in
11 * all copies and that this notice is included verbatim in any
12 * distributions. No written agreement, license, or royalty fee is
13 * required for any of the authorized uses. Modifications to this
14 * software may be copyrighted by their author and need not follow the
15 * licensing terms described here, provided that the new terms are
16 * clearly indicated on the first page of each file where they apply.
18 * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY
19 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
20 * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
21 * DERIVATIVES THEREOF, EVEN IF THE AUTHOR HAVE BEEN ADVISED OF THE
22 * POSSIBILITY OF SUCH DAMAGE.
24 * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
25 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
27 * NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
28 * AND THE AUTHOR AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
29 * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
32 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.53 2004/08/05 03:10:29 joe Exp $
34 *********************************************************************
44 /* postgreSQL stuff */
45 #include "access/heapam.h"
46 #include "catalog/pg_proc.h"
47 #include "catalog/pg_type.h"
48 #include "commands/trigger.h"
49 #include "executor/spi.h"
51 #include "nodes/makefuncs.h"
52 #include "parser/parse_type.h"
53 #include "tcop/tcopprot.h"
54 #include "utils/lsyscache.h"
55 #include "utils/syscache.h"
56 #include "utils/typcache.h"
61 /* convert Postgresql Datum or tuple into a PyObject.
62 * input to Python. Tuples are converted to dictionary
66 typedef PyObject *(*PLyDatumToObFunc) (const char *);
68 typedef struct PLyDatumToOb
70 PLyDatumToObFunc func;
76 typedef struct PLyTupleToOb
82 typedef union PLyTypeInput
88 /* convert PyObject to a Postgresql Datum or tuple.
91 typedef struct PLyObToDatum
98 typedef struct PLyObToTuple
104 typedef union PLyTypeOutput
110 /* all we need to move Postgresql data to Python objects,
113 typedef struct PLyTypeInfo
120 * -1 not known yet (initial state)
123 * 2 rowtype, but I/O functions not set up yet
128 /* cached procedure data
130 typedef struct PLyProcedure
132 char *proname; /* SQL name of procedure */
133 char *pyname; /* Python name of procedure */
134 TransactionId fn_xmin;
136 PLyTypeInfo result; /* also used to store info for trigger
138 PLyTypeInfo args[FUNC_MAX_ARGS];
140 PyObject *code; /* compiled procedure code */
141 PyObject *statics; /* data saved across calls, local scope */
142 PyObject *globals; /* data saved across calls, global score */
143 PyObject *me; /* PyCObject containing pointer to this
150 typedef struct PLyPlanObject
153 void *plan; /* return of an SPI_saveplan */
160 typedef struct PLyResultObject
163 /* HeapTuple *tuples; */
164 PyObject *nrows; /* number of rows returned by query */
165 PyObject *rows; /* data rows, or None if no data returned */
166 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
170 /* function declarations
173 /* Two exported functions: first is the magic telling Postgresql
174 * what function call interface it implements. Second allows
175 * preinitialization of the interpreter during postmaster startup.
177 Datum plpython_call_handler(PG_FUNCTION_ARGS);
178 void plpython_init(void);
180 PG_FUNCTION_INFO_V1(plpython_call_handler);
182 /* most of the remaining of the declarations, all static
185 /* these should only be called once at the first call
186 * of plpython_call_handler. initialize the python interpreter
189 static void PLy_init_all(void);
190 static void PLy_init_interp(void);
191 static void PLy_init_plpy(void);
193 /* call PyErr_SetString with a vprint interface
196 PLy_exception_set(PyObject *, const char *,...)
197 __attribute__((format(printf, 2, 3)));
199 /* Get the innermost python procedure called from the backend.
201 static char *PLy_procedure_name(PLyProcedure *);
203 /* some utility functions
205 static void PLy_elog(int, const char *,...);
206 static char *PLy_traceback(int *);
207 static char *PLy_vprintf(const char *fmt, va_list ap);
208 static char *PLy_printf(const char *fmt,...);
210 static void *PLy_malloc(size_t);
211 static void *PLy_realloc(void *, size_t);
212 static void PLy_free(void *);
214 /* sub handlers for functions and triggers
216 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
217 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
219 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
220 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
222 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
223 TriggerData *, HeapTuple);
225 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
227 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
230 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
232 HeapTuple procTup, char *key);
234 static void PLy_procedure_compile(PLyProcedure *, const char *);
235 static char *PLy_procedure_munge_source(const char *, const char *);
236 static void PLy_procedure_delete(PLyProcedure *);
238 static void PLy_typeinfo_init(PLyTypeInfo *);
239 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
240 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
241 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
242 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
243 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
244 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
245 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
247 /* conversion functions
249 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
250 static PyObject *PLyBool_FromString(const char *);
251 static PyObject *PLyFloat_FromString(const char *);
252 static PyObject *PLyInt_FromString(const char *);
253 static PyObject *PLyLong_FromString(const char *);
254 static PyObject *PLyString_FromString(const char *);
259 static int PLy_first_call = 1;
262 * Last function called by postgres backend
264 * XXX replace this with errcontext mechanism
266 static PLyProcedure *PLy_last_procedure = NULL;
269 * When a callback from Python into PG incurs an error, we temporarily store
270 * the error information here, and return NULL to the Python interpreter.
271 * Any further callback attempts immediately fail, and when the Python
272 * interpreter returns to the calling function, we re-throw the error (even if
273 * Python thinks it trapped the error and doesn't return NULL). Eventually
274 * this ought to be improved to let Python code really truly trap the error,
275 * but that's more of a change from the pre-8.0 semantics than I have time for
276 * now --- it will only be possible if the callback query is executed inside a
279 static ErrorData *PLy_error_in_progress = NULL;
281 static PyObject *PLy_interp_globals = NULL;
282 static PyObject *PLy_interp_safe_globals = NULL;
283 static PyObject *PLy_procedure_cache = NULL;
287 static PyObject *PLy_exc_error = NULL;
288 static PyObject *PLy_exc_fatal = NULL;
289 static PyObject *PLy_exc_spi_error = NULL;
291 /* some globals for the python module
293 static char PLy_plan_doc[] = {
294 "Store a PostgreSQL plan"
297 static char PLy_result_doc[] = {
298 "Results of a PostgreSQL query"
303 * the function definitions
307 * This routine is a crock, and so is everyplace that calls it. The problem
308 * is that the cached form of plpython functions/queries is allocated permanently
309 * (mostly via malloc()) and never released until backend exit. Subsidiary
310 * data structures such as fmgr info records therefore must live forever
311 * as well. A better implementation would store all this stuff in a per-
312 * function memory context that could be reclaimed at need. In the meantime,
313 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
314 * it might allocate, and whatever the eventual function might allocate using
315 * fn_mcxt, will live forever too.
318 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
320 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
324 plpython_call_handler(PG_FUNCTION_ARGS)
327 PLyProcedure *volatile proc = NULL;
331 if (SPI_connect() != SPI_OK_CONNECT)
332 elog(ERROR, "could not connect to SPI manager");
336 if (CALLED_AS_TRIGGER(fcinfo))
338 TriggerData *tdata = (TriggerData *) fcinfo->context;
341 proc = PLy_procedure_get(fcinfo,
342 RelationGetRelid(tdata->tg_relation));
343 trv = PLy_trigger_handler(fcinfo, proc);
344 retval = PointerGetDatum(trv);
348 proc = PLy_procedure_get(fcinfo, InvalidOid);
349 retval = PLy_function_handler(fcinfo, proc);
356 /* note: Py_DECREF needs braces around it, as of 2003/08 */
369 /* trigger and function sub handlers
371 * the python function is expected to return Py_None if the tuple is
372 * acceptable and unmodified. Otherwise it should return a PyString
373 * object who's value is SKIP, or MODIFY. SKIP means don't perform
374 * this action. MODIFY means the tuple has been modified, so update
375 * tuple and perform action. SKIP and MODIFY assume the trigger fires
376 * BEFORE the event and is ROW level. postgres expects the function
377 * to take no arguments and return an argument of type trigger.
380 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
383 PyObject *volatile plargs = NULL;
384 PyObject *volatile plrv = NULL;
388 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
389 plrv = PLy_procedure_call(proc, "TD", plargs);
391 Assert(plrv != NULL);
392 Assert(!PLy_error_in_progress);
395 * Disconnect from SPI manager
397 if (SPI_finish() != SPI_OK_FINISH)
398 elog(ERROR, "SPI_finish failed");
401 * return of None means we're happy with the tuple
407 if (!PyString_Check(plrv))
408 elog(ERROR, "expected trigger to return None or a String");
410 srv = PyString_AsString(plrv);
411 if (pg_strcasecmp(srv, "SKIP") == 0)
413 else if (pg_strcasecmp(srv, "MODIFY") == 0)
415 TriggerData *tdata = (TriggerData *) fcinfo->context;
417 if ((TRIGGER_FIRED_BY_INSERT(tdata->tg_event)) ||
418 (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event)))
419 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
421 elog(WARNING, "ignoring modified tuple in DELETE trigger");
423 else if (pg_strcasecmp(srv, "OK") != 0)
426 * hmmm, perhaps they only read the pltcl page, not a
427 * surprising thing since i've written no documentation, so
428 * accept a belated OK
430 elog(ERROR, "expected return to be \"SKIP\" or \"MODIFY\"");
450 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
453 PyObject *volatile plntup;
454 PyObject *volatile plkeys;
455 PyObject *volatile platt;
456 PyObject *volatile plval;
457 PyObject *volatile plstr;
463 int *volatile modattrs;
464 Datum *volatile modvalues;
465 char *volatile modnulls;
468 plntup = plkeys = platt = plval = plstr = NULL;
475 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
476 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
477 if (!PyDict_Check(plntup))
478 elog(ERROR, "TD[\"new\"] is not a dictionary object");
481 plkeys = PyDict_Keys(plntup);
482 natts = PyList_Size(plkeys);
484 modattrs = (int *) palloc(natts * sizeof(int));
485 modvalues = (Datum *) palloc(natts * sizeof(Datum));
486 modnulls = (char *) palloc(natts * sizeof(char));
488 tupdesc = tdata->tg_relation->rd_att;
490 for (i = 0; i < natts; i++)
494 platt = PyList_GetItem(plkeys, i);
495 if (!PyString_Check(platt))
496 elog(ERROR, "attribute name is not a string");
497 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
498 if (attn == SPI_ERROR_NOATTRIBUTE)
499 elog(ERROR, "invalid attribute \"%s\" in tuple",
500 PyString_AsString(platt));
503 plval = PyDict_GetItem(plntup, platt);
505 elog(FATAL, "python interpreter is probably corrupted");
511 if (plval != Py_None && !tupdesc->attrs[atti]->attisdropped)
513 plstr = PyObject_Str(plval);
514 src = PyString_AsString(plstr);
516 modvalues[i] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
517 CStringGetDatum(src),
518 ObjectIdGetDatum(proc->result.out.r.atts[atti].typioparam),
519 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
527 modvalues[i] = (Datum) 0;
535 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
536 modattrs, modvalues, modnulls);
538 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
570 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
572 TriggerData *tdata = (TriggerData *) fcinfo->context;
581 PyObject *volatile pltdata = NULL;
586 pltdata = PyDict_New();
588 PLy_elog(ERROR, "could not build arguments for trigger procedure");
590 pltname = PyString_FromString(tdata->tg_trigger->tgname);
591 PyDict_SetItemString(pltdata, "name", pltname);
594 stroid = DatumGetCString(DirectFunctionCall1(oidout,
595 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
596 pltrelid = PyString_FromString(stroid);
597 PyDict_SetItemString(pltdata, "relid", pltrelid);
601 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
602 pltwhen = PyString_FromString("BEFORE");
603 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
604 pltwhen = PyString_FromString("AFTER");
607 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
608 pltwhen = NULL; /* keep compiler quiet */
610 PyDict_SetItemString(pltdata, "when", pltwhen);
613 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
615 pltlevel = PyString_FromString("ROW");
616 PyDict_SetItemString(pltdata, "level", pltlevel);
619 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
621 pltevent = PyString_FromString("INSERT");
623 PyDict_SetItemString(pltdata, "old", Py_None);
624 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
625 tdata->tg_relation->rd_att);
626 PyDict_SetItemString(pltdata, "new", pytnew);
628 *rv = tdata->tg_trigtuple;
630 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
632 pltevent = PyString_FromString("DELETE");
634 PyDict_SetItemString(pltdata, "new", Py_None);
635 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
636 tdata->tg_relation->rd_att);
637 PyDict_SetItemString(pltdata, "old", pytold);
639 *rv = tdata->tg_trigtuple;
641 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
643 pltevent = PyString_FromString("UPDATE");
645 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
646 tdata->tg_relation->rd_att);
647 PyDict_SetItemString(pltdata, "new", pytnew);
649 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
650 tdata->tg_relation->rd_att);
651 PyDict_SetItemString(pltdata, "old", pytold);
653 *rv = tdata->tg_newtuple;
657 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
658 pltevent = NULL; /* keep compiler quiet */
661 PyDict_SetItemString(pltdata, "event", pltevent);
664 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
666 pltlevel = PyString_FromString("STATEMENT");
667 PyDict_SetItemString(pltdata, "level", pltlevel);
670 PyDict_SetItemString(pltdata, "old", Py_None);
671 PyDict_SetItemString(pltdata, "new", Py_None);
674 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
675 pltevent = PyString_FromString("INSERT");
676 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
677 pltevent = PyString_FromString("DELETE");
678 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
679 pltevent = PyString_FromString("UPDATE");
682 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
683 pltevent = NULL; /* keep compiler quiet */
686 PyDict_SetItemString(pltdata, "event", pltevent);
690 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
692 if (tdata->tg_trigger->tgnargs)
700 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
701 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
703 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
706 * stolen, don't Py_DECREF
708 PyList_SetItem(pltargs, i, pltarg);
716 PyDict_SetItemString(pltdata, "args", pltargs);
731 /* function handler and friends
734 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
737 PyObject *volatile plargs = NULL;
738 PyObject *volatile plrv = NULL;
739 PyObject *volatile plrv_so = NULL;
744 plargs = PLy_function_build_args(fcinfo, proc);
745 plrv = PLy_procedure_call(proc, "args", plargs);
747 Assert(plrv != NULL);
748 Assert(!PLy_error_in_progress);
751 * Disconnect from SPI manager and then create the return values datum
752 * (if the input function does a palloc for it this must not be
753 * allocated in the SPI memory context because SPI_finish would free
756 if (SPI_finish() != SPI_OK_FINISH)
757 elog(ERROR, "SPI_finish failed");
760 * convert the python PyObject to a postgresql Datum
764 fcinfo->isnull = true;
769 fcinfo->isnull = false;
770 plrv_so = PyObject_Str(plrv);
771 plrv_sc = PyString_AsString(plrv_so);
772 rv = FunctionCall3(&proc->result.out.d.typfunc,
773 PointerGetDatum(plrv_sc),
774 ObjectIdGetDatum(proc->result.out.d.typioparam),
797 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
800 PLyProcedure *current;
802 current = PLy_last_procedure;
803 PLy_last_procedure = proc;
804 PyDict_SetItemString(proc->globals, kargs, vargs);
805 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
806 proc->globals, proc->globals);
807 PLy_last_procedure = current;
810 * If there was an error in a PG callback, propagate that
811 * no matter what Python claims about its success.
813 if (PLy_error_in_progress)
815 ErrorData *edata = PLy_error_in_progress;
817 PLy_error_in_progress = NULL;
821 if ((rv == NULL) || (PyErr_Occurred()))
824 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
831 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
833 PyObject *volatile arg = NULL;
834 PyObject *volatile args = NULL;
839 args = PyList_New(proc->nargs);
840 for (i = 0; i < proc->nargs; i++)
842 if (proc->args[i].is_rowtype > 0)
844 if (fcinfo->argnull[i])
852 HeapTupleData tmptup;
854 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
855 /* Extract rowtype info and find a tupdesc */
856 tupType = HeapTupleHeaderGetTypeId(td);
857 tupTypmod = HeapTupleHeaderGetTypMod(td);
858 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
860 /* Set up I/O funcs if not done yet */
861 if (proc->args[i].is_rowtype != 1)
862 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
864 /* Build a temporary HeapTuple control structure */
865 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
868 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
873 if (fcinfo->argnull[i])
880 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
882 ObjectIdGetDatum(proc->args[i].in.d.typioparam),
884 ct = DatumGetCString(dt);
885 arg = (proc->args[i].in.d.func) (ct);
897 * FIXME -- error check this
899 PyList_SetItem(args, i, arg);
916 * PLyProcedure functions
919 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
920 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
921 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
924 static PLyProcedure *
925 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
931 PLyProcedure *proc = NULL;
934 fn_oid = fcinfo->flinfo->fn_oid;
935 procTup = SearchSysCache(PROCOID,
936 ObjectIdGetDatum(fn_oid),
938 if (!HeapTupleIsValid(procTup))
939 elog(ERROR, "cache lookup failed for function %u", fn_oid);
941 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
942 if ((rv >= sizeof(key)) || (rv < 0))
943 elog(ERROR, "key too long");
945 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
950 if (!PyCObject_Check(plproc))
951 elog(FATAL, "expected a PyCObject, didn't get one");
953 proc = PyCObject_AsVoidPtr(plproc);
954 if (proc->me != plproc)
955 elog(FATAL, "proc->me != plproc");
956 /* did we find an up-to-date cache entry? */
957 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
958 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
966 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
968 ReleaseSysCache(procTup);
973 static PLyProcedure *
974 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
975 HeapTuple procTup, char *key)
977 char procName[NAMEDATALEN + 256];
979 Form_pg_proc procStruct;
980 PLyProcedure *volatile proc;
981 char *volatile procSource = NULL;
987 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
989 if (OidIsValid(tgreloid))
990 rv = snprintf(procName, sizeof(procName),
991 "__plpython_procedure_%s_%u_trigger_%u",
992 NameStr(procStruct->proname),
993 fcinfo->flinfo->fn_oid,
996 rv = snprintf(procName, sizeof(procName),
997 "__plpython_procedure_%s_%u",
998 NameStr(procStruct->proname),
999 fcinfo->flinfo->fn_oid);
1000 if ((rv >= sizeof(procName)) || (rv < 0))
1001 elog(ERROR, "procedure name would overrun buffer");
1003 proc = PLy_malloc(sizeof(PLyProcedure));
1004 proc->proname = PLy_malloc(strlen(NameStr(procStruct->proname)) + 1);
1005 strcpy(proc->proname, NameStr(procStruct->proname));
1006 proc->pyname = PLy_malloc(strlen(procName) + 1);
1007 strcpy(proc->pyname, procName);
1008 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1009 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1010 PLy_typeinfo_init(&proc->result);
1011 for (i = 0; i < FUNC_MAX_ARGS; i++)
1012 PLy_typeinfo_init(&proc->args[i]);
1014 proc->code = proc->statics = NULL;
1015 proc->globals = proc->me = NULL;
1020 * get information required for output conversion of the return value,
1021 * but only if this isn't a trigger.
1023 if (!CALLED_AS_TRIGGER(fcinfo))
1025 HeapTuple rvTypeTup;
1026 Form_pg_type rvTypeStruct;
1028 rvTypeTup = SearchSysCache(TYPEOID,
1029 ObjectIdGetDatum(procStruct->prorettype),
1031 if (!HeapTupleIsValid(rvTypeTup))
1032 elog(ERROR, "cache lookup failed for type %u",
1033 procStruct->prorettype);
1035 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1036 if (rvTypeStruct->typtype != 'c')
1037 PLy_output_datum_func(&proc->result, rvTypeTup);
1040 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1041 errmsg("tuple return types are not supported yet")));
1043 ReleaseSysCache(rvTypeTup);
1048 * input/output conversion for trigger tuples. use the result
1049 * TypeInfo variable to store the tuple conversion info.
1051 TriggerData *tdata = (TriggerData *) fcinfo->context;
1053 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1054 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1058 * now get information required for input conversion of the procedures
1061 proc->nargs = fcinfo->nargs;
1062 for (i = 0; i < fcinfo->nargs; i++)
1064 HeapTuple argTypeTup;
1065 Form_pg_type argTypeStruct;
1067 argTypeTup = SearchSysCache(TYPEOID,
1068 ObjectIdGetDatum(procStruct->proargtypes[i]),
1070 if (!HeapTupleIsValid(argTypeTup))
1071 elog(ERROR, "cache lookup failed for type %u",
1072 procStruct->proargtypes[i]);
1073 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1075 if (argTypeStruct->typtype != 'c')
1076 PLy_input_datum_func(&(proc->args[i]),
1077 procStruct->proargtypes[i],
1080 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1082 ReleaseSysCache(argTypeTup);
1087 * get the text of the function.
1089 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1090 Anum_pg_proc_prosrc, &isnull);
1092 elog(ERROR, "null prosrc");
1093 procSource = DatumGetCString(DirectFunctionCall1(textout,
1096 PLy_procedure_compile(proc, procSource);
1100 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1101 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1105 PLy_procedure_delete(proc);
1117 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1119 PyObject *crv = NULL;
1122 proc->globals = PyDict_Copy(PLy_interp_globals);
1125 * SD is private preserved data between calls GD is global data shared
1128 proc->statics = PyDict_New();
1129 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1132 * insert the function code into the interpreter
1134 msrc = PLy_procedure_munge_source(proc->pyname, src);
1135 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1138 if ((crv != NULL) && (!PyErr_Occurred()))
1141 char call[NAMEDATALEN + 256];
1146 * compile a call to the function
1148 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1149 if ((clen < 0) || (clen >= sizeof(call)))
1150 elog(ERROR, "string would overflow buffer");
1151 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1152 if ((proc->code != NULL) && (!PyErr_Occurred()))
1158 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1162 PLy_procedure_munge_source(const char *name, const char *src)
1171 * room for function source and the def statement
1173 mlen = (strlen(src) * 2) + strlen(name) + 16;
1175 mrc = PLy_malloc(mlen);
1176 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1177 Assert(plen >= 0 && plen < mlen);
1196 if (mp > (mrc + mlen))
1197 elog(FATAL, "buffer overrun in PLy_munge_source");
1203 PLy_procedure_delete(PLyProcedure * proc)
1207 Py_XDECREF(proc->code);
1208 Py_XDECREF(proc->statics);
1209 Py_XDECREF(proc->globals);
1210 Py_XDECREF(proc->me);
1212 PLy_free(proc->proname);
1214 PLy_free(proc->pyname);
1215 for (i = 0; i < proc->nargs; i++)
1216 if (proc->args[i].is_rowtype == 1)
1218 if (proc->args[i].in.r.atts)
1219 PLy_free(proc->args[i].in.r.atts);
1220 if (proc->args[i].out.r.atts)
1221 PLy_free(proc->args[i].out.r.atts);
1225 /* conversion functions. remember output from python is
1226 * input to postgresql, and vis versa.
1229 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1233 if (arg->is_rowtype == 0)
1234 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1236 arg->is_rowtype = 1;
1237 arg->in.r.natts = desc->natts;
1238 arg->in.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1240 for (i = 0; i < desc->natts; i++)
1244 if (desc->attrs[i]->attisdropped)
1247 typeTup = SearchSysCache(TYPEOID,
1248 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1250 if (!HeapTupleIsValid(typeTup))
1251 elog(ERROR, "cache lookup failed for type %u",
1252 desc->attrs[i]->atttypid);
1254 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1255 desc->attrs[i]->atttypid,
1258 ReleaseSysCache(typeTup);
1263 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1267 if (arg->is_rowtype == 0)
1268 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1270 arg->is_rowtype = 1;
1271 arg->out.r.natts = desc->natts;
1272 arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1274 for (i = 0; i < desc->natts; i++)
1278 if (desc->attrs[i]->attisdropped)
1281 typeTup = SearchSysCache(TYPEOID,
1282 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1284 if (!HeapTupleIsValid(typeTup))
1285 elog(ERROR, "cache lookup failed for type %u",
1286 desc->attrs[i]->atttypid);
1288 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1290 ReleaseSysCache(typeTup);
1295 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1297 if (arg->is_rowtype > 0)
1298 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1299 arg->is_rowtype = 0;
1300 PLy_output_datum_func2(&(arg->out.d), typeTup);
1304 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1306 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1308 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1309 arg->typioparam = getTypeIOParam(typeTup);
1310 arg->typbyval = typeStruct->typbyval;
1314 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1316 if (arg->is_rowtype > 0)
1317 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1318 arg->is_rowtype = 0;
1319 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1323 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1325 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1327 /* Get the type's conversion information */
1328 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1329 arg->typioparam = getTypeIOParam(typeTup);
1330 arg->typbyval = typeStruct->typbyval;
1332 /* Determine which kind of Python object we will convert to */
1336 arg->func = PLyBool_FromString;
1341 arg->func = PLyFloat_FromString;
1345 arg->func = PLyInt_FromString;
1348 arg->func = PLyLong_FromString;
1351 arg->func = PLyString_FromString;
1357 PLy_typeinfo_init(PLyTypeInfo * arg)
1359 arg->is_rowtype = -1;
1360 arg->in.r.natts = arg->out.r.natts = 0;
1361 arg->in.r.atts = NULL;
1362 arg->out.r.atts = NULL;
1366 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1368 if (arg->is_rowtype == 1)
1371 PLy_free(arg->in.r.atts);
1372 if (arg->out.r.atts)
1373 PLy_free(arg->out.r.atts);
1377 /* assumes that a bool is always returned as a 't' or 'f'
1380 PLyBool_FromString(const char *src)
1383 return PyInt_FromLong(1);
1384 return PyInt_FromLong(0);
1388 PLyFloat_FromString(const char *src)
1394 v = strtod(src, &eptr);
1395 if ((*eptr != '\0') || (errno))
1397 return PyFloat_FromDouble(v);
1401 PLyInt_FromString(const char *src)
1407 v = strtol(src, &eptr, 0);
1408 if ((*eptr != '\0') || (errno))
1410 return PyInt_FromLong(v);
1414 PLyLong_FromString(const char *src)
1416 return PyLong_FromString((char *) src, NULL, 0);
1420 PLyString_FromString(const char *src)
1422 return PyString_FromString(src);
1426 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1428 PyObject *volatile dict;
1431 if (info->is_rowtype != 1)
1432 elog(ERROR, "PLyTypeInfo structure describes a datum");
1434 dict = PyDict_New();
1436 PLy_elog(ERROR, "could not create tuple dictionary");
1440 for (i = 0; i < info->in.r.natts; i++)
1449 if (desc->attrs[i]->attisdropped)
1452 key = NameStr(desc->attrs[i]->attname);
1453 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1455 if ((is_null) || (info->in.r.atts[i].func == NULL))
1456 PyDict_SetItemString(dict, key, Py_None);
1459 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1461 ObjectIdGetDatum(info->in.r.atts[i].typioparam),
1462 Int32GetDatum(desc->attrs[i]->atttypmod));
1463 vsrc = DatumGetCString(vdat);
1466 * no exceptions allowed
1468 value = info->in.r.atts[i].func(vsrc);
1470 PyDict_SetItemString(dict, key, value);
1485 /* initialization, some python variables function declared here
1488 /* interface to postgresql elog
1490 static PyObject *PLy_debug(PyObject *, PyObject *);
1491 static PyObject *PLy_log(PyObject *, PyObject *);
1492 static PyObject *PLy_info(PyObject *, PyObject *);
1493 static PyObject *PLy_notice(PyObject *, PyObject *);
1494 static PyObject *PLy_warning(PyObject *, PyObject *);
1495 static PyObject *PLy_error(PyObject *, PyObject *);
1496 static PyObject *PLy_fatal(PyObject *, PyObject *);
1498 /* PLyPlanObject, PLyResultObject and SPI interface
1500 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1501 static PyObject *PLy_plan_new(void);
1502 static void PLy_plan_dealloc(PyObject *);
1503 static PyObject *PLy_plan_getattr(PyObject *, char *);
1504 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1506 static PyObject *PLy_result_new(void);
1507 static void PLy_result_dealloc(PyObject *);
1508 static PyObject *PLy_result_getattr(PyObject *, char *);
1511 /* Appear to be unused */
1512 static PyObject *PLy_result_fetch(PyObject *, PyObject *);
1513 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1514 static PyObject *PLy_result_status(PyObject *, PyObject *);
1516 static int PLy_result_length(PyObject *);
1517 static PyObject *PLy_result_item(PyObject *, int);
1518 static PyObject *PLy_result_slice(PyObject *, int, int);
1519 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1520 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1523 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1524 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1525 static PyObject *PLy_spi_execute_query(char *query, int limit);
1526 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, int);
1527 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1530 static PyTypeObject PLy_PlanType = {
1531 PyObject_HEAD_INIT(NULL)
1533 "PLyPlan", /* tp_name */
1534 sizeof(PLyPlanObject), /* tp_size */
1535 0, /* tp_itemsize */
1540 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1542 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1546 0, /* tp_as_number */
1547 0, /* tp_as_sequence */
1548 0, /* tp_as_mapping */
1552 0, /* tp_getattro */
1553 0, /* tp_setattro */
1554 0, /* tp_as_buffer */
1556 PLy_plan_doc, /* tp_doc */
1559 static PyMethodDef PLy_plan_methods[] = {
1560 {"status", (PyCFunction) PLy_plan_status, METH_VARARGS, NULL},
1561 {NULL, NULL, 0, NULL}
1565 static PySequenceMethods PLy_result_as_sequence = {
1566 (inquiry) PLy_result_length, /* sq_length */
1567 (binaryfunc) 0, /* sq_concat */
1568 (intargfunc) 0, /* sq_repeat */
1569 (intargfunc) PLy_result_item, /* sq_item */
1570 (intintargfunc) PLy_result_slice, /* sq_slice */
1571 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1572 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1575 static PyTypeObject PLy_ResultType = {
1576 PyObject_HEAD_INIT(NULL)
1578 "PLyResult", /* tp_name */
1579 sizeof(PLyResultObject), /* tp_size */
1580 0, /* tp_itemsize */
1585 (destructor) PLy_result_dealloc, /* tp_dealloc */
1587 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1591 0, /* tp_as_number */
1592 &PLy_result_as_sequence, /* tp_as_sequence */
1593 0, /* tp_as_mapping */
1597 0, /* tp_getattro */
1598 0, /* tp_setattro */
1599 0, /* tp_as_buffer */
1601 PLy_result_doc, /* tp_doc */
1605 /* Appear to be unused */
1606 static PyMethodDef PLy_result_methods[] = {
1607 {"fetch", (PyCFunction) PLy_result_fetch, METH_VARARGS, NULL,},
1608 {"nrows", (PyCFunction) PLy_result_nrows, METH_VARARGS, NULL},
1609 {"status", (PyCFunction) PLy_result_status, METH_VARARGS, NULL},
1610 {NULL, NULL, 0, NULL}
1614 static PyMethodDef PLy_methods[] = {
1618 {"debug", PLy_debug, METH_VARARGS, NULL},
1619 {"log", PLy_log, METH_VARARGS, NULL},
1620 {"info", PLy_info, METH_VARARGS, NULL},
1621 {"notice", PLy_notice, METH_VARARGS, NULL},
1622 {"warning", PLy_warning, METH_VARARGS, NULL},
1623 {"error", PLy_error, METH_VARARGS, NULL},
1624 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1627 * create a stored plan
1629 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1632 * execute a plan or query
1634 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1636 {NULL, NULL, 0, NULL}
1640 /* plan object methods
1647 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1655 return (PyObject *) ob;
1660 PLy_plan_dealloc(PyObject * arg)
1662 PLyPlanObject *ob = (PLyPlanObject *) arg;
1665 SPI_freeplan(ob->plan);
1667 PLy_free(ob->types);
1672 for (i = 0; i < ob->nargs; i++)
1673 PLy_typeinfo_dealloc(&ob->args[i]);
1682 PLy_plan_getattr(PyObject * self, char *name)
1684 return Py_FindMethod(PLy_plan_methods, self, name);
1688 PLy_plan_status(PyObject * self, PyObject * args)
1690 if (PyArg_ParseTuple(args, ""))
1694 /* return PyInt_FromLong(self->status); */
1696 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1702 /* result object methods
1706 PLy_result_new(void)
1708 PLyResultObject *ob;
1710 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1713 /* ob->tuples = NULL; */
1716 ob->status = Py_None;
1717 ob->nrows = PyInt_FromLong(-1);
1718 ob->rows = PyList_New(0);
1720 return (PyObject *) ob;
1724 PLy_result_dealloc(PyObject * arg)
1726 PLyResultObject *ob = (PLyResultObject *) arg;
1728 Py_XDECREF(ob->nrows);
1729 Py_XDECREF(ob->rows);
1730 Py_XDECREF(ob->status);
1736 PLy_result_getattr(PyObject * self, char *attr)
1742 /* Appear to be unused */
1744 PLy_result_fetch(PyObject * self, PyObject * args)
1750 PLy_result_nrows(PyObject * self, PyObject * args)
1752 PLyResultObject *ob = (PLyResultObject *) self;
1754 Py_INCREF(ob->nrows);
1759 PLy_result_status(PyObject * self, PyObject * args)
1761 PLyResultObject *ob = (PLyResultObject *) self;
1763 Py_INCREF(ob->status);
1769 PLy_result_length(PyObject * arg)
1771 PLyResultObject *ob = (PLyResultObject *) arg;
1773 return PyList_Size(ob->rows);
1777 PLy_result_item(PyObject * arg, int idx)
1780 PLyResultObject *ob = (PLyResultObject *) arg;
1782 rv = PyList_GetItem(ob->rows, idx);
1789 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1792 PLyResultObject *ob = (PLyResultObject *) arg;
1795 rv = PyList_SetItem(ob->rows, idx, item);
1800 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1803 PLyResultObject *ob = (PLyResultObject *) arg;
1805 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1813 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1816 PLyResultObject *ob = (PLyResultObject *) arg;
1818 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1825 PLy_spi_prepare(PyObject * self, PyObject * args)
1827 PLyPlanObject *plan;
1828 PyObject *list = NULL;
1829 PyObject *volatile optr = NULL;
1832 MemoryContext oldcontext;
1834 /* Can't execute more if we have an unhandled error */
1835 if (PLy_error_in_progress)
1837 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1841 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1843 PyErr_SetString(PLy_exc_spi_error,
1844 "Invalid arguments for plpy.prepare()");
1848 if ((list) && (!PySequence_Check(list)))
1850 PyErr_SetString(PLy_exc_spi_error,
1851 "Second argument in plpy.prepare() must be a sequence");
1855 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1858 oldcontext = CurrentMemoryContext;
1866 nargs = PySequence_Length(list);
1869 plan->nargs = nargs;
1870 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1871 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1872 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1875 * the other loop might throw an exception, if PLyTypeInfo
1876 * member isn't properly initialized the Py_DECREF(plan) will
1879 for (i = 0; i < nargs; i++)
1881 PLy_typeinfo_init(&plan->args[i]);
1882 plan->values[i] = (Datum) NULL;
1885 for (i = 0; i < nargs; i++)
1889 Form_pg_type typeStruct;
1891 optr = PySequence_GetItem(list, i);
1892 if (!PyString_Check(optr))
1893 elog(ERROR, "Type names must be strings.");
1894 sptr = PyString_AsString(optr);
1895 /* XXX should extend this to allow qualified type names */
1896 typeTup = typenameType(makeTypeName(sptr));
1898 optr = NULL; /* this is important */
1900 plan->types[i] = HeapTupleGetOid(typeTup);
1901 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1902 if (typeStruct->typtype != 'c')
1903 PLy_output_datum_func(&plan->args[i], typeTup);
1905 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
1906 ReleaseSysCache(typeTup);
1911 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1912 if (plan->plan == NULL)
1913 elog(ERROR, "SPI_prepare failed: %s",
1914 SPI_result_code_string(SPI_result));
1916 /* transfer plan from procCxt to topCxt */
1917 tmpplan = plan->plan;
1918 plan->plan = SPI_saveplan(tmpplan);
1919 SPI_freeplan(tmpplan);
1920 if (plan->plan == NULL)
1921 elog(ERROR, "SPI_saveplan failed: %s",
1922 SPI_result_code_string(SPI_result));
1926 MemoryContextSwitchTo(oldcontext);
1927 PLy_error_in_progress = CopyErrorData();
1931 if (!PyErr_Occurred())
1932 PyErr_SetString(PLy_exc_spi_error,
1933 "Unknown error in PLy_spi_prepare");
1934 /* XXX this oughta be replaced with errcontext mechanism */
1935 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
1940 return (PyObject *) plan;
1943 /* execute(query="select * from foo", limit=5)
1944 * execute(plan=plan, values=(foo, bar), limit=5)
1947 PLy_spi_execute(PyObject * self, PyObject * args)
1951 PyObject *list = NULL;
1954 /* Can't execute more if we have an unhandled error */
1955 if (PLy_error_in_progress)
1957 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1961 if (PyArg_ParseTuple(args, "s|i", &query, &limit))
1962 return PLy_spi_execute_query(query, limit);
1966 if ((PyArg_ParseTuple(args, "O|Oi", &plan, &list, &limit)) &&
1967 (is_PLyPlanObject(plan)))
1968 return PLy_spi_execute_plan(plan, list, limit);
1970 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
1975 PLy_spi_execute_plan(PyObject * ob, PyObject * list, int limit)
1980 PLyPlanObject *plan;
1982 MemoryContext oldcontext;
1986 if ((!PySequence_Check(list)) || (PyString_Check(list)))
1988 char *msg = "plpy.execute() takes a sequence as its second argument";
1990 PyErr_SetString(PLy_exc_spi_error, msg);
1993 nargs = PySequence_Length(list);
1998 plan = (PLyPlanObject *) ob;
2000 if (nargs != plan->nargs)
2004 PyObject *so = PyObject_Str(list);
2006 sv = PyString_AsString(so);
2007 PLy_exception_set(PLy_exc_spi_error,
2008 "Expected sequence of %d arguments, got %d. %s",
2009 plan->nargs, nargs, sv);
2015 oldcontext = CurrentMemoryContext;
2018 nulls = palloc(nargs * sizeof(char));
2020 for (i = 0; i < nargs; i++)
2026 elem = PySequence_GetItem(list, i);
2027 if (elem != Py_None)
2029 so = PyObject_Str(elem);
2030 sv = PyString_AsString(so);
2033 * FIXME -- if this elogs, we have Python reference leak
2036 FunctionCall3(&(plan->args[i].out.d.typfunc),
2037 CStringGetDatum(sv),
2038 ObjectIdGetDatum(plan->args[i].out.d.typioparam),
2049 plan->values[i] = (Datum) 0;
2054 rv = SPI_execp(plan->plan, plan->values, nulls, limit);
2060 MemoryContextSwitchTo(oldcontext);
2061 PLy_error_in_progress = CopyErrorData();
2064 * cleanup plan->values array
2066 for (i = 0; i < nargs; i++)
2068 if (!plan->args[i].out.d.typbyval &&
2069 (plan->values[i] != (Datum) NULL))
2071 pfree(DatumGetPointer(plan->values[i]));
2072 plan->values[i] = (Datum) NULL;
2076 if (!PyErr_Occurred())
2077 PyErr_SetString(PLy_exc_error,
2078 "Unknown error in PLy_spi_execute_plan");
2079 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2084 for (i = 0; i < nargs; i++)
2086 if (!plan->args[i].out.d.typbyval &&
2087 (plan->values[i] != (Datum) NULL))
2089 pfree(DatumGetPointer(plan->values[i]));
2090 plan->values[i] = (Datum) NULL;
2096 PLy_exception_set(PLy_exc_spi_error,
2097 "SPI_execp failed: %s",
2098 SPI_result_code_string(rv));
2102 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2106 PLy_spi_execute_query(char *query, int limit)
2109 MemoryContext oldcontext;
2111 oldcontext = CurrentMemoryContext;
2114 rv = SPI_exec(query, limit);
2118 MemoryContextSwitchTo(oldcontext);
2119 PLy_error_in_progress = CopyErrorData();
2121 if (!PyErr_Occurred())
2122 PyErr_SetString(PLy_exc_spi_error,
2123 "Unknown error in PLy_spi_execute_query");
2124 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2131 PLy_exception_set(PLy_exc_spi_error,
2132 "SPI_exec failed: %s",
2133 SPI_result_code_string(rv));
2137 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2141 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2143 PLyResultObject *result;
2144 MemoryContext oldcontext;
2146 result = (PLyResultObject *) PLy_result_new();
2147 Py_DECREF(result->status);
2148 result->status = PyInt_FromLong(status);
2150 if (status == SPI_OK_UTILITY)
2152 Py_DECREF(result->nrows);
2153 result->nrows = PyInt_FromLong(0);
2155 else if (status != SPI_OK_SELECT)
2157 Py_DECREF(result->nrows);
2158 result->nrows = PyInt_FromLong(rows);
2165 PLy_typeinfo_init(&args);
2166 Py_DECREF(result->nrows);
2167 result->nrows = PyInt_FromLong(rows);
2169 oldcontext = CurrentMemoryContext;
2174 Py_DECREF(result->rows);
2175 result->rows = PyList_New(rows);
2177 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2178 for (i = 0; i < rows; i++)
2180 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2183 PyList_SetItem(result->rows, i, row);
2185 PLy_typeinfo_dealloc(&args);
2187 SPI_freetuptable(tuptable);
2192 MemoryContextSwitchTo(oldcontext);
2193 PLy_error_in_progress = CopyErrorData();
2195 if (!PyErr_Occurred())
2196 PyErr_SetString(PLy_exc_error,
2197 "Unknown error in PLy_spi_execute_fetch_result");
2199 PLy_typeinfo_dealloc(&args);
2205 return (PyObject *) result;
2210 * language handler and interpreter initialization
2214 * plpython_init() - Initialize everything that can be
2215 * safely initialized during postmaster
2218 * DO NOT make this static --- it has to be callable by preload
2223 static volatile int init_active = 0;
2225 /* Do initialization only once */
2226 if (!PLy_first_call)
2230 elog(FATAL, "initialization of language module failed");
2236 if (PyErr_Occurred())
2237 PLy_elog(FATAL, "untrapped error in initialization");
2238 PLy_procedure_cache = PyDict_New();
2239 if (PLy_procedure_cache == NULL)
2240 PLy_elog(ERROR, "could not create procedure cache");
2248 /* Execute postmaster-startup safe initialization */
2253 * Any other initialization that must be done each time a new backend
2254 * starts -- currently none
2260 PLy_init_interp(void)
2264 mainmod = PyImport_AddModule("__main__");
2265 if ((mainmod == NULL) || (PyErr_Occurred()))
2266 PLy_elog(ERROR, "could not import \"__main__\" module.");
2268 PLy_interp_globals = PyModule_GetDict(mainmod);
2269 PLy_interp_safe_globals = PyDict_New();
2270 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2272 if ((PLy_interp_globals == NULL) || (PyErr_Occurred()))
2273 PLy_elog(ERROR, "could not initialize globals");
2286 * initialize plpy module
2288 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2289 plpy = Py_InitModule("plpy", PLy_methods);
2290 plpy_dict = PyModule_GetDict(plpy);
2292 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2294 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2295 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2296 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2297 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2298 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2299 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2302 * initialize main module, and add plpy
2304 main_mod = PyImport_AddModule("__main__");
2305 main_dict = PyModule_GetDict(main_mod);
2306 plpy_mod = PyImport_AddModule("plpy");
2307 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2308 if (PyErr_Occurred())
2309 elog(ERROR, "could not init plpy");
2312 /* the python interface to the elog function
2313 * don't confuse these with PLy_elog
2315 static PyObject *PLy_output(int, PyObject *, PyObject *);
2318 PLy_debug(PyObject * self, PyObject * args)
2320 return PLy_output(DEBUG2, self, args);
2324 PLy_log(PyObject * self, PyObject * args)
2326 return PLy_output(LOG, self, args);
2330 PLy_info(PyObject * self, PyObject * args)
2332 return PLy_output(INFO, self, args);
2336 PLy_notice(PyObject * self, PyObject * args)
2338 return PLy_output(NOTICE, self, args);
2342 PLy_warning(PyObject * self, PyObject * args)
2344 return PLy_output(WARNING, self, args);
2348 PLy_error(PyObject * self, PyObject * args)
2350 return PLy_output(ERROR, self, args);
2354 PLy_fatal(PyObject * self, PyObject * args)
2356 return PLy_output(FATAL, self, args);
2361 PLy_output(volatile int level, PyObject * self, PyObject * args)
2365 MemoryContext oldcontext;
2367 so = PyObject_Str(args);
2368 if ((so == NULL) || ((sv = PyString_AsString(so)) == NULL))
2371 sv = "Unable to parse error message in `plpy.elog'";
2374 oldcontext = CurrentMemoryContext;
2377 elog(level, "%s", sv);
2381 MemoryContextSwitchTo(oldcontext);
2382 PLy_error_in_progress = CopyErrorData();
2386 * returning NULL here causes the python interpreter to bail. when
2387 * control passes back to PLy_procedure_call, we check for PG
2388 * exceptions and re-throw the error.
2390 PyErr_SetString(PLy_exc_error, sv);
2398 * return a legal object so the interpreter will continue on its merry
2407 * Get the last procedure name called by the backend ( the innermost,
2408 * If a plpython procedure call calls the backend and the backend calls
2409 * another plpython procedure )
2411 * NB: this returns SQL name, not the internal Python procedure name
2415 PLy_procedure_name(PLyProcedure * proc)
2418 return "<unknown procedure>";
2419 return proc->proname;
2422 /* output a python traceback/exception via the postgresql elog
2423 * function. not pretty.
2426 PLy_exception_set(PyObject * exc, const char *fmt,...)
2432 vsnprintf(buf, sizeof(buf), fmt, ap);
2435 PyErr_SetString(exc, buf);
2438 /* Emit a PG error or notice, together with any available info about the
2439 * current Python error. This should be used to propagate Python errors
2443 PLy_elog(int elevel, const char *fmt,...)
2450 xmsg = PLy_traceback(&xlevel);
2453 emsg = PLy_vprintf(fmt, ap);
2459 (errmsg("plpython: %s", emsg),
2460 (xmsg) ? errdetail("%s", xmsg) : 0));
2477 PLy_traceback(int *xlevel)
2489 * get the current exception
2491 PyErr_Fetch(&e, &v, &tb);
2494 * oops, no exception, return
2502 PyErr_NormalizeException(&e, &v, &tb);
2504 eob = PyObject_Str(e);
2505 if ((v) && ((vob = PyObject_Str(v)) != NULL))
2506 vstr = PyString_AsString(vob);
2510 estr = PyString_AsString(eob);
2511 xstr = PLy_printf("%s: %s", estr, vstr);
2517 * intuit an appropriate error level for based on the exception type
2519 if ((PLy_exc_error) && (PyErr_GivenExceptionMatches(e, PLy_exc_error)))
2521 else if ((PLy_exc_fatal) && (PyErr_GivenExceptionMatches(e, PLy_exc_fatal)))
2530 PLy_printf(const char *fmt,...)
2536 emsg = PLy_vprintf(fmt, ap);
2542 PLy_vprintf(const char *fmt, va_list ap)
2549 blen = strlen(fmt) * 2;
2552 buf = PLy_malloc(blen * sizeof(char));
2556 bchar = vsnprintf(buf, blen, fmt, ap);
2557 if ((bchar > 0) && (bchar < blen))
2565 buf = PLy_realloc(buf, blen);
2571 /* python module code
2575 /* some dumb utility functions
2579 PLy_malloc(size_t bytes)
2581 void *ptr = malloc(bytes);
2585 (errcode(ERRCODE_OUT_OF_MEMORY),
2586 errmsg("out of memory")));
2591 PLy_realloc(void *optr, size_t bytes)
2593 void *nptr = realloc(optr, bytes);
2597 (errcode(ERRCODE_OUT_OF_MEMORY),
2598 errmsg("out of memory")));