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.62 2005/05/06 17:24:55 tgl 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/memutils.h"
56 #include "utils/syscache.h"
57 #include "utils/typcache.h"
62 /* convert Postgresql Datum or tuple into a PyObject.
63 * input to Python. Tuples are converted to dictionary
67 typedef PyObject *(*PLyDatumToObFunc) (const char *);
69 typedef struct PLyDatumToOb
71 PLyDatumToObFunc func;
77 typedef struct PLyTupleToOb
83 typedef union PLyTypeInput
89 /* convert PyObject to a Postgresql Datum or tuple.
92 typedef struct PLyObToDatum
99 typedef struct PLyObToTuple
105 typedef union PLyTypeOutput
111 /* all we need to move Postgresql data to Python objects,
114 typedef struct PLyTypeInfo
121 * is_rowtype can be: -1 not known yet (initial state) 0 scalar
122 * datatype 1 rowtype 2 rowtype, but I/O functions not set up yet
127 /* cached procedure data
129 typedef struct PLyProcedure
131 char *proname; /* SQL name of procedure */
132 char *pyname; /* Python name of procedure */
133 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 * Currently active plpython function
264 static PLyProcedure *PLy_curr_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 *save_curr_proc;
326 PLyProcedure *volatile proc = NULL;
330 if (SPI_connect() != SPI_OK_CONNECT)
331 elog(ERROR, "could not connect to SPI manager");
333 save_curr_proc = PLy_curr_procedure;
337 if (CALLED_AS_TRIGGER(fcinfo))
339 TriggerData *tdata = (TriggerData *) fcinfo->context;
342 proc = PLy_procedure_get(fcinfo,
343 RelationGetRelid(tdata->tg_relation));
344 PLy_curr_procedure = proc;
345 trv = PLy_trigger_handler(fcinfo, proc);
346 retval = PointerGetDatum(trv);
350 proc = PLy_procedure_get(fcinfo, InvalidOid);
351 PLy_curr_procedure = proc;
352 retval = PLy_function_handler(fcinfo, proc);
357 PLy_curr_procedure = save_curr_proc;
360 /* note: Py_DECREF needs braces around it, as of 2003/08 */
368 PLy_curr_procedure = save_curr_proc;
375 /* trigger and function sub handlers
377 * the python function is expected to return Py_None if the tuple is
378 * acceptable and unmodified. Otherwise it should return a PyString
379 * object who's value is SKIP, or MODIFY. SKIP means don't perform
380 * this action. MODIFY means the tuple has been modified, so update
381 * tuple and perform action. SKIP and MODIFY assume the trigger fires
382 * BEFORE the event and is ROW level. postgres expects the function
383 * to take no arguments and return an argument of type trigger.
386 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
389 PyObject *volatile plargs = NULL;
390 PyObject *volatile plrv = NULL;
394 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
395 plrv = PLy_procedure_call(proc, "TD", plargs);
397 Assert(plrv != NULL);
398 Assert(!PLy_error_in_progress);
401 * Disconnect from SPI manager
403 if (SPI_finish() != SPI_OK_FINISH)
404 elog(ERROR, "SPI_finish failed");
407 * return of None means we're happy with the tuple
413 if (!PyString_Check(plrv))
414 elog(ERROR, "expected trigger to return None or a String");
416 srv = PyString_AsString(plrv);
417 if (pg_strcasecmp(srv, "SKIP") == 0)
419 else if (pg_strcasecmp(srv, "MODIFY") == 0)
421 TriggerData *tdata = (TriggerData *) fcinfo->context;
423 if ((TRIGGER_FIRED_BY_INSERT(tdata->tg_event)) ||
424 (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event)))
425 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
427 elog(WARNING, "ignoring modified tuple in DELETE trigger");
429 else if (pg_strcasecmp(srv, "OK") != 0)
432 * hmmm, perhaps they only read the pltcl page, not a
433 * surprising thing since i've written no documentation,
434 * so accept a belated OK
436 elog(ERROR, "expected return to be \"SKIP\" or \"MODIFY\"");
456 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
459 PyObject *volatile plntup;
460 PyObject *volatile plkeys;
461 PyObject *volatile platt;
462 PyObject *volatile plval;
463 PyObject *volatile plstr;
469 int *volatile modattrs;
470 Datum *volatile modvalues;
471 char *volatile modnulls;
474 plntup = plkeys = platt = plval = plstr = NULL;
481 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
482 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
483 if (!PyDict_Check(plntup))
484 elog(ERROR, "TD[\"new\"] is not a dictionary object");
487 plkeys = PyDict_Keys(plntup);
488 natts = PyList_Size(plkeys);
490 modattrs = (int *) palloc(natts * sizeof(int));
491 modvalues = (Datum *) palloc(natts * sizeof(Datum));
492 modnulls = (char *) palloc(natts * sizeof(char));
494 tupdesc = tdata->tg_relation->rd_att;
496 for (i = 0; i < natts; i++)
500 platt = PyList_GetItem(plkeys, i);
501 if (!PyString_Check(platt))
502 elog(ERROR, "attribute name is not a string");
503 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
504 if (attn == SPI_ERROR_NOATTRIBUTE)
505 elog(ERROR, "invalid attribute \"%s\" in tuple",
506 PyString_AsString(platt));
509 plval = PyDict_GetItem(plntup, platt);
511 elog(FATAL, "python interpreter is probably corrupted");
517 if (plval != Py_None && !tupdesc->attrs[atti]->attisdropped)
519 plstr = PyObject_Str(plval);
520 src = PyString_AsString(plstr);
522 modvalues[i] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
523 CStringGetDatum(src),
524 ObjectIdGetDatum(proc->result.out.r.atts[atti].typioparam),
525 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
533 modvalues[i] = (Datum) 0;
541 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
542 modattrs, modvalues, modnulls);
544 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
576 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
578 TriggerData *tdata = (TriggerData *) fcinfo->context;
587 PyObject *volatile pltdata = NULL;
592 pltdata = PyDict_New();
594 PLy_elog(ERROR, "could not build arguments for trigger procedure");
596 pltname = PyString_FromString(tdata->tg_trigger->tgname);
597 PyDict_SetItemString(pltdata, "name", pltname);
600 stroid = DatumGetCString(DirectFunctionCall1(oidout,
601 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
602 pltrelid = PyString_FromString(stroid);
603 PyDict_SetItemString(pltdata, "relid", pltrelid);
607 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
608 pltwhen = PyString_FromString("BEFORE");
609 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
610 pltwhen = PyString_FromString("AFTER");
613 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
614 pltwhen = NULL; /* keep compiler quiet */
616 PyDict_SetItemString(pltdata, "when", pltwhen);
619 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
621 pltlevel = PyString_FromString("ROW");
622 PyDict_SetItemString(pltdata, "level", pltlevel);
625 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
627 pltevent = PyString_FromString("INSERT");
629 PyDict_SetItemString(pltdata, "old", Py_None);
630 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
631 tdata->tg_relation->rd_att);
632 PyDict_SetItemString(pltdata, "new", pytnew);
634 *rv = tdata->tg_trigtuple;
636 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
638 pltevent = PyString_FromString("DELETE");
640 PyDict_SetItemString(pltdata, "new", Py_None);
641 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
642 tdata->tg_relation->rd_att);
643 PyDict_SetItemString(pltdata, "old", pytold);
645 *rv = tdata->tg_trigtuple;
647 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
649 pltevent = PyString_FromString("UPDATE");
651 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
652 tdata->tg_relation->rd_att);
653 PyDict_SetItemString(pltdata, "new", pytnew);
655 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
656 tdata->tg_relation->rd_att);
657 PyDict_SetItemString(pltdata, "old", pytold);
659 *rv = tdata->tg_newtuple;
663 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
664 pltevent = NULL; /* keep compiler quiet */
667 PyDict_SetItemString(pltdata, "event", pltevent);
670 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
672 pltlevel = PyString_FromString("STATEMENT");
673 PyDict_SetItemString(pltdata, "level", pltlevel);
676 PyDict_SetItemString(pltdata, "old", Py_None);
677 PyDict_SetItemString(pltdata, "new", Py_None);
680 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
681 pltevent = PyString_FromString("INSERT");
682 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
683 pltevent = PyString_FromString("DELETE");
684 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
685 pltevent = PyString_FromString("UPDATE");
688 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
689 pltevent = NULL; /* keep compiler quiet */
692 PyDict_SetItemString(pltdata, "event", pltevent);
696 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
698 if (tdata->tg_trigger->tgnargs)
706 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
707 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
709 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
712 * stolen, don't Py_DECREF
714 PyList_SetItem(pltargs, i, pltarg);
722 PyDict_SetItemString(pltdata, "args", pltargs);
737 /* function handler and friends
740 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
743 PyObject *volatile plargs = NULL;
744 PyObject *volatile plrv = NULL;
745 PyObject *volatile plrv_so = NULL;
750 plargs = PLy_function_build_args(fcinfo, proc);
751 plrv = PLy_procedure_call(proc, "args", plargs);
753 Assert(plrv != NULL);
754 Assert(!PLy_error_in_progress);
757 * Disconnect from SPI manager and then create the return values
758 * datum (if the input function does a palloc for it this must not
759 * be allocated in the SPI memory context because SPI_finish would
762 if (SPI_finish() != SPI_OK_FINISH)
763 elog(ERROR, "SPI_finish failed");
766 * convert the python PyObject to a postgresql Datum
770 fcinfo->isnull = true;
775 fcinfo->isnull = false;
776 plrv_so = PyObject_Str(plrv);
777 plrv_sc = PyString_AsString(plrv_so);
778 rv = FunctionCall3(&proc->result.out.d.typfunc,
779 PointerGetDatum(plrv_sc),
780 ObjectIdGetDatum(proc->result.out.d.typioparam),
803 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
807 PyDict_SetItemString(proc->globals, kargs, vargs);
808 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
809 proc->globals, proc->globals);
812 * If there was an error in a PG callback, propagate that no matter
813 * what Python claims about its success.
815 if (PLy_error_in_progress)
817 ErrorData *edata = PLy_error_in_progress;
819 PLy_error_in_progress = NULL;
823 if ((rv == NULL) || (PyErr_Occurred()))
826 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
833 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
835 PyObject *volatile arg = NULL;
836 PyObject *volatile args = NULL;
841 args = PyList_New(proc->nargs);
842 for (i = 0; i < proc->nargs; i++)
844 if (proc->args[i].is_rowtype > 0)
846 if (fcinfo->argnull[i])
854 HeapTupleData tmptup;
856 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
857 /* Extract rowtype info and find a tupdesc */
858 tupType = HeapTupleHeaderGetTypeId(td);
859 tupTypmod = HeapTupleHeaderGetTypMod(td);
860 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
862 /* Set up I/O funcs if not done yet */
863 if (proc->args[i].is_rowtype != 1)
864 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
866 /* Build a temporary HeapTuple control structure */
867 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
870 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
875 if (fcinfo->argnull[i])
882 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
884 ObjectIdGetDatum(proc->args[i].in.d.typioparam),
886 ct = DatumGetCString(dt);
887 arg = (proc->args[i].in.d.func) (ct);
899 * FIXME -- error check this
901 PyList_SetItem(args, i, arg);
918 * PLyProcedure functions
921 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
922 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
923 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
926 static PLyProcedure *
927 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
933 PLyProcedure *proc = NULL;
936 fn_oid = fcinfo->flinfo->fn_oid;
937 procTup = SearchSysCache(PROCOID,
938 ObjectIdGetDatum(fn_oid),
940 if (!HeapTupleIsValid(procTup))
941 elog(ERROR, "cache lookup failed for function %u", fn_oid);
943 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
944 if ((rv >= sizeof(key)) || (rv < 0))
945 elog(ERROR, "key too long");
947 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
952 if (!PyCObject_Check(plproc))
953 elog(FATAL, "expected a PyCObject, didn't get one");
955 proc = PyCObject_AsVoidPtr(plproc);
956 if (proc->me != plproc)
957 elog(FATAL, "proc->me != plproc");
958 /* did we find an up-to-date cache entry? */
959 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
960 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
968 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
970 ReleaseSysCache(procTup);
975 static PLyProcedure *
976 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
977 HeapTuple procTup, char *key)
979 char procName[NAMEDATALEN + 256];
980 Form_pg_proc procStruct;
981 PLyProcedure *volatile proc;
982 char *volatile procSource = NULL;
988 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
990 if (OidIsValid(tgreloid))
991 rv = snprintf(procName, sizeof(procName),
992 "__plpython_procedure_%s_%u_trigger_%u",
993 NameStr(procStruct->proname),
994 fcinfo->flinfo->fn_oid,
997 rv = snprintf(procName, sizeof(procName),
998 "__plpython_procedure_%s_%u",
999 NameStr(procStruct->proname),
1000 fcinfo->flinfo->fn_oid);
1001 if ((rv >= sizeof(procName)) || (rv < 0))
1002 elog(ERROR, "procedure name would overrun buffer");
1004 proc = PLy_malloc(sizeof(PLyProcedure));
1005 proc->proname = PLy_malloc(strlen(NameStr(procStruct->proname)) + 1);
1006 strcpy(proc->proname, NameStr(procStruct->proname));
1007 proc->pyname = PLy_malloc(strlen(procName) + 1);
1008 strcpy(proc->pyname, procName);
1009 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1010 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1011 /* Remember if function is STABLE/IMMUTABLE */
1013 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1014 PLy_typeinfo_init(&proc->result);
1015 for (i = 0; i < FUNC_MAX_ARGS; i++)
1016 PLy_typeinfo_init(&proc->args[i]);
1018 proc->code = proc->statics = NULL;
1019 proc->globals = proc->me = NULL;
1024 * get information required for output conversion of the return
1025 * value, but only if this isn't a trigger.
1027 if (!CALLED_AS_TRIGGER(fcinfo))
1029 HeapTuple rvTypeTup;
1030 Form_pg_type rvTypeStruct;
1032 rvTypeTup = SearchSysCache(TYPEOID,
1033 ObjectIdGetDatum(procStruct->prorettype),
1035 if (!HeapTupleIsValid(rvTypeTup))
1036 elog(ERROR, "cache lookup failed for type %u",
1037 procStruct->prorettype);
1038 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1040 /* Disallow pseudotype result */
1041 if (rvTypeStruct->typtype == 'p')
1043 if (procStruct->prorettype == TRIGGEROID)
1045 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1046 errmsg("trigger functions may only be called as triggers")));
1049 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1050 errmsg("plpython functions cannot return type %s",
1051 format_type_be(procStruct->prorettype))));
1054 if (rvTypeStruct->typtype == 'c')
1056 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1057 errmsg("plpython functions cannot return tuples yet")));
1059 PLy_output_datum_func(&proc->result, rvTypeTup);
1061 ReleaseSysCache(rvTypeTup);
1066 * input/output conversion for trigger tuples. use the result
1067 * TypeInfo variable to store the tuple conversion info.
1069 TriggerData *tdata = (TriggerData *) fcinfo->context;
1071 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1072 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1076 * now get information required for input conversion of the
1077 * procedures arguments.
1079 proc->nargs = fcinfo->nargs;
1080 for (i = 0; i < fcinfo->nargs; i++)
1082 HeapTuple argTypeTup;
1083 Form_pg_type argTypeStruct;
1085 argTypeTup = SearchSysCache(TYPEOID,
1086 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1088 if (!HeapTupleIsValid(argTypeTup))
1089 elog(ERROR, "cache lookup failed for type %u",
1090 procStruct->proargtypes.values[i]);
1091 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1093 /* Disallow pseudotype argument */
1094 if (argTypeStruct->typtype == 'p')
1096 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1097 errmsg("plpython functions cannot take type %s",
1098 format_type_be(procStruct->proargtypes.values[i]))));
1100 if (argTypeStruct->typtype != 'c')
1101 PLy_input_datum_func(&(proc->args[i]),
1102 procStruct->proargtypes.values[i],
1105 proc->args[i].is_rowtype = 2; /* still need to set I/O
1108 ReleaseSysCache(argTypeTup);
1113 * get the text of the function.
1115 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1116 Anum_pg_proc_prosrc, &isnull);
1118 elog(ERROR, "null prosrc");
1119 procSource = DatumGetCString(DirectFunctionCall1(textout,
1122 PLy_procedure_compile(proc, procSource);
1126 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1127 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1131 PLy_procedure_delete(proc);
1143 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1145 PyObject *crv = NULL;
1148 proc->globals = PyDict_Copy(PLy_interp_globals);
1151 * SD is private preserved data between calls GD is global data shared
1154 proc->statics = PyDict_New();
1155 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1158 * insert the function code into the interpreter
1160 msrc = PLy_procedure_munge_source(proc->pyname, src);
1161 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1164 if ((crv != NULL) && (!PyErr_Occurred()))
1167 char call[NAMEDATALEN + 256];
1172 * compile a call to the function
1174 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1175 if ((clen < 0) || (clen >= sizeof(call)))
1176 elog(ERROR, "string would overflow buffer");
1177 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1178 if ((proc->code != NULL) && (!PyErr_Occurred()))
1184 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1188 PLy_procedure_munge_source(const char *name, const char *src)
1197 * room for function source and the def statement
1199 mlen = (strlen(src) * 2) + strlen(name) + 16;
1201 mrc = PLy_malloc(mlen);
1202 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1203 Assert(plen >= 0 && plen < mlen);
1210 if (*sp == '\r' && *(sp + 1) == '\n')
1213 if (*sp == '\n' || *sp == '\r')
1226 if (mp > (mrc + mlen))
1227 elog(FATAL, "buffer overrun in PLy_munge_source");
1233 PLy_procedure_delete(PLyProcedure * proc)
1237 Py_XDECREF(proc->code);
1238 Py_XDECREF(proc->statics);
1239 Py_XDECREF(proc->globals);
1240 Py_XDECREF(proc->me);
1242 PLy_free(proc->proname);
1244 PLy_free(proc->pyname);
1245 for (i = 0; i < proc->nargs; i++)
1246 if (proc->args[i].is_rowtype == 1)
1248 if (proc->args[i].in.r.atts)
1249 PLy_free(proc->args[i].in.r.atts);
1250 if (proc->args[i].out.r.atts)
1251 PLy_free(proc->args[i].out.r.atts);
1255 /* conversion functions. remember output from python is
1256 * input to postgresql, and vis versa.
1259 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1263 if (arg->is_rowtype == 0)
1264 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1266 arg->is_rowtype = 1;
1267 arg->in.r.natts = desc->natts;
1268 arg->in.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1270 for (i = 0; i < desc->natts; i++)
1274 if (desc->attrs[i]->attisdropped)
1277 typeTup = SearchSysCache(TYPEOID,
1278 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1280 if (!HeapTupleIsValid(typeTup))
1281 elog(ERROR, "cache lookup failed for type %u",
1282 desc->attrs[i]->atttypid);
1284 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1285 desc->attrs[i]->atttypid,
1288 ReleaseSysCache(typeTup);
1293 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1297 if (arg->is_rowtype == 0)
1298 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1300 arg->is_rowtype = 1;
1301 arg->out.r.natts = desc->natts;
1302 arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1304 for (i = 0; i < desc->natts; i++)
1308 if (desc->attrs[i]->attisdropped)
1311 typeTup = SearchSysCache(TYPEOID,
1312 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1314 if (!HeapTupleIsValid(typeTup))
1315 elog(ERROR, "cache lookup failed for type %u",
1316 desc->attrs[i]->atttypid);
1318 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1320 ReleaseSysCache(typeTup);
1325 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1327 if (arg->is_rowtype > 0)
1328 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1329 arg->is_rowtype = 0;
1330 PLy_output_datum_func2(&(arg->out.d), typeTup);
1334 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1336 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1338 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1339 arg->typioparam = getTypeIOParam(typeTup);
1340 arg->typbyval = typeStruct->typbyval;
1344 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1346 if (arg->is_rowtype > 0)
1347 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1348 arg->is_rowtype = 0;
1349 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1353 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1355 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1357 /* Get the type's conversion information */
1358 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1359 arg->typioparam = getTypeIOParam(typeTup);
1360 arg->typbyval = typeStruct->typbyval;
1362 /* Determine which kind of Python object we will convert to */
1366 arg->func = PLyBool_FromString;
1371 arg->func = PLyFloat_FromString;
1375 arg->func = PLyInt_FromString;
1378 arg->func = PLyLong_FromString;
1381 arg->func = PLyString_FromString;
1387 PLy_typeinfo_init(PLyTypeInfo * arg)
1389 arg->is_rowtype = -1;
1390 arg->in.r.natts = arg->out.r.natts = 0;
1391 arg->in.r.atts = NULL;
1392 arg->out.r.atts = NULL;
1396 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1398 if (arg->is_rowtype == 1)
1401 PLy_free(arg->in.r.atts);
1402 if (arg->out.r.atts)
1403 PLy_free(arg->out.r.atts);
1407 /* assumes that a bool is always returned as a 't' or 'f'
1410 PLyBool_FromString(const char *src)
1413 return PyInt_FromLong(1);
1414 return PyInt_FromLong(0);
1418 PLyFloat_FromString(const char *src)
1424 v = strtod(src, &eptr);
1425 if ((*eptr != '\0') || (errno))
1427 return PyFloat_FromDouble(v);
1431 PLyInt_FromString(const char *src)
1437 v = strtol(src, &eptr, 0);
1438 if ((*eptr != '\0') || (errno))
1440 return PyInt_FromLong(v);
1444 PLyLong_FromString(const char *src)
1446 return PyLong_FromString((char *) src, NULL, 0);
1450 PLyString_FromString(const char *src)
1452 return PyString_FromString(src);
1456 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1458 PyObject *volatile dict;
1461 if (info->is_rowtype != 1)
1462 elog(ERROR, "PLyTypeInfo structure describes a datum");
1464 dict = PyDict_New();
1466 PLy_elog(ERROR, "could not create tuple dictionary");
1470 for (i = 0; i < info->in.r.natts; i++)
1479 if (desc->attrs[i]->attisdropped)
1482 key = NameStr(desc->attrs[i]->attname);
1483 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1485 if ((is_null) || (info->in.r.atts[i].func == NULL))
1486 PyDict_SetItemString(dict, key, Py_None);
1489 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1491 ObjectIdGetDatum(info->in.r.atts[i].typioparam),
1492 Int32GetDatum(desc->attrs[i]->atttypmod));
1493 vsrc = DatumGetCString(vdat);
1496 * no exceptions allowed
1498 value = info->in.r.atts[i].func(vsrc);
1500 PyDict_SetItemString(dict, key, value);
1515 /* initialization, some python variables function declared here
1518 /* interface to postgresql elog
1520 static PyObject *PLy_debug(PyObject *, PyObject *);
1521 static PyObject *PLy_log(PyObject *, PyObject *);
1522 static PyObject *PLy_info(PyObject *, PyObject *);
1523 static PyObject *PLy_notice(PyObject *, PyObject *);
1524 static PyObject *PLy_warning(PyObject *, PyObject *);
1525 static PyObject *PLy_error(PyObject *, PyObject *);
1526 static PyObject *PLy_fatal(PyObject *, PyObject *);
1528 /* PLyPlanObject, PLyResultObject and SPI interface
1530 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1531 static PyObject *PLy_plan_new(void);
1532 static void PLy_plan_dealloc(PyObject *);
1533 static PyObject *PLy_plan_getattr(PyObject *, char *);
1534 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1536 static PyObject *PLy_result_new(void);
1537 static void PLy_result_dealloc(PyObject *);
1538 static PyObject *PLy_result_getattr(PyObject *, char *);
1539 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1540 static PyObject *PLy_result_status(PyObject *, PyObject *);
1541 static int PLy_result_length(PyObject *);
1542 static PyObject *PLy_result_item(PyObject *, int);
1543 static PyObject *PLy_result_slice(PyObject *, int, int);
1544 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1545 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1548 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1549 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1550 static PyObject *PLy_spi_execute_query(char *query, long limit);
1551 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1552 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1555 static PyTypeObject PLy_PlanType = {
1556 PyObject_HEAD_INIT(NULL)
1558 "PLyPlan", /* tp_name */
1559 sizeof(PLyPlanObject), /* tp_size */
1560 0, /* tp_itemsize */
1565 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1567 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1571 0, /* tp_as_number */
1572 0, /* tp_as_sequence */
1573 0, /* tp_as_mapping */
1577 0, /* tp_getattro */
1578 0, /* tp_setattro */
1579 0, /* tp_as_buffer */
1581 PLy_plan_doc, /* tp_doc */
1584 static PyMethodDef PLy_plan_methods[] = {
1585 {"status", PLy_plan_status, METH_VARARGS, NULL},
1586 {NULL, NULL, 0, NULL}
1590 static PySequenceMethods PLy_result_as_sequence = {
1591 (inquiry) PLy_result_length, /* sq_length */
1592 (binaryfunc) 0, /* sq_concat */
1593 (intargfunc) 0, /* sq_repeat */
1594 (intargfunc) PLy_result_item, /* sq_item */
1595 (intintargfunc) PLy_result_slice, /* sq_slice */
1596 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1597 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1600 static PyTypeObject PLy_ResultType = {
1601 PyObject_HEAD_INIT(NULL)
1603 "PLyResult", /* tp_name */
1604 sizeof(PLyResultObject), /* tp_size */
1605 0, /* tp_itemsize */
1610 (destructor) PLy_result_dealloc, /* tp_dealloc */
1612 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1616 0, /* tp_as_number */
1617 &PLy_result_as_sequence, /* tp_as_sequence */
1618 0, /* tp_as_mapping */
1622 0, /* tp_getattro */
1623 0, /* tp_setattro */
1624 0, /* tp_as_buffer */
1626 PLy_result_doc, /* tp_doc */
1629 static PyMethodDef PLy_result_methods[] = {
1630 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
1631 {"status", PLy_result_status, METH_VARARGS, NULL},
1632 {NULL, NULL, 0, NULL}
1635 static PyMethodDef PLy_methods[] = {
1639 {"debug", PLy_debug, METH_VARARGS, NULL},
1640 {"log", PLy_log, METH_VARARGS, NULL},
1641 {"info", PLy_info, METH_VARARGS, NULL},
1642 {"notice", PLy_notice, METH_VARARGS, NULL},
1643 {"warning", PLy_warning, METH_VARARGS, NULL},
1644 {"error", PLy_error, METH_VARARGS, NULL},
1645 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1648 * create a stored plan
1650 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1653 * execute a plan or query
1655 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1657 {NULL, NULL, 0, NULL}
1661 /* plan object methods
1668 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1676 return (PyObject *) ob;
1681 PLy_plan_dealloc(PyObject * arg)
1683 PLyPlanObject *ob = (PLyPlanObject *) arg;
1686 SPI_freeplan(ob->plan);
1688 PLy_free(ob->types);
1693 for (i = 0; i < ob->nargs; i++)
1694 PLy_typeinfo_dealloc(&ob->args[i]);
1703 PLy_plan_getattr(PyObject * self, char *name)
1705 return Py_FindMethod(PLy_plan_methods, self, name);
1709 PLy_plan_status(PyObject * self, PyObject * args)
1711 if (PyArg_ParseTuple(args, ""))
1715 /* return PyInt_FromLong(self->status); */
1717 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1723 /* result object methods
1727 PLy_result_new(void)
1729 PLyResultObject *ob;
1731 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1734 /* ob->tuples = NULL; */
1737 ob->status = Py_None;
1738 ob->nrows = PyInt_FromLong(-1);
1739 ob->rows = PyList_New(0);
1741 return (PyObject *) ob;
1745 PLy_result_dealloc(PyObject * arg)
1747 PLyResultObject *ob = (PLyResultObject *) arg;
1749 Py_XDECREF(ob->nrows);
1750 Py_XDECREF(ob->rows);
1751 Py_XDECREF(ob->status);
1757 PLy_result_getattr(PyObject * self, char *name)
1759 return Py_FindMethod(PLy_result_methods, self, name);
1763 PLy_result_nrows(PyObject * self, PyObject * args)
1765 PLyResultObject *ob = (PLyResultObject *) self;
1767 Py_INCREF(ob->nrows);
1772 PLy_result_status(PyObject * self, PyObject * args)
1774 PLyResultObject *ob = (PLyResultObject *) self;
1776 Py_INCREF(ob->status);
1781 PLy_result_length(PyObject * arg)
1783 PLyResultObject *ob = (PLyResultObject *) arg;
1785 return PyList_Size(ob->rows);
1789 PLy_result_item(PyObject * arg, int idx)
1792 PLyResultObject *ob = (PLyResultObject *) arg;
1794 rv = PyList_GetItem(ob->rows, idx);
1801 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1804 PLyResultObject *ob = (PLyResultObject *) arg;
1807 rv = PyList_SetItem(ob->rows, idx, item);
1812 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1815 PLyResultObject *ob = (PLyResultObject *) arg;
1817 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1825 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1828 PLyResultObject *ob = (PLyResultObject *) arg;
1830 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1837 PLy_spi_prepare(PyObject * self, PyObject * args)
1839 PLyPlanObject *plan;
1840 PyObject *list = NULL;
1841 PyObject *volatile optr = NULL;
1844 MemoryContext oldcontext;
1846 /* Can't execute more if we have an unhandled error */
1847 if (PLy_error_in_progress)
1849 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1853 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1855 PyErr_SetString(PLy_exc_spi_error,
1856 "Invalid arguments for plpy.prepare()");
1860 if ((list) && (!PySequence_Check(list)))
1862 PyErr_SetString(PLy_exc_spi_error,
1863 "Second argument in plpy.prepare() must be a sequence");
1867 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1870 oldcontext = CurrentMemoryContext;
1878 nargs = PySequence_Length(list);
1881 plan->nargs = nargs;
1882 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1883 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1884 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1887 * the other loop might throw an exception, if PLyTypeInfo
1888 * member isn't properly initialized the Py_DECREF(plan)
1891 for (i = 0; i < nargs; i++)
1893 PLy_typeinfo_init(&plan->args[i]);
1894 plan->values[i] = (Datum) NULL;
1897 for (i = 0; i < nargs; i++)
1901 Form_pg_type typeStruct;
1903 optr = PySequence_GetItem(list, i);
1904 if (!PyString_Check(optr))
1905 elog(ERROR, "Type names must be strings.");
1906 sptr = PyString_AsString(optr);
1909 * XXX should extend this to allow qualified type
1912 typeTup = typenameType(makeTypeName(sptr));
1914 optr = NULL; /* this is important */
1916 plan->types[i] = HeapTupleGetOid(typeTup);
1917 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1918 if (typeStruct->typtype != 'c')
1919 PLy_output_datum_func(&plan->args[i], typeTup);
1921 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
1922 ReleaseSysCache(typeTup);
1927 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1928 if (plan->plan == NULL)
1929 elog(ERROR, "SPI_prepare failed: %s",
1930 SPI_result_code_string(SPI_result));
1932 /* transfer plan from procCxt to topCxt */
1933 tmpplan = plan->plan;
1934 plan->plan = SPI_saveplan(tmpplan);
1935 SPI_freeplan(tmpplan);
1936 if (plan->plan == NULL)
1937 elog(ERROR, "SPI_saveplan failed: %s",
1938 SPI_result_code_string(SPI_result));
1942 MemoryContextSwitchTo(oldcontext);
1943 PLy_error_in_progress = CopyErrorData();
1947 if (!PyErr_Occurred())
1948 PyErr_SetString(PLy_exc_spi_error,
1949 "Unknown error in PLy_spi_prepare");
1950 /* XXX this oughta be replaced with errcontext mechanism */
1951 PLy_elog(WARNING, "in function %s:",
1952 PLy_procedure_name(PLy_curr_procedure));
1957 return (PyObject *) plan;
1960 /* execute(query="select * from foo", limit=5)
1961 * execute(plan=plan, values=(foo, bar), limit=5)
1964 PLy_spi_execute(PyObject * self, PyObject * args)
1968 PyObject *list = NULL;
1971 /* Can't execute more if we have an unhandled error */
1972 if (PLy_error_in_progress)
1974 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1978 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
1979 return PLy_spi_execute_query(query, limit);
1983 if ((PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit)) &&
1984 (is_PLyPlanObject(plan)))
1985 return PLy_spi_execute_plan(plan, list, limit);
1987 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
1992 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
1997 PLyPlanObject *plan;
1999 MemoryContext oldcontext;
2003 if ((!PySequence_Check(list)) || (PyString_Check(list)))
2005 char *msg = "plpy.execute() takes a sequence as its second argument";
2007 PyErr_SetString(PLy_exc_spi_error, msg);
2010 nargs = PySequence_Length(list);
2015 plan = (PLyPlanObject *) ob;
2017 if (nargs != plan->nargs)
2021 PyObject *so = PyObject_Str(list);
2023 sv = PyString_AsString(so);
2024 PLy_exception_set(PLy_exc_spi_error,
2025 "Expected sequence of %d arguments, got %d. %s",
2026 plan->nargs, nargs, sv);
2032 oldcontext = CurrentMemoryContext;
2035 nulls = palloc(nargs * sizeof(char));
2037 for (i = 0; i < nargs; i++)
2043 elem = PySequence_GetItem(list, i);
2044 if (elem != Py_None)
2046 so = PyObject_Str(elem);
2047 sv = PyString_AsString(so);
2050 * FIXME -- if this elogs, we have Python reference leak
2053 FunctionCall3(&(plan->args[i].out.d.typfunc),
2054 CStringGetDatum(sv),
2055 ObjectIdGetDatum(plan->args[i].out.d.typioparam),
2066 plan->values[i] = (Datum) 0;
2071 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2072 PLy_curr_procedure->fn_readonly, limit);
2078 MemoryContextSwitchTo(oldcontext);
2079 PLy_error_in_progress = CopyErrorData();
2083 * cleanup plan->values array
2085 for (i = 0; i < nargs; i++)
2087 if (!plan->args[i].out.d.typbyval &&
2088 (plan->values[i] != (Datum) NULL))
2090 pfree(DatumGetPointer(plan->values[i]));
2091 plan->values[i] = (Datum) NULL;
2095 if (!PyErr_Occurred())
2096 PyErr_SetString(PLy_exc_error,
2097 "Unknown error in PLy_spi_execute_plan");
2098 /* XXX this oughta be replaced with errcontext mechanism */
2099 PLy_elog(WARNING, "in function %s:",
2100 PLy_procedure_name(PLy_curr_procedure));
2105 for (i = 0; i < nargs; i++)
2107 if (!plan->args[i].out.d.typbyval &&
2108 (plan->values[i] != (Datum) NULL))
2110 pfree(DatumGetPointer(plan->values[i]));
2111 plan->values[i] = (Datum) NULL;
2117 PLy_exception_set(PLy_exc_spi_error,
2118 "SPI_execute_plan failed: %s",
2119 SPI_result_code_string(rv));
2123 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2127 PLy_spi_execute_query(char *query, long limit)
2130 MemoryContext oldcontext;
2132 oldcontext = CurrentMemoryContext;
2135 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2139 MemoryContextSwitchTo(oldcontext);
2140 PLy_error_in_progress = CopyErrorData();
2142 if (!PyErr_Occurred())
2143 PyErr_SetString(PLy_exc_spi_error,
2144 "Unknown error in PLy_spi_execute_query");
2145 /* XXX this oughta be replaced with errcontext mechanism */
2146 PLy_elog(WARNING, "in function %s:",
2147 PLy_procedure_name(PLy_curr_procedure));
2154 PLy_exception_set(PLy_exc_spi_error,
2155 "SPI_execute failed: %s",
2156 SPI_result_code_string(rv));
2160 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2164 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2166 PLyResultObject *result;
2167 MemoryContext oldcontext;
2169 result = (PLyResultObject *) PLy_result_new();
2170 Py_DECREF(result->status);
2171 result->status = PyInt_FromLong(status);
2173 if (status == SPI_OK_UTILITY)
2175 Py_DECREF(result->nrows);
2176 result->nrows = PyInt_FromLong(0);
2178 else if (status != SPI_OK_SELECT)
2180 Py_DECREF(result->nrows);
2181 result->nrows = PyInt_FromLong(rows);
2188 PLy_typeinfo_init(&args);
2189 Py_DECREF(result->nrows);
2190 result->nrows = PyInt_FromLong(rows);
2192 oldcontext = CurrentMemoryContext;
2197 Py_DECREF(result->rows);
2198 result->rows = PyList_New(rows);
2200 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2201 for (i = 0; i < rows; i++)
2203 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2206 PyList_SetItem(result->rows, i, row);
2208 PLy_typeinfo_dealloc(&args);
2210 SPI_freetuptable(tuptable);
2215 MemoryContextSwitchTo(oldcontext);
2216 PLy_error_in_progress = CopyErrorData();
2218 if (!PyErr_Occurred())
2219 PyErr_SetString(PLy_exc_error,
2220 "Unknown error in PLy_spi_execute_fetch_result");
2222 PLy_typeinfo_dealloc(&args);
2228 return (PyObject *) result;
2233 * language handler and interpreter initialization
2237 * plpython_init() - Initialize everything that can be
2238 * safely initialized during postmaster
2241 * DO NOT make this static --- it has to be callable by preload
2246 static volatile int init_active = 0;
2248 /* Do initialization only once */
2249 if (!PLy_first_call)
2253 elog(FATAL, "initialization of language module failed");
2259 if (PyErr_Occurred())
2260 PLy_elog(FATAL, "untrapped error in initialization");
2261 PLy_procedure_cache = PyDict_New();
2262 if (PLy_procedure_cache == NULL)
2263 PLy_elog(ERROR, "could not create procedure cache");
2271 /* Execute postmaster-startup safe initialization */
2276 * Any other initialization that must be done each time a new backend
2277 * starts -- currently none
2283 PLy_init_interp(void)
2287 mainmod = PyImport_AddModule("__main__");
2288 if ((mainmod == NULL) || (PyErr_Occurred()))
2289 PLy_elog(ERROR, "could not import \"__main__\" module.");
2291 PLy_interp_globals = PyModule_GetDict(mainmod);
2292 PLy_interp_safe_globals = PyDict_New();
2293 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2295 if ((PLy_interp_globals == NULL) || (PyErr_Occurred()))
2296 PLy_elog(ERROR, "could not initialize globals");
2309 * initialize plpy module
2311 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2312 plpy = Py_InitModule("plpy", PLy_methods);
2313 plpy_dict = PyModule_GetDict(plpy);
2315 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2317 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2318 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2319 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2320 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2321 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2322 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2325 * initialize main module, and add plpy
2327 main_mod = PyImport_AddModule("__main__");
2328 main_dict = PyModule_GetDict(main_mod);
2329 plpy_mod = PyImport_AddModule("plpy");
2330 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2331 if (PyErr_Occurred())
2332 elog(ERROR, "could not init plpy");
2335 /* the python interface to the elog function
2336 * don't confuse these with PLy_elog
2338 static PyObject *PLy_output(int, PyObject *, PyObject *);
2341 PLy_debug(PyObject * self, PyObject * args)
2343 return PLy_output(DEBUG2, self, args);
2347 PLy_log(PyObject * self, PyObject * args)
2349 return PLy_output(LOG, self, args);
2353 PLy_info(PyObject * self, PyObject * args)
2355 return PLy_output(INFO, self, args);
2359 PLy_notice(PyObject * self, PyObject * args)
2361 return PLy_output(NOTICE, self, args);
2365 PLy_warning(PyObject * self, PyObject * args)
2367 return PLy_output(WARNING, self, args);
2371 PLy_error(PyObject * self, PyObject * args)
2373 return PLy_output(ERROR, self, args);
2377 PLy_fatal(PyObject * self, PyObject * args)
2379 return PLy_output(FATAL, self, args);
2384 PLy_output(volatile int level, PyObject * self, PyObject * args)
2388 MemoryContext oldcontext;
2390 so = PyObject_Str(args);
2391 if ((so == NULL) || ((sv = PyString_AsString(so)) == NULL))
2394 sv = "Unable to parse error message in `plpy.elog'";
2397 oldcontext = CurrentMemoryContext;
2400 elog(level, "%s", sv);
2404 MemoryContextSwitchTo(oldcontext);
2405 PLy_error_in_progress = CopyErrorData();
2410 * returning NULL here causes the python interpreter to bail. when
2411 * control passes back to PLy_procedure_call, we check for PG
2412 * exceptions and re-throw the error.
2414 PyErr_SetString(PLy_exc_error, sv);
2422 * return a legal object so the interpreter will continue on its merry
2431 * Get the last procedure name called by the backend ( the innermost,
2432 * If a plpython procedure call calls the backend and the backend calls
2433 * another plpython procedure )
2435 * NB: this returns SQL name, not the internal Python procedure name
2439 PLy_procedure_name(PLyProcedure * proc)
2442 return "<unknown procedure>";
2443 return proc->proname;
2446 /* output a python traceback/exception via the postgresql elog
2447 * function. not pretty.
2450 PLy_exception_set(PyObject * exc, const char *fmt,...)
2456 vsnprintf(buf, sizeof(buf), fmt, ap);
2459 PyErr_SetString(exc, buf);
2462 /* Emit a PG error or notice, together with any available info about the
2463 * current Python error. This should be used to propagate Python errors
2467 PLy_elog(int elevel, const char *fmt,...)
2474 xmsg = PLy_traceback(&xlevel);
2477 emsg = PLy_vprintf(fmt, ap);
2483 (errmsg("plpython: %s", emsg),
2484 (xmsg) ? errdetail("%s", xmsg) : 0));
2501 PLy_traceback(int *xlevel)
2513 * get the current exception
2515 PyErr_Fetch(&e, &v, &tb);
2518 * oops, no exception, return
2526 PyErr_NormalizeException(&e, &v, &tb);
2528 eob = PyObject_Str(e);
2529 if ((v) && ((vob = PyObject_Str(v)) != NULL))
2530 vstr = PyString_AsString(vob);
2534 estr = PyString_AsString(eob);
2535 xstr = PLy_printf("%s: %s", estr, vstr);
2541 * intuit an appropriate error level for based on the exception type
2543 if ((PLy_exc_error) && (PyErr_GivenExceptionMatches(e, PLy_exc_error)))
2545 else if ((PLy_exc_fatal) && (PyErr_GivenExceptionMatches(e, PLy_exc_fatal)))
2554 PLy_printf(const char *fmt,...)
2560 emsg = PLy_vprintf(fmt, ap);
2566 PLy_vprintf(const char *fmt, va_list ap)
2573 blen = strlen(fmt) * 2;
2576 buf = PLy_malloc(blen * sizeof(char));
2580 bchar = vsnprintf(buf, blen, fmt, ap);
2581 if ((bchar > 0) && (bchar < blen))
2589 buf = PLy_realloc(buf, blen);
2595 /* python module code
2599 /* some dumb utility functions
2603 PLy_malloc(size_t bytes)
2605 void *ptr = malloc(bytes);
2609 (errcode(ERRCODE_OUT_OF_MEMORY),
2610 errmsg("out of memory")));
2615 PLy_realloc(void *optr, size_t bytes)
2617 void *nptr = realloc(optr, bytes);
2621 (errcode(ERRCODE_OUT_OF_MEMORY),
2622 errmsg("out of memory")));