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.55 2004/08/30 02:54:42 momjian 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 * is_rowtype can be: -1 not known yet (initial state) 0 scalar
121 * datatype 1 rowtype 2 rowtype, but I/O functions not set up yet
126 /* cached procedure data
128 typedef struct PLyProcedure
130 char *proname; /* SQL name of procedure */
131 char *pyname; /* Python name of procedure */
132 TransactionId fn_xmin;
134 PLyTypeInfo result; /* also used to store info for trigger
136 PLyTypeInfo args[FUNC_MAX_ARGS];
138 PyObject *code; /* compiled procedure code */
139 PyObject *statics; /* data saved across calls, local scope */
140 PyObject *globals; /* data saved across calls, global score */
141 PyObject *me; /* PyCObject containing pointer to this
148 typedef struct PLyPlanObject
151 void *plan; /* return of an SPI_saveplan */
158 typedef struct PLyResultObject
161 /* HeapTuple *tuples; */
162 PyObject * nrows; /* number of rows returned by query */
163 PyObject *rows; /* data rows, or None if no data returned */
164 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
168 /* function declarations
171 /* Two exported functions: first is the magic telling Postgresql
172 * what function call interface it implements. Second allows
173 * preinitialization of the interpreter during postmaster startup.
175 Datum plpython_call_handler(PG_FUNCTION_ARGS);
176 void plpython_init(void);
178 PG_FUNCTION_INFO_V1(plpython_call_handler);
180 /* most of the remaining of the declarations, all static
183 /* these should only be called once at the first call
184 * of plpython_call_handler. initialize the python interpreter
187 static void PLy_init_all(void);
188 static void PLy_init_interp(void);
189 static void PLy_init_plpy(void);
191 /* call PyErr_SetString with a vprint interface
194 PLy_exception_set(PyObject *, const char *,...)
195 __attribute__((format(printf, 2, 3)));
197 /* Get the innermost python procedure called from the backend.
199 static char *PLy_procedure_name(PLyProcedure *);
201 /* some utility functions
203 static void PLy_elog(int, const char *,...);
204 static char *PLy_traceback(int *);
205 static char *PLy_vprintf(const char *fmt, va_list ap);
206 static char *PLy_printf(const char *fmt,...);
208 static void *PLy_malloc(size_t);
209 static void *PLy_realloc(void *, size_t);
210 static void PLy_free(void *);
212 /* sub handlers for functions and triggers
214 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
215 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
217 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
218 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
220 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
221 TriggerData *, HeapTuple);
223 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
225 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
228 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
230 HeapTuple procTup, char *key);
232 static void PLy_procedure_compile(PLyProcedure *, const char *);
233 static char *PLy_procedure_munge_source(const char *, const char *);
234 static void PLy_procedure_delete(PLyProcedure *);
236 static void PLy_typeinfo_init(PLyTypeInfo *);
237 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
238 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
239 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
240 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
241 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
242 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
243 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
245 /* conversion functions
247 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
248 static PyObject *PLyBool_FromString(const char *);
249 static PyObject *PLyFloat_FromString(const char *);
250 static PyObject *PLyInt_FromString(const char *);
251 static PyObject *PLyLong_FromString(const char *);
252 static PyObject *PLyString_FromString(const char *);
257 static int PLy_first_call = 1;
260 * Last function called by postgres backend
262 * XXX replace this with errcontext mechanism
264 static PLyProcedure *PLy_last_procedure = NULL;
267 * When a callback from Python into PG incurs an error, we temporarily store
268 * the error information here, and return NULL to the Python interpreter.
269 * Any further callback attempts immediately fail, and when the Python
270 * interpreter returns to the calling function, we re-throw the error (even if
271 * Python thinks it trapped the error and doesn't return NULL). Eventually
272 * this ought to be improved to let Python code really truly trap the error,
273 * but that's more of a change from the pre-8.0 semantics than I have time for
274 * now --- it will only be possible if the callback query is executed inside a
277 static ErrorData *PLy_error_in_progress = NULL;
279 static PyObject *PLy_interp_globals = NULL;
280 static PyObject *PLy_interp_safe_globals = NULL;
281 static PyObject *PLy_procedure_cache = NULL;
285 static PyObject *PLy_exc_error = NULL;
286 static PyObject *PLy_exc_fatal = NULL;
287 static PyObject *PLy_exc_spi_error = NULL;
289 /* some globals for the python module
291 static char PLy_plan_doc[] = {
292 "Store a PostgreSQL plan"
295 static char PLy_result_doc[] = {
296 "Results of a PostgreSQL query"
301 * the function definitions
305 * This routine is a crock, and so is everyplace that calls it. The problem
306 * is that the cached form of plpython functions/queries is allocated permanently
307 * (mostly via malloc()) and never released until backend exit. Subsidiary
308 * data structures such as fmgr info records therefore must live forever
309 * as well. A better implementation would store all this stuff in a per-
310 * function memory context that could be reclaimed at need. In the meantime,
311 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
312 * it might allocate, and whatever the eventual function might allocate using
313 * fn_mcxt, will live forever too.
316 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
318 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
322 plpython_call_handler(PG_FUNCTION_ARGS)
325 PLyProcedure *volatile proc = NULL;
329 if (SPI_connect() != SPI_OK_CONNECT)
330 elog(ERROR, "could not connect to SPI manager");
334 if (CALLED_AS_TRIGGER(fcinfo))
336 TriggerData *tdata = (TriggerData *) fcinfo->context;
339 proc = PLy_procedure_get(fcinfo,
340 RelationGetRelid(tdata->tg_relation));
341 trv = PLy_trigger_handler(fcinfo, proc);
342 retval = PointerGetDatum(trv);
346 proc = PLy_procedure_get(fcinfo, InvalidOid);
347 retval = PLy_function_handler(fcinfo, proc);
354 /* note: Py_DECREF needs braces around it, as of 2003/08 */
367 /* trigger and function sub handlers
369 * the python function is expected to return Py_None if the tuple is
370 * acceptable and unmodified. Otherwise it should return a PyString
371 * object who's value is SKIP, or MODIFY. SKIP means don't perform
372 * this action. MODIFY means the tuple has been modified, so update
373 * tuple and perform action. SKIP and MODIFY assume the trigger fires
374 * BEFORE the event and is ROW level. postgres expects the function
375 * to take no arguments and return an argument of type trigger.
378 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
381 PyObject *volatile plargs = NULL;
382 PyObject *volatile plrv = NULL;
386 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
387 plrv = PLy_procedure_call(proc, "TD", plargs);
389 Assert(plrv != NULL);
390 Assert(!PLy_error_in_progress);
393 * Disconnect from SPI manager
395 if (SPI_finish() != SPI_OK_FINISH)
396 elog(ERROR, "SPI_finish failed");
399 * return of None means we're happy with the tuple
405 if (!PyString_Check(plrv))
406 elog(ERROR, "expected trigger to return None or a String");
408 srv = PyString_AsString(plrv);
409 if (pg_strcasecmp(srv, "SKIP") == 0)
411 else if (pg_strcasecmp(srv, "MODIFY") == 0)
413 TriggerData *tdata = (TriggerData *) fcinfo->context;
415 if ((TRIGGER_FIRED_BY_INSERT(tdata->tg_event)) ||
416 (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event)))
417 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
419 elog(WARNING, "ignoring modified tuple in DELETE trigger");
421 else if (pg_strcasecmp(srv, "OK") != 0)
424 * hmmm, perhaps they only read the pltcl page, not a
425 * surprising thing since i've written no documentation,
426 * so accept a belated OK
428 elog(ERROR, "expected return to be \"SKIP\" or \"MODIFY\"");
448 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
451 PyObject *volatile plntup;
452 PyObject *volatile plkeys;
453 PyObject *volatile platt;
454 PyObject *volatile plval;
455 PyObject *volatile plstr;
461 int *volatile modattrs;
462 Datum *volatile modvalues;
463 char *volatile modnulls;
466 plntup = plkeys = platt = plval = plstr = NULL;
473 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
474 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
475 if (!PyDict_Check(plntup))
476 elog(ERROR, "TD[\"new\"] is not a dictionary object");
479 plkeys = PyDict_Keys(plntup);
480 natts = PyList_Size(plkeys);
482 modattrs = (int *) palloc(natts * sizeof(int));
483 modvalues = (Datum *) palloc(natts * sizeof(Datum));
484 modnulls = (char *) palloc(natts * sizeof(char));
486 tupdesc = tdata->tg_relation->rd_att;
488 for (i = 0; i < natts; i++)
492 platt = PyList_GetItem(plkeys, i);
493 if (!PyString_Check(platt))
494 elog(ERROR, "attribute name is not a string");
495 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
496 if (attn == SPI_ERROR_NOATTRIBUTE)
497 elog(ERROR, "invalid attribute \"%s\" in tuple",
498 PyString_AsString(platt));
501 plval = PyDict_GetItem(plntup, platt);
503 elog(FATAL, "python interpreter is probably corrupted");
509 if (plval != Py_None && !tupdesc->attrs[atti]->attisdropped)
511 plstr = PyObject_Str(plval);
512 src = PyString_AsString(plstr);
514 modvalues[i] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
515 CStringGetDatum(src),
516 ObjectIdGetDatum(proc->result.out.r.atts[atti].typioparam),
517 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
525 modvalues[i] = (Datum) 0;
533 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
534 modattrs, modvalues, modnulls);
536 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
568 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
570 TriggerData *tdata = (TriggerData *) fcinfo->context;
579 PyObject *volatile pltdata = NULL;
584 pltdata = PyDict_New();
586 PLy_elog(ERROR, "could not build arguments for trigger procedure");
588 pltname = PyString_FromString(tdata->tg_trigger->tgname);
589 PyDict_SetItemString(pltdata, "name", pltname);
592 stroid = DatumGetCString(DirectFunctionCall1(oidout,
593 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
594 pltrelid = PyString_FromString(stroid);
595 PyDict_SetItemString(pltdata, "relid", pltrelid);
599 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
600 pltwhen = PyString_FromString("BEFORE");
601 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
602 pltwhen = PyString_FromString("AFTER");
605 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
606 pltwhen = NULL; /* keep compiler quiet */
608 PyDict_SetItemString(pltdata, "when", pltwhen);
611 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
613 pltlevel = PyString_FromString("ROW");
614 PyDict_SetItemString(pltdata, "level", pltlevel);
617 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
619 pltevent = PyString_FromString("INSERT");
621 PyDict_SetItemString(pltdata, "old", Py_None);
622 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
623 tdata->tg_relation->rd_att);
624 PyDict_SetItemString(pltdata, "new", pytnew);
626 *rv = tdata->tg_trigtuple;
628 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
630 pltevent = PyString_FromString("DELETE");
632 PyDict_SetItemString(pltdata, "new", Py_None);
633 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
634 tdata->tg_relation->rd_att);
635 PyDict_SetItemString(pltdata, "old", pytold);
637 *rv = tdata->tg_trigtuple;
639 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
641 pltevent = PyString_FromString("UPDATE");
643 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
644 tdata->tg_relation->rd_att);
645 PyDict_SetItemString(pltdata, "new", pytnew);
647 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
648 tdata->tg_relation->rd_att);
649 PyDict_SetItemString(pltdata, "old", pytold);
651 *rv = tdata->tg_newtuple;
655 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
656 pltevent = NULL; /* keep compiler quiet */
659 PyDict_SetItemString(pltdata, "event", pltevent);
662 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
664 pltlevel = PyString_FromString("STATEMENT");
665 PyDict_SetItemString(pltdata, "level", pltlevel);
668 PyDict_SetItemString(pltdata, "old", Py_None);
669 PyDict_SetItemString(pltdata, "new", Py_None);
672 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
673 pltevent = PyString_FromString("INSERT");
674 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
675 pltevent = PyString_FromString("DELETE");
676 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
677 pltevent = PyString_FromString("UPDATE");
680 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
681 pltevent = NULL; /* keep compiler quiet */
684 PyDict_SetItemString(pltdata, "event", pltevent);
688 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
690 if (tdata->tg_trigger->tgnargs)
698 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
699 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
701 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
704 * stolen, don't Py_DECREF
706 PyList_SetItem(pltargs, i, pltarg);
714 PyDict_SetItemString(pltdata, "args", pltargs);
729 /* function handler and friends
732 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
735 PyObject *volatile plargs = NULL;
736 PyObject *volatile plrv = NULL;
737 PyObject *volatile plrv_so = NULL;
742 plargs = PLy_function_build_args(fcinfo, proc);
743 plrv = PLy_procedure_call(proc, "args", plargs);
745 Assert(plrv != NULL);
746 Assert(!PLy_error_in_progress);
749 * Disconnect from SPI manager and then create the return values
750 * datum (if the input function does a palloc for it this must not
751 * be allocated in the SPI memory context because SPI_finish would
754 if (SPI_finish() != SPI_OK_FINISH)
755 elog(ERROR, "SPI_finish failed");
758 * convert the python PyObject to a postgresql Datum
762 fcinfo->isnull = true;
767 fcinfo->isnull = false;
768 plrv_so = PyObject_Str(plrv);
769 plrv_sc = PyString_AsString(plrv_so);
770 rv = FunctionCall3(&proc->result.out.d.typfunc,
771 PointerGetDatum(plrv_sc),
772 ObjectIdGetDatum(proc->result.out.d.typioparam),
795 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
798 PLyProcedure *current;
800 current = PLy_last_procedure;
801 PLy_last_procedure = proc;
802 PyDict_SetItemString(proc->globals, kargs, vargs);
803 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
804 proc->globals, proc->globals);
805 PLy_last_procedure = current;
808 * If there was an error in a PG callback, propagate that no matter
809 * what Python claims about its success.
811 if (PLy_error_in_progress)
813 ErrorData *edata = PLy_error_in_progress;
815 PLy_error_in_progress = NULL;
819 if ((rv == NULL) || (PyErr_Occurred()))
822 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
829 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
831 PyObject *volatile arg = NULL;
832 PyObject *volatile args = NULL;
837 args = PyList_New(proc->nargs);
838 for (i = 0; i < proc->nargs; i++)
840 if (proc->args[i].is_rowtype > 0)
842 if (fcinfo->argnull[i])
850 HeapTupleData tmptup;
852 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
853 /* Extract rowtype info and find a tupdesc */
854 tupType = HeapTupleHeaderGetTypeId(td);
855 tupTypmod = HeapTupleHeaderGetTypMod(td);
856 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
858 /* Set up I/O funcs if not done yet */
859 if (proc->args[i].is_rowtype != 1)
860 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
862 /* Build a temporary HeapTuple control structure */
863 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
866 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
871 if (fcinfo->argnull[i])
878 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
880 ObjectIdGetDatum(proc->args[i].in.d.typioparam),
882 ct = DatumGetCString(dt);
883 arg = (proc->args[i].in.d.func) (ct);
895 * FIXME -- error check this
897 PyList_SetItem(args, i, arg);
914 * PLyProcedure functions
917 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
918 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
919 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
922 static PLyProcedure *
923 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
929 PLyProcedure *proc = NULL;
932 fn_oid = fcinfo->flinfo->fn_oid;
933 procTup = SearchSysCache(PROCOID,
934 ObjectIdGetDatum(fn_oid),
936 if (!HeapTupleIsValid(procTup))
937 elog(ERROR, "cache lookup failed for function %u", fn_oid);
939 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
940 if ((rv >= sizeof(key)) || (rv < 0))
941 elog(ERROR, "key too long");
943 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
948 if (!PyCObject_Check(plproc))
949 elog(FATAL, "expected a PyCObject, didn't get one");
951 proc = PyCObject_AsVoidPtr(plproc);
952 if (proc->me != plproc)
953 elog(FATAL, "proc->me != plproc");
954 /* did we find an up-to-date cache entry? */
955 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
956 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
964 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
966 ReleaseSysCache(procTup);
971 static PLyProcedure *
972 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
973 HeapTuple procTup, char *key)
975 char procName[NAMEDATALEN + 256];
977 Form_pg_proc procStruct;
978 PLyProcedure *volatile proc;
979 char *volatile procSource = NULL;
985 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
987 if (OidIsValid(tgreloid))
988 rv = snprintf(procName, sizeof(procName),
989 "__plpython_procedure_%s_%u_trigger_%u",
990 NameStr(procStruct->proname),
991 fcinfo->flinfo->fn_oid,
994 rv = snprintf(procName, sizeof(procName),
995 "__plpython_procedure_%s_%u",
996 NameStr(procStruct->proname),
997 fcinfo->flinfo->fn_oid);
998 if ((rv >= sizeof(procName)) || (rv < 0))
999 elog(ERROR, "procedure name would overrun buffer");
1001 proc = PLy_malloc(sizeof(PLyProcedure));
1002 proc->proname = PLy_malloc(strlen(NameStr(procStruct->proname)) + 1);
1003 strcpy(proc->proname, NameStr(procStruct->proname));
1004 proc->pyname = PLy_malloc(strlen(procName) + 1);
1005 strcpy(proc->pyname, procName);
1006 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1007 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1008 PLy_typeinfo_init(&proc->result);
1009 for (i = 0; i < FUNC_MAX_ARGS; i++)
1010 PLy_typeinfo_init(&proc->args[i]);
1012 proc->code = proc->statics = NULL;
1013 proc->globals = proc->me = NULL;
1018 * get information required for output conversion of the return
1019 * value, but only if this isn't a trigger.
1021 if (!CALLED_AS_TRIGGER(fcinfo))
1023 HeapTuple rvTypeTup;
1024 Form_pg_type rvTypeStruct;
1026 rvTypeTup = SearchSysCache(TYPEOID,
1027 ObjectIdGetDatum(procStruct->prorettype),
1029 if (!HeapTupleIsValid(rvTypeTup))
1030 elog(ERROR, "cache lookup failed for type %u",
1031 procStruct->prorettype);
1033 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1034 if (rvTypeStruct->typtype != 'c')
1035 PLy_output_datum_func(&proc->result, rvTypeTup);
1038 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1039 errmsg("tuple return types are not supported yet")));
1041 ReleaseSysCache(rvTypeTup);
1046 * input/output conversion for trigger tuples. use the result
1047 * TypeInfo variable to store the tuple conversion info.
1049 TriggerData *tdata = (TriggerData *) fcinfo->context;
1051 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1052 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1056 * now get information required for input conversion of the
1057 * procedures arguments.
1059 proc->nargs = fcinfo->nargs;
1060 for (i = 0; i < fcinfo->nargs; i++)
1062 HeapTuple argTypeTup;
1063 Form_pg_type argTypeStruct;
1065 argTypeTup = SearchSysCache(TYPEOID,
1066 ObjectIdGetDatum(procStruct->proargtypes[i]),
1068 if (!HeapTupleIsValid(argTypeTup))
1069 elog(ERROR, "cache lookup failed for type %u",
1070 procStruct->proargtypes[i]);
1071 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1073 if (argTypeStruct->typtype != 'c')
1074 PLy_input_datum_func(&(proc->args[i]),
1075 procStruct->proargtypes[i],
1078 proc->args[i].is_rowtype = 2; /* still need to set I/O
1081 ReleaseSysCache(argTypeTup);
1086 * get the text of the function.
1088 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1089 Anum_pg_proc_prosrc, &isnull);
1091 elog(ERROR, "null prosrc");
1092 procSource = DatumGetCString(DirectFunctionCall1(textout,
1095 PLy_procedure_compile(proc, procSource);
1099 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1100 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1104 PLy_procedure_delete(proc);
1116 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1118 PyObject *crv = NULL;
1121 proc->globals = PyDict_Copy(PLy_interp_globals);
1124 * SD is private preserved data between calls GD is global data shared
1127 proc->statics = PyDict_New();
1128 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1131 * insert the function code into the interpreter
1133 msrc = PLy_procedure_munge_source(proc->pyname, src);
1134 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1137 if ((crv != NULL) && (!PyErr_Occurred()))
1140 char call[NAMEDATALEN + 256];
1145 * compile a call to the function
1147 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1148 if ((clen < 0) || (clen >= sizeof(call)))
1149 elog(ERROR, "string would overflow buffer");
1150 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1151 if ((proc->code != NULL) && (!PyErr_Occurred()))
1157 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1161 PLy_procedure_munge_source(const char *name, const char *src)
1170 * room for function source and the def statement
1172 mlen = (strlen(src) * 2) + strlen(name) + 16;
1174 mrc = PLy_malloc(mlen);
1175 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1176 Assert(plen >= 0 && plen < mlen);
1195 if (mp > (mrc + mlen))
1196 elog(FATAL, "buffer overrun in PLy_munge_source");
1202 PLy_procedure_delete(PLyProcedure * proc)
1206 Py_XDECREF(proc->code);
1207 Py_XDECREF(proc->statics);
1208 Py_XDECREF(proc->globals);
1209 Py_XDECREF(proc->me);
1211 PLy_free(proc->proname);
1213 PLy_free(proc->pyname);
1214 for (i = 0; i < proc->nargs; i++)
1215 if (proc->args[i].is_rowtype == 1)
1217 if (proc->args[i].in.r.atts)
1218 PLy_free(proc->args[i].in.r.atts);
1219 if (proc->args[i].out.r.atts)
1220 PLy_free(proc->args[i].out.r.atts);
1224 /* conversion functions. remember output from python is
1225 * input to postgresql, and vis versa.
1228 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1232 if (arg->is_rowtype == 0)
1233 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1235 arg->is_rowtype = 1;
1236 arg->in.r.natts = desc->natts;
1237 arg->in.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1239 for (i = 0; i < desc->natts; i++)
1243 if (desc->attrs[i]->attisdropped)
1246 typeTup = SearchSysCache(TYPEOID,
1247 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1249 if (!HeapTupleIsValid(typeTup))
1250 elog(ERROR, "cache lookup failed for type %u",
1251 desc->attrs[i]->atttypid);
1253 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1254 desc->attrs[i]->atttypid,
1257 ReleaseSysCache(typeTup);
1262 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1266 if (arg->is_rowtype == 0)
1267 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1269 arg->is_rowtype = 1;
1270 arg->out.r.natts = desc->natts;
1271 arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1273 for (i = 0; i < desc->natts; i++)
1277 if (desc->attrs[i]->attisdropped)
1280 typeTup = SearchSysCache(TYPEOID,
1281 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1283 if (!HeapTupleIsValid(typeTup))
1284 elog(ERROR, "cache lookup failed for type %u",
1285 desc->attrs[i]->atttypid);
1287 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1289 ReleaseSysCache(typeTup);
1294 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1296 if (arg->is_rowtype > 0)
1297 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1298 arg->is_rowtype = 0;
1299 PLy_output_datum_func2(&(arg->out.d), typeTup);
1303 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1305 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1307 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1308 arg->typioparam = getTypeIOParam(typeTup);
1309 arg->typbyval = typeStruct->typbyval;
1313 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1315 if (arg->is_rowtype > 0)
1316 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1317 arg->is_rowtype = 0;
1318 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1322 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1324 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1326 /* Get the type's conversion information */
1327 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1328 arg->typioparam = getTypeIOParam(typeTup);
1329 arg->typbyval = typeStruct->typbyval;
1331 /* Determine which kind of Python object we will convert to */
1335 arg->func = PLyBool_FromString;
1340 arg->func = PLyFloat_FromString;
1344 arg->func = PLyInt_FromString;
1347 arg->func = PLyLong_FromString;
1350 arg->func = PLyString_FromString;
1356 PLy_typeinfo_init(PLyTypeInfo * arg)
1358 arg->is_rowtype = -1;
1359 arg->in.r.natts = arg->out.r.natts = 0;
1360 arg->in.r.atts = NULL;
1361 arg->out.r.atts = NULL;
1365 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1367 if (arg->is_rowtype == 1)
1370 PLy_free(arg->in.r.atts);
1371 if (arg->out.r.atts)
1372 PLy_free(arg->out.r.atts);
1376 /* assumes that a bool is always returned as a 't' or 'f'
1379 PLyBool_FromString(const char *src)
1382 return PyInt_FromLong(1);
1383 return PyInt_FromLong(0);
1387 PLyFloat_FromString(const char *src)
1393 v = strtod(src, &eptr);
1394 if ((*eptr != '\0') || (errno))
1396 return PyFloat_FromDouble(v);
1400 PLyInt_FromString(const char *src)
1406 v = strtol(src, &eptr, 0);
1407 if ((*eptr != '\0') || (errno))
1409 return PyInt_FromLong(v);
1413 PLyLong_FromString(const char *src)
1415 return PyLong_FromString((char *) src, NULL, 0);
1419 PLyString_FromString(const char *src)
1421 return PyString_FromString(src);
1425 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1427 PyObject *volatile dict;
1430 if (info->is_rowtype != 1)
1431 elog(ERROR, "PLyTypeInfo structure describes a datum");
1433 dict = PyDict_New();
1435 PLy_elog(ERROR, "could not create tuple dictionary");
1439 for (i = 0; i < info->in.r.natts; i++)
1448 if (desc->attrs[i]->attisdropped)
1451 key = NameStr(desc->attrs[i]->attname);
1452 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1454 if ((is_null) || (info->in.r.atts[i].func == NULL))
1455 PyDict_SetItemString(dict, key, Py_None);
1458 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1460 ObjectIdGetDatum(info->in.r.atts[i].typioparam),
1461 Int32GetDatum(desc->attrs[i]->atttypmod));
1462 vsrc = DatumGetCString(vdat);
1465 * no exceptions allowed
1467 value = info->in.r.atts[i].func(vsrc);
1469 PyDict_SetItemString(dict, key, value);
1484 /* initialization, some python variables function declared here
1487 /* interface to postgresql elog
1489 static PyObject *PLy_debug(PyObject *, PyObject *);
1490 static PyObject *PLy_log(PyObject *, PyObject *);
1491 static PyObject *PLy_info(PyObject *, PyObject *);
1492 static PyObject *PLy_notice(PyObject *, PyObject *);
1493 static PyObject *PLy_warning(PyObject *, PyObject *);
1494 static PyObject *PLy_error(PyObject *, PyObject *);
1495 static PyObject *PLy_fatal(PyObject *, PyObject *);
1497 /* PLyPlanObject, PLyResultObject and SPI interface
1499 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1500 static PyObject *PLy_plan_new(void);
1501 static void PLy_plan_dealloc(PyObject *);
1502 static PyObject *PLy_plan_getattr(PyObject *, char *);
1503 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1505 static PyObject *PLy_result_new(void);
1506 static void PLy_result_dealloc(PyObject *);
1507 static PyObject *PLy_result_getattr(PyObject *, char *);
1510 /* Appear to be unused */
1511 static PyObject *PLy_result_fetch(PyObject *, PyObject *);
1512 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1513 static PyObject *PLy_result_status(PyObject *, PyObject *);
1515 static int PLy_result_length(PyObject *);
1516 static PyObject *PLy_result_item(PyObject *, int);
1517 static PyObject *PLy_result_slice(PyObject *, int, int);
1518 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1519 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1522 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1523 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1524 static PyObject *PLy_spi_execute_query(char *query, int limit);
1525 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, int);
1526 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1529 static PyTypeObject PLy_PlanType = {
1530 PyObject_HEAD_INIT(NULL)
1532 "PLyPlan", /* tp_name */
1533 sizeof(PLyPlanObject), /* tp_size */
1534 0, /* tp_itemsize */
1539 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1541 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1545 0, /* tp_as_number */
1546 0, /* tp_as_sequence */
1547 0, /* tp_as_mapping */
1551 0, /* tp_getattro */
1552 0, /* tp_setattro */
1553 0, /* tp_as_buffer */
1555 PLy_plan_doc, /* tp_doc */
1558 static PyMethodDef PLy_plan_methods[] = {
1559 {"status", (PyCFunction) PLy_plan_status, METH_VARARGS, NULL},
1560 {NULL, NULL, 0, NULL}
1564 static PySequenceMethods PLy_result_as_sequence = {
1565 (inquiry) PLy_result_length, /* sq_length */
1566 (binaryfunc) 0, /* sq_concat */
1567 (intargfunc) 0, /* sq_repeat */
1568 (intargfunc) PLy_result_item, /* sq_item */
1569 (intintargfunc) PLy_result_slice, /* sq_slice */
1570 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1571 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1574 static PyTypeObject PLy_ResultType = {
1575 PyObject_HEAD_INIT(NULL)
1577 "PLyResult", /* tp_name */
1578 sizeof(PLyResultObject), /* tp_size */
1579 0, /* tp_itemsize */
1584 (destructor) PLy_result_dealloc, /* tp_dealloc */
1586 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1590 0, /* tp_as_number */
1591 &PLy_result_as_sequence, /* tp_as_sequence */
1592 0, /* tp_as_mapping */
1596 0, /* tp_getattro */
1597 0, /* tp_setattro */
1598 0, /* tp_as_buffer */
1600 PLy_result_doc, /* tp_doc */
1604 /* Appear to be unused */
1605 static PyMethodDef PLy_result_methods[] = {
1606 {"fetch", (PyCFunction) PLy_result_fetch, METH_VARARGS, NULL,},
1607 {"nrows", (PyCFunction) PLy_result_nrows, METH_VARARGS, NULL},
1608 {"status", (PyCFunction) PLy_result_status, METH_VARARGS, NULL},
1609 {NULL, NULL, 0, NULL}
1613 static PyMethodDef PLy_methods[] = {
1617 {"debug", PLy_debug, METH_VARARGS, NULL},
1618 {"log", PLy_log, METH_VARARGS, NULL},
1619 {"info", PLy_info, METH_VARARGS, NULL},
1620 {"notice", PLy_notice, METH_VARARGS, NULL},
1621 {"warning", PLy_warning, METH_VARARGS, NULL},
1622 {"error", PLy_error, METH_VARARGS, NULL},
1623 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1626 * create a stored plan
1628 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1631 * execute a plan or query
1633 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1635 {NULL, NULL, 0, NULL}
1639 /* plan object methods
1646 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1654 return (PyObject *) ob;
1659 PLy_plan_dealloc(PyObject * arg)
1661 PLyPlanObject *ob = (PLyPlanObject *) arg;
1664 SPI_freeplan(ob->plan);
1666 PLy_free(ob->types);
1671 for (i = 0; i < ob->nargs; i++)
1672 PLy_typeinfo_dealloc(&ob->args[i]);
1681 PLy_plan_getattr(PyObject * self, char *name)
1683 return Py_FindMethod(PLy_plan_methods, self, name);
1687 PLy_plan_status(PyObject * self, PyObject * args)
1689 if (PyArg_ParseTuple(args, ""))
1693 /* return PyInt_FromLong(self->status); */
1695 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1701 /* result object methods
1705 PLy_result_new(void)
1707 PLyResultObject *ob;
1709 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1712 /* ob->tuples = NULL; */
1715 ob->status = Py_None;
1716 ob->nrows = PyInt_FromLong(-1);
1717 ob->rows = PyList_New(0);
1719 return (PyObject *) ob;
1723 PLy_result_dealloc(PyObject * arg)
1725 PLyResultObject *ob = (PLyResultObject *) arg;
1727 Py_XDECREF(ob->nrows);
1728 Py_XDECREF(ob->rows);
1729 Py_XDECREF(ob->status);
1735 PLy_result_getattr(PyObject * self, char *attr)
1741 /* Appear to be unused */
1743 PLy_result_fetch(PyObject * self, PyObject * args)
1749 PLy_result_nrows(PyObject * self, PyObject * args)
1751 PLyResultObject *ob = (PLyResultObject *) self;
1753 Py_INCREF(ob->nrows);
1758 PLy_result_status(PyObject * self, PyObject * args)
1760 PLyResultObject *ob = (PLyResultObject *) self;
1762 Py_INCREF(ob->status);
1768 PLy_result_length(PyObject * arg)
1770 PLyResultObject *ob = (PLyResultObject *) arg;
1772 return PyList_Size(ob->rows);
1776 PLy_result_item(PyObject * arg, int idx)
1779 PLyResultObject *ob = (PLyResultObject *) arg;
1781 rv = PyList_GetItem(ob->rows, idx);
1788 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1791 PLyResultObject *ob = (PLyResultObject *) arg;
1794 rv = PyList_SetItem(ob->rows, idx, item);
1799 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1802 PLyResultObject *ob = (PLyResultObject *) arg;
1804 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1812 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1815 PLyResultObject *ob = (PLyResultObject *) arg;
1817 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1824 PLy_spi_prepare(PyObject * self, PyObject * args)
1826 PLyPlanObject *plan;
1827 PyObject *list = NULL;
1828 PyObject *volatile optr = NULL;
1831 MemoryContext oldcontext;
1833 /* Can't execute more if we have an unhandled error */
1834 if (PLy_error_in_progress)
1836 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1840 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1842 PyErr_SetString(PLy_exc_spi_error,
1843 "Invalid arguments for plpy.prepare()");
1847 if ((list) && (!PySequence_Check(list)))
1849 PyErr_SetString(PLy_exc_spi_error,
1850 "Second argument in plpy.prepare() must be a sequence");
1854 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1857 oldcontext = CurrentMemoryContext;
1865 nargs = PySequence_Length(list);
1868 plan->nargs = nargs;
1869 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1870 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1871 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1874 * the other loop might throw an exception, if PLyTypeInfo
1875 * member isn't properly initialized the Py_DECREF(plan)
1878 for (i = 0; i < nargs; i++)
1880 PLy_typeinfo_init(&plan->args[i]);
1881 plan->values[i] = (Datum) NULL;
1884 for (i = 0; i < nargs; i++)
1888 Form_pg_type typeStruct;
1890 optr = PySequence_GetItem(list, i);
1891 if (!PyString_Check(optr))
1892 elog(ERROR, "Type names must be strings.");
1893 sptr = PyString_AsString(optr);
1896 * XXX should extend this to allow qualified type
1899 typeTup = typenameType(makeTypeName(sptr));
1901 optr = NULL; /* this is important */
1903 plan->types[i] = HeapTupleGetOid(typeTup);
1904 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1905 if (typeStruct->typtype != 'c')
1906 PLy_output_datum_func(&plan->args[i], typeTup);
1908 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
1909 ReleaseSysCache(typeTup);
1914 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1915 if (plan->plan == NULL)
1916 elog(ERROR, "SPI_prepare failed: %s",
1917 SPI_result_code_string(SPI_result));
1919 /* transfer plan from procCxt to topCxt */
1920 tmpplan = plan->plan;
1921 plan->plan = SPI_saveplan(tmpplan);
1922 SPI_freeplan(tmpplan);
1923 if (plan->plan == NULL)
1924 elog(ERROR, "SPI_saveplan failed: %s",
1925 SPI_result_code_string(SPI_result));
1929 MemoryContextSwitchTo(oldcontext);
1930 PLy_error_in_progress = CopyErrorData();
1934 if (!PyErr_Occurred())
1935 PyErr_SetString(PLy_exc_spi_error,
1936 "Unknown error in PLy_spi_prepare");
1937 /* XXX this oughta be replaced with errcontext mechanism */
1938 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
1943 return (PyObject *) plan;
1946 /* execute(query="select * from foo", limit=5)
1947 * execute(plan=plan, values=(foo, bar), limit=5)
1950 PLy_spi_execute(PyObject * self, PyObject * args)
1954 PyObject *list = NULL;
1957 /* Can't execute more if we have an unhandled error */
1958 if (PLy_error_in_progress)
1960 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1964 if (PyArg_ParseTuple(args, "s|i", &query, &limit))
1965 return PLy_spi_execute_query(query, limit);
1969 if ((PyArg_ParseTuple(args, "O|Oi", &plan, &list, &limit)) &&
1970 (is_PLyPlanObject(plan)))
1971 return PLy_spi_execute_plan(plan, list, limit);
1973 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
1978 PLy_spi_execute_plan(PyObject * ob, PyObject * list, int limit)
1983 PLyPlanObject *plan;
1985 MemoryContext oldcontext;
1989 if ((!PySequence_Check(list)) || (PyString_Check(list)))
1991 char *msg = "plpy.execute() takes a sequence as its second argument";
1993 PyErr_SetString(PLy_exc_spi_error, msg);
1996 nargs = PySequence_Length(list);
2001 plan = (PLyPlanObject *) ob;
2003 if (nargs != plan->nargs)
2007 PyObject *so = PyObject_Str(list);
2009 sv = PyString_AsString(so);
2010 PLy_exception_set(PLy_exc_spi_error,
2011 "Expected sequence of %d arguments, got %d. %s",
2012 plan->nargs, nargs, sv);
2018 oldcontext = CurrentMemoryContext;
2021 nulls = palloc(nargs * sizeof(char));
2023 for (i = 0; i < nargs; i++)
2029 elem = PySequence_GetItem(list, i);
2030 if (elem != Py_None)
2032 so = PyObject_Str(elem);
2033 sv = PyString_AsString(so);
2036 * FIXME -- if this elogs, we have Python reference leak
2039 FunctionCall3(&(plan->args[i].out.d.typfunc),
2040 CStringGetDatum(sv),
2041 ObjectIdGetDatum(plan->args[i].out.d.typioparam),
2052 plan->values[i] = (Datum) 0;
2057 rv = SPI_execp(plan->plan, plan->values, nulls, limit);
2063 MemoryContextSwitchTo(oldcontext);
2064 PLy_error_in_progress = CopyErrorData();
2068 * cleanup plan->values array
2070 for (i = 0; i < nargs; i++)
2072 if (!plan->args[i].out.d.typbyval &&
2073 (plan->values[i] != (Datum) NULL))
2075 pfree(DatumGetPointer(plan->values[i]));
2076 plan->values[i] = (Datum) NULL;
2080 if (!PyErr_Occurred())
2081 PyErr_SetString(PLy_exc_error,
2082 "Unknown error in PLy_spi_execute_plan");
2083 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2088 for (i = 0; i < nargs; i++)
2090 if (!plan->args[i].out.d.typbyval &&
2091 (plan->values[i] != (Datum) NULL))
2093 pfree(DatumGetPointer(plan->values[i]));
2094 plan->values[i] = (Datum) NULL;
2100 PLy_exception_set(PLy_exc_spi_error,
2101 "SPI_execp failed: %s",
2102 SPI_result_code_string(rv));
2106 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2110 PLy_spi_execute_query(char *query, int limit)
2113 MemoryContext oldcontext;
2115 oldcontext = CurrentMemoryContext;
2117 rv = SPI_exec(query, limit);
2120 MemoryContextSwitchTo(oldcontext);
2121 PLy_error_in_progress = CopyErrorData();
2123 if (!PyErr_Occurred())
2124 PyErr_SetString(PLy_exc_spi_error,
2125 "Unknown error in PLy_spi_execute_query");
2126 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2133 PLy_exception_set(PLy_exc_spi_error,
2134 "SPI_exec failed: %s",
2135 SPI_result_code_string(rv));
2139 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2143 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2145 PLyResultObject *result;
2146 MemoryContext oldcontext;
2148 result = (PLyResultObject *) PLy_result_new();
2149 Py_DECREF(result->status);
2150 result->status = PyInt_FromLong(status);
2152 if (status == SPI_OK_UTILITY)
2154 Py_DECREF(result->nrows);
2155 result->nrows = PyInt_FromLong(0);
2157 else if (status != SPI_OK_SELECT)
2159 Py_DECREF(result->nrows);
2160 result->nrows = PyInt_FromLong(rows);
2167 PLy_typeinfo_init(&args);
2168 Py_DECREF(result->nrows);
2169 result->nrows = PyInt_FromLong(rows);
2171 oldcontext = CurrentMemoryContext;
2176 Py_DECREF(result->rows);
2177 result->rows = PyList_New(rows);
2179 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2180 for (i = 0; i < rows; i++)
2182 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2185 PyList_SetItem(result->rows, i, row);
2187 PLy_typeinfo_dealloc(&args);
2189 SPI_freetuptable(tuptable);
2194 MemoryContextSwitchTo(oldcontext);
2195 PLy_error_in_progress = CopyErrorData();
2197 if (!PyErr_Occurred())
2198 PyErr_SetString(PLy_exc_error,
2199 "Unknown error in PLy_spi_execute_fetch_result");
2201 PLy_typeinfo_dealloc(&args);
2207 return (PyObject *) result;
2212 * language handler and interpreter initialization
2216 * plpython_init() - Initialize everything that can be
2217 * safely initialized during postmaster
2220 * DO NOT make this static --- it has to be callable by preload
2225 static volatile int init_active = 0;
2227 /* Do initialization only once */
2228 if (!PLy_first_call)
2232 elog(FATAL, "initialization of language module failed");
2238 if (PyErr_Occurred())
2239 PLy_elog(FATAL, "untrapped error in initialization");
2240 PLy_procedure_cache = PyDict_New();
2241 if (PLy_procedure_cache == NULL)
2242 PLy_elog(ERROR, "could not create procedure cache");
2250 /* Execute postmaster-startup safe initialization */
2255 * Any other initialization that must be done each time a new backend
2256 * starts -- currently none
2262 PLy_init_interp(void)
2266 mainmod = PyImport_AddModule("__main__");
2267 if ((mainmod == NULL) || (PyErr_Occurred()))
2268 PLy_elog(ERROR, "could not import \"__main__\" module.");
2270 PLy_interp_globals = PyModule_GetDict(mainmod);
2271 PLy_interp_safe_globals = PyDict_New();
2272 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2274 if ((PLy_interp_globals == NULL) || (PyErr_Occurred()))
2275 PLy_elog(ERROR, "could not initialize globals");
2288 * initialize plpy module
2290 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2291 plpy = Py_InitModule("plpy", PLy_methods);
2292 plpy_dict = PyModule_GetDict(plpy);
2294 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2296 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2297 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2298 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2299 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2300 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2301 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2304 * initialize main module, and add plpy
2306 main_mod = PyImport_AddModule("__main__");
2307 main_dict = PyModule_GetDict(main_mod);
2308 plpy_mod = PyImport_AddModule("plpy");
2309 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2310 if (PyErr_Occurred())
2311 elog(ERROR, "could not init plpy");
2314 /* the python interface to the elog function
2315 * don't confuse these with PLy_elog
2317 static PyObject *PLy_output(int, PyObject *, PyObject *);
2320 PLy_debug(PyObject * self, PyObject * args)
2322 return PLy_output(DEBUG2, self, args);
2326 PLy_log(PyObject * self, PyObject * args)
2328 return PLy_output(LOG, self, args);
2332 PLy_info(PyObject * self, PyObject * args)
2334 return PLy_output(INFO, self, args);
2338 PLy_notice(PyObject * self, PyObject * args)
2340 return PLy_output(NOTICE, self, args);
2344 PLy_warning(PyObject * self, PyObject * args)
2346 return PLy_output(WARNING, self, args);
2350 PLy_error(PyObject * self, PyObject * args)
2352 return PLy_output(ERROR, self, args);
2356 PLy_fatal(PyObject * self, PyObject * args)
2358 return PLy_output(FATAL, self, args);
2363 PLy_output(volatile int level, PyObject * self, PyObject * args)
2367 MemoryContext oldcontext;
2369 so = PyObject_Str(args);
2370 if ((so == NULL) || ((sv = PyString_AsString(so)) == NULL))
2373 sv = "Unable to parse error message in `plpy.elog'";
2376 oldcontext = CurrentMemoryContext;
2378 elog(level, "%s", sv);
2381 MemoryContextSwitchTo(oldcontext);
2382 PLy_error_in_progress = CopyErrorData();
2387 * returning NULL here causes the python interpreter to bail. when
2388 * control passes back to PLy_procedure_call, we check for PG
2389 * exceptions and re-throw the error.
2391 PyErr_SetString(PLy_exc_error, sv);
2399 * return a legal object so the interpreter will continue on its merry
2408 * Get the last procedure name called by the backend ( the innermost,
2409 * If a plpython procedure call calls the backend and the backend calls
2410 * another plpython procedure )
2412 * NB: this returns SQL name, not the internal Python procedure name
2416 PLy_procedure_name(PLyProcedure * proc)
2419 return "<unknown procedure>";
2420 return proc->proname;
2423 /* output a python traceback/exception via the postgresql elog
2424 * function. not pretty.
2427 PLy_exception_set(PyObject * exc, const char *fmt,...)
2433 vsnprintf(buf, sizeof(buf), fmt, ap);
2436 PyErr_SetString(exc, buf);
2439 /* Emit a PG error or notice, together with any available info about the
2440 * current Python error. This should be used to propagate Python errors
2444 PLy_elog(int elevel, const char *fmt,...)
2451 xmsg = PLy_traceback(&xlevel);
2454 emsg = PLy_vprintf(fmt, ap);
2460 (errmsg("plpython: %s", emsg),
2461 (xmsg) ? errdetail("%s", xmsg) : 0));
2478 PLy_traceback(int *xlevel)
2490 * get the current exception
2492 PyErr_Fetch(&e, &v, &tb);
2495 * oops, no exception, return
2503 PyErr_NormalizeException(&e, &v, &tb);
2505 eob = PyObject_Str(e);
2506 if ((v) && ((vob = PyObject_Str(v)) != NULL))
2507 vstr = PyString_AsString(vob);
2511 estr = PyString_AsString(eob);
2512 xstr = PLy_printf("%s: %s", estr, vstr);
2518 * intuit an appropriate error level for based on the exception type
2520 if ((PLy_exc_error) && (PyErr_GivenExceptionMatches(e, PLy_exc_error)))
2522 else if ((PLy_exc_fatal) && (PyErr_GivenExceptionMatches(e, PLy_exc_fatal)))
2531 PLy_printf(const char *fmt,...)
2537 emsg = PLy_vprintf(fmt, ap);
2543 PLy_vprintf(const char *fmt, va_list ap)
2550 blen = strlen(fmt) * 2;
2553 buf = PLy_malloc(blen * sizeof(char));
2557 bchar = vsnprintf(buf, blen, fmt, ap);
2558 if ((bchar > 0) && (bchar < blen))
2566 buf = PLy_realloc(buf, blen);
2572 /* python module code
2576 /* some dumb utility functions
2580 PLy_malloc(size_t bytes)
2582 void *ptr = malloc(bytes);
2586 (errcode(ERRCODE_OUT_OF_MEMORY),
2587 errmsg("out of memory")));
2592 PLy_realloc(void *optr, size_t bytes)
2594 void *nptr = realloc(optr, bytes);
2598 (errcode(ERRCODE_OUT_OF_MEMORY),
2599 errmsg("out of memory")));