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.48 2004/06/05 19:48:09 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/syscache.h"
55 #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 * -1 not known yet (initial state)
124 * 2 rowtype, but I/O functions not set up yet
129 /* cached procedure data
131 typedef struct PLyProcedure
133 char *proname; /* SQL name of procedure */
134 char *pyname; /* Python name of procedure */
135 TransactionId fn_xmin;
137 PLyTypeInfo result; /* also used to store info for trigger
139 PLyTypeInfo args[FUNC_MAX_ARGS];
141 PyObject *code; /* compiled procedure code */
142 PyObject *statics; /* data saved across calls, local scope */
143 PyObject *globals; /* data saved across calls, global score */
144 PyObject *me; /* PyCObject containing pointer to this
151 typedef struct PLyPlanObject
154 void *plan; /* return of an SPI_saveplan */
161 typedef struct PLyResultObject
164 /* HeapTuple *tuples; */
165 PyObject *nrows; /* number of rows returned by query */
166 PyObject *rows; /* data rows, or None if no data returned */
167 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
171 /* function declarations
174 /* Two exported functions: first is the magic telling Postgresql
175 * what function call interface it implements. Second allows
176 * preinitialization of the interpreter during postmaster startup.
178 Datum plpython_call_handler(PG_FUNCTION_ARGS);
179 void plpython_init(void);
181 PG_FUNCTION_INFO_V1(plpython_call_handler);
183 /* most of the remaining of the declarations, all static
186 /* these should only be called once at the first call
187 * of plpython_call_handler. initialize the python interpreter
190 static void PLy_init_all(void);
191 static void PLy_init_interp(void);
192 static void PLy_init_plpy(void);
194 /* error handler. collects the current Python exception, if any,
195 * and appends it to the error and sends it to elog
197 static void PLy_elog(int, const char *,...);
199 /* call PyErr_SetString with a vprint interface
202 PLy_exception_set(PyObject *, const char *,...)
203 __attribute__((format(printf, 2, 3)));
205 /* Get the innermost python procedure called from the backend.
207 static char *PLy_procedure_name(PLyProcedure *);
209 /* some utility functions
211 static void *PLy_malloc(size_t);
212 static void *PLy_realloc(void *, size_t);
213 static void PLy_free(void *);
215 /* sub handlers for functions and triggers
217 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
218 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
220 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
221 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
223 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
224 TriggerData *, HeapTuple);
226 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
228 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
231 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
233 HeapTuple procTup, char *key);
235 static void PLy_procedure_compile(PLyProcedure *, const char *);
236 static char *PLy_procedure_munge_source(const char *, const char *);
237 static void PLy_procedure_delete(PLyProcedure *);
239 static void PLy_typeinfo_init(PLyTypeInfo *);
240 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
241 static void PLy_output_datum_func(PLyTypeInfo *, Form_pg_type);
242 static void PLy_output_datum_func2(PLyObToDatum *, Form_pg_type);
243 static void PLy_input_datum_func(PLyTypeInfo *, Oid, Form_pg_type);
244 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, Form_pg_type);
245 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
246 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
248 /* conversion functions
250 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
251 static PyObject *PLyBool_FromString(const char *);
252 static PyObject *PLyFloat_FromString(const char *);
253 static PyObject *PLyInt_FromString(const char *);
254 static PyObject *PLyLong_FromString(const char *);
255 static PyObject *PLyString_FromString(const char *);
260 static int PLy_first_call = 1;
261 static volatile int PLy_call_level = 0;
264 * Last function called by postgres backend
266 static PLyProcedure *PLy_last_procedure = NULL;
268 /* this gets modified in plpython_call_handler and PLy_elog.
269 * test it any old where, but do NOT modify it anywhere except
270 * those two functions
272 static volatile int PLy_restart_in_progress = 0;
274 static PyObject *PLy_interp_globals = NULL;
275 static PyObject *PLy_interp_safe_globals = NULL;
276 static PyObject *PLy_procedure_cache = NULL;
280 static PyObject *PLy_exc_error = NULL;
281 static PyObject *PLy_exc_fatal = NULL;
282 static PyObject *PLy_exc_spi_error = NULL;
284 /* some globals for the python module
286 static char PLy_plan_doc[] = {
287 "Store a PostgreSQL plan"
290 static char PLy_result_doc[] = {
291 "Results of a PostgreSQL query"
296 volatile int exc_save_calls = 0;
297 volatile int exc_restore_calls = 0;
298 volatile int func_enter_calls = 0;
299 volatile int func_leave_calls = 0;
303 * the function definitions
307 * This routine is a crock, and so is everyplace that calls it. The problem
308 * is that the cached form of plpython functions/queries is allocated permanently
309 * (mostly via malloc()) and never released until backend exit. Subsidiary
310 * data structures such as fmgr info records therefore must live forever
311 * as well. A better implementation would store all this stuff in a per-
312 * function memory context that could be reclaimed at need. In the meantime,
313 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
314 * it might allocate, and whatever the eventual function might allocate using
315 * fn_mcxt, will live forever too.
318 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
320 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
324 plpython_call_handler(PG_FUNCTION_ARGS)
328 PLyProcedure *volatile proc = NULL;
334 if (SPI_connect() != SPI_OK_CONNECT)
335 elog(ERROR, "could not connect to SPI manager");
344 if (PLy_call_level == 0)
346 PLy_restart_in_progress = 0;
350 PLy_restart_in_progress += 1;
353 /* note: Py_DECREF needs braces around it, as of 2003/08 */
360 * elog(DEBUG3, "PLy_restart_in_progress is %d",
361 * PLy_restart_in_progress);
364 if (CALLED_AS_TRIGGER(fcinfo))
366 TriggerData *tdata = (TriggerData *) fcinfo->context;
369 proc = PLy_procedure_get(fcinfo,
370 RelationGetRelid(tdata->tg_relation));
371 trv = PLy_trigger_handler(fcinfo, proc);
372 retval = PointerGetDatum(trv);
376 proc = PLy_procedure_get(fcinfo, InvalidOid);
377 retval = PLy_function_handler(fcinfo, proc);
389 /* trigger and function sub handlers
391 * the python function is expected to return Py_None if the tuple is
392 * acceptable and unmodified. Otherwise it should return a PyString
393 * object who's value is SKIP, or MODIFY. SKIP means don't perform
394 * this action. MODIFY means the tuple has been modified, so update
395 * tuple and perform action. SKIP and MODIFY assume the trigger fires
396 * BEFORE the event and is ROW level. postgres expects the function
397 * to take no arguments and return an argument of type trigger.
400 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
404 PyObject *volatile plargs = NULL;
405 PyObject *volatile plrv = NULL;
420 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
421 plrv = PLy_procedure_call(proc, "TD", plargs);
424 * Disconnect from SPI manager
426 if (SPI_finish() != SPI_OK_FINISH)
427 elog(ERROR, "SPI_finish failed");
430 elog(FATAL, "PLy_procedure_call returned NULL");
432 if (PLy_restart_in_progress)
433 elog(FATAL, "restart in progress not expected");
436 * return of None means we're happy with the tuple
442 if (!PyString_Check(plrv))
443 elog(ERROR, "expected trigger to return None or a String");
445 srv = PyString_AsString(plrv);
446 if (pg_strcasecmp(srv, "SKIP") == 0)
448 else if (pg_strcasecmp(srv, "MODIFY") == 0)
450 TriggerData *tdata = (TriggerData *) fcinfo->context;
452 if ((TRIGGER_FIRED_BY_INSERT(tdata->tg_event)) ||
453 (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event)))
454 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
456 elog(WARNING, "ignoring modified tuple in DELETE trigger");
458 else if (pg_strcasecmp(srv, "OK") != 0)
461 * hmmm, perhaps they only read the pltcl page, not a
462 * surprising thing since i've written no documentation, so
463 * accept a belated OK
465 elog(ERROR, "expected return to be \"SKIP\" or \"MODIFY\"");
478 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
482 PyObject *volatile plntup;
483 PyObject *volatile plkeys;
484 PyObject *volatile platt;
485 PyObject *volatile plval;
486 PyObject *volatile plstr;
492 int *volatile modattrs;
493 Datum *volatile modvalues;
494 char *volatile modnulls;
497 plntup = plkeys = platt = plval = plstr = NULL;
525 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
526 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
527 if (!PyDict_Check(plntup))
528 elog(ERROR, "TD[\"new\"] is not a dictionary object");
531 plkeys = PyDict_Keys(plntup);
532 natts = PyList_Size(plkeys);
534 modattrs = (int *) palloc(natts * sizeof(int));
535 modvalues = (Datum *) palloc(natts * sizeof(Datum));
536 modnulls = (char *) palloc(natts * sizeof(char));
538 tupdesc = tdata->tg_relation->rd_att;
540 for (i = 0; i < natts; i++)
544 platt = PyList_GetItem(plkeys, i);
545 if (!PyString_Check(platt))
546 elog(ERROR, "attribute name is not a string");
547 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
548 if (attn == SPI_ERROR_NOATTRIBUTE)
549 elog(ERROR, "invalid attribute \"%s\" in tuple",
550 PyString_AsString(platt));
553 plval = PyDict_GetItem(plntup, platt);
555 elog(FATAL, "python interpreter is probably corrupted");
561 if (plval != Py_None && !tupdesc->attrs[atti]->attisdropped)
563 plstr = PyObject_Str(plval);
564 src = PyString_AsString(plstr);
566 modvalues[i] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
567 CStringGetDatum(src),
568 ObjectIdGetDatum(proc->result.out.r.atts[atti].typelem),
569 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
577 modvalues[i] = (Datum) 0;
585 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
586 modattrs, modvalues, modnulls);
589 * FIXME -- these leak if not explicitly pfree'd by other elog calls,
590 * no? (No, I think, but might as well leave the pfrees here...)
597 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
608 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
620 PyObject *volatile pltdata = NULL;
635 tdata = (TriggerData *) fcinfo->context;
637 pltdata = PyDict_New();
639 PLy_elog(ERROR, "could not build arguments for trigger procedure");
641 pltname = PyString_FromString(tdata->tg_trigger->tgname);
642 PyDict_SetItemString(pltdata, "name", pltname);
645 stroid = DatumGetCString(DirectFunctionCall1(oidout,
646 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
647 pltrelid = PyString_FromString(stroid);
648 PyDict_SetItemString(pltdata, "relid", pltrelid);
652 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
653 pltwhen = PyString_FromString("BEFORE");
654 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
655 pltwhen = PyString_FromString("AFTER");
658 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
659 pltwhen = NULL; /* keep compiler quiet */
661 PyDict_SetItemString(pltdata, "when", pltwhen);
664 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
666 pltlevel = PyString_FromString("ROW");
667 PyDict_SetItemString(pltdata, "level", pltlevel);
670 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
672 pltevent = PyString_FromString("INSERT");
674 PyDict_SetItemString(pltdata, "old", Py_None);
675 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
676 tdata->tg_relation->rd_att);
677 PyDict_SetItemString(pltdata, "new", pytnew);
679 *rv = tdata->tg_trigtuple;
681 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
683 pltevent = PyString_FromString("DELETE");
685 PyDict_SetItemString(pltdata, "new", Py_None);
686 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
687 tdata->tg_relation->rd_att);
688 PyDict_SetItemString(pltdata, "old", pytold);
690 *rv = tdata->tg_trigtuple;
692 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
694 pltevent = PyString_FromString("UPDATE");
696 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
697 tdata->tg_relation->rd_att);
698 PyDict_SetItemString(pltdata, "new", pytnew);
700 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
701 tdata->tg_relation->rd_att);
702 PyDict_SetItemString(pltdata, "old", pytold);
704 *rv = tdata->tg_newtuple;
708 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
709 pltevent = NULL; /* keep compiler quiet */
712 PyDict_SetItemString(pltdata, "event", pltevent);
715 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
717 pltlevel = PyString_FromString("STATEMENT");
718 PyDict_SetItemString(pltdata, "level", pltlevel);
721 PyDict_SetItemString(pltdata, "old", Py_None);
722 PyDict_SetItemString(pltdata, "new", Py_None);
725 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
726 pltevent = PyString_FromString("INSERT");
727 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
728 pltevent = PyString_FromString("DELETE");
729 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
730 pltevent = PyString_FromString("UPDATE");
733 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
734 pltevent = NULL; /* keep compiler quiet */
737 PyDict_SetItemString(pltdata, "event", pltevent);
741 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
743 if (tdata->tg_trigger->tgnargs)
751 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
752 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
754 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
757 * stolen, don't Py_DECREF
759 PyList_SetItem(pltargs, i, pltarg);
767 PyDict_SetItemString(pltdata, "args", pltargs);
777 /* function handler and friends
780 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
784 PyObject *volatile plargs = NULL;
785 PyObject *volatile plrv = NULL;
786 PyObject *volatile plrv_so = NULL;
792 * setup to catch elog in while building function arguments, and
793 * DECREF the plargs if the function call fails
807 plargs = PLy_function_build_args(fcinfo, proc);
808 plrv = PLy_procedure_call(proc, "args", plargs);
811 * Disconnect from SPI manager and then create the return values datum
812 * (if the input function does a palloc for it this must not be
813 * allocated in the SPI memory context because SPI_finish would free
816 if (SPI_finish() != SPI_OK_FINISH)
817 elog(ERROR, "SPI_finish failed");
821 elog(FATAL, "PLy_procedure_call returned NULL");
823 if (!PLy_restart_in_progress)
824 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
827 * FIXME is this dead code? i'm pretty sure it is for unnested
828 * calls, but not for nested calls
835 * convert the python PyObject to a postgresql Datum FIXME returning a
836 * NULL, ie PG_RETURN_NULL() blows the backend to small messy bits...
837 * it this a bug or expected? so just call with the string value of
843 fcinfo->isnull = true;
848 fcinfo->isnull = false;
849 plrv_so = PyObject_Str(plrv);
850 plrv_sc = PyString_AsString(plrv_so);
851 rv = FunctionCall3(&proc->result.out.d.typfunc,
852 PointerGetDatum(plrv_sc),
853 ObjectIdGetDatum(proc->result.out.d.typelem),
867 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
870 PLyProcedure *current;
874 current = PLy_last_procedure;
875 PLy_last_procedure = proc;
876 PyDict_SetItemString(proc->globals, kargs, vargs);
877 rv = PyEval_EvalCode((PyCodeObject *) proc->code, proc->globals, proc->globals);
878 PLy_last_procedure = current;
880 if ((rv == NULL) || (PyErr_Occurred()))
883 if (!PLy_restart_in_progress)
884 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
892 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
895 PyObject *volatile arg = NULL;
896 PyObject *volatile args = NULL;
902 * FIXME -- if the setjmp setup is expensive, add the arg and args
903 * field to the procedure struct and cleanup at the start of the next
916 args = PyList_New(proc->nargs);
917 for (i = 0; i < proc->nargs; i++)
919 if (proc->args[i].is_rowtype > 0)
921 if (fcinfo->argnull[i])
929 HeapTupleData tmptup;
931 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
932 /* Extract rowtype info and find a tupdesc */
933 tupType = HeapTupleHeaderGetTypeId(td);
934 tupTypmod = HeapTupleHeaderGetTypMod(td);
935 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
937 /* Set up I/O funcs if not done yet */
938 if (proc->args[i].is_rowtype != 1)
939 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
941 /* Build a temporary HeapTuple control structure */
942 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
945 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
950 if (fcinfo->argnull[i])
957 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
959 ObjectIdGetDatum(proc->args[i].in.d.typelem),
961 ct = DatumGetCString(dt);
962 arg = (proc->args[i].in.d.func) (ct);
974 * FIXME -- error check this
976 PyList_SetItem(args, i, arg);
986 * PLyProcedure functions
989 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
990 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
991 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
994 static PLyProcedure *
995 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
1001 PLyProcedure *proc = NULL;
1006 fn_oid = fcinfo->flinfo->fn_oid;
1007 procTup = SearchSysCache(PROCOID,
1008 ObjectIdGetDatum(fn_oid),
1010 if (!HeapTupleIsValid(procTup))
1011 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1013 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
1014 if ((rv >= sizeof(key)) || (rv < 0))
1015 elog(ERROR, "key too long");
1017 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
1022 if (!PyCObject_Check(plproc))
1023 elog(FATAL, "expected a PyCObject, didn't get one");
1027 proc = PyCObject_AsVoidPtr(plproc);
1028 if (proc->me != plproc)
1029 elog(FATAL, "proc->me != plproc");
1030 /* did we find an up-to-date cache entry? */
1031 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
1032 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
1040 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
1042 ReleaseSysCache(procTup);
1047 static PLyProcedure *
1048 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
1049 HeapTuple procTup, char *key)
1051 char procName[NAMEDATALEN + 256];
1054 Form_pg_proc procStruct;
1055 PLyProcedure *volatile proc;
1056 char *volatile procSource = NULL;
1064 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1066 if (OidIsValid(tgreloid))
1067 rv = snprintf(procName, sizeof(procName),
1068 "__plpython_procedure_%s_%u_trigger_%u",
1069 NameStr(procStruct->proname),
1070 fcinfo->flinfo->fn_oid,
1073 rv = snprintf(procName, sizeof(procName),
1074 "__plpython_procedure_%s_%u",
1075 NameStr(procStruct->proname),
1076 fcinfo->flinfo->fn_oid);
1077 if ((rv >= sizeof(procName)) || (rv < 0))
1078 elog(ERROR, "procedure name would overrun buffer");
1080 proc = PLy_malloc(sizeof(PLyProcedure));
1081 proc->proname = PLy_malloc(strlen(NameStr(procStruct->proname)) + 1);
1082 strcpy(proc->proname, NameStr(procStruct->proname));
1083 proc->pyname = PLy_malloc(strlen(procName) + 1);
1084 strcpy(proc->pyname, procName);
1085 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1086 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1087 PLy_typeinfo_init(&proc->result);
1088 for (i = 0; i < FUNC_MAX_ARGS; i++)
1089 PLy_typeinfo_init(&proc->args[i]);
1091 proc->code = proc->statics = NULL;
1092 proc->globals = proc->me = NULL;
1098 PLy_procedure_delete(proc);
1105 * get information required for output conversion of the return value,
1106 * but only if this isn't a trigger.
1108 if (!CALLED_AS_TRIGGER(fcinfo))
1110 HeapTuple rvTypeTup;
1111 Form_pg_type rvTypeStruct;
1113 rvTypeTup = SearchSysCache(TYPEOID,
1114 ObjectIdGetDatum(procStruct->prorettype),
1116 if (!HeapTupleIsValid(rvTypeTup))
1117 elog(ERROR, "cache lookup failed for type %u",
1118 procStruct->prorettype);
1120 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1121 if (rvTypeStruct->typtype != 'c')
1122 PLy_output_datum_func(&proc->result, rvTypeStruct);
1125 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1126 errmsg("tuple return types are not supported yet")));
1128 ReleaseSysCache(rvTypeTup);
1133 * input/output conversion for trigger tuples. use the result
1134 * TypeInfo variable to store the tuple conversion info.
1136 TriggerData *tdata = (TriggerData *) fcinfo->context;
1138 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1139 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1143 * now get information required for input conversion of the procedures
1146 proc->nargs = fcinfo->nargs;
1147 for (i = 0; i < fcinfo->nargs; i++)
1149 HeapTuple argTypeTup;
1150 Form_pg_type argTypeStruct;
1152 argTypeTup = SearchSysCache(TYPEOID,
1153 ObjectIdGetDatum(procStruct->proargtypes[i]),
1155 if (!HeapTupleIsValid(argTypeTup))
1156 elog(ERROR, "cache lookup failed for type %u",
1157 procStruct->proargtypes[i]);
1158 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1160 if (argTypeStruct->typtype != 'c')
1161 PLy_input_datum_func(&(proc->args[i]),
1162 procStruct->proargtypes[i],
1165 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1167 ReleaseSysCache(argTypeTup);
1172 * get the text of the function.
1174 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1175 Anum_pg_proc_prosrc, &isnull);
1177 elog(ERROR, "null prosrc");
1178 procSource = DatumGetCString(DirectFunctionCall1(textout,
1181 PLy_procedure_compile(proc, procSource);
1185 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1186 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1194 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1196 PyObject *crv = NULL;
1201 proc->globals = PyDict_Copy(PLy_interp_globals);
1204 * SD is private preserved data between calls GD is global data shared
1207 proc->statics = PyDict_New();
1208 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1211 * insert the function code into the interpreter
1213 msrc = PLy_procedure_munge_source(proc->pyname, src);
1214 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1217 if ((crv != NULL) && (!PyErr_Occurred()))
1220 char call[NAMEDATALEN + 256];
1225 * compile a call to the function
1227 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1228 if ((clen < 0) || (clen >= sizeof(call)))
1229 elog(ERROR, "string would overflow buffer");
1230 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1231 if ((proc->code != NULL) && (!PyErr_Occurred()))
1237 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1241 PLy_procedure_munge_source(const char *name, const char *src)
1252 * room for function source and the def statement
1254 mlen = (strlen(src) * 2) + strlen(name) + 16;
1256 mrc = PLy_malloc(mlen);
1257 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1258 Assert(plen >= 0 && plen < mlen);
1277 if (mp > (mrc + mlen))
1278 elog(FATAL, "buffer overrun in PLy_munge_source");
1284 PLy_procedure_delete(PLyProcedure * proc)
1290 Py_XDECREF(proc->code);
1291 Py_XDECREF(proc->statics);
1292 Py_XDECREF(proc->globals);
1293 Py_XDECREF(proc->me);
1295 PLy_free(proc->proname);
1297 PLy_free(proc->pyname);
1298 for (i = 0; i < proc->nargs; i++)
1299 if (proc->args[i].is_rowtype == 1)
1301 if (proc->args[i].in.r.atts)
1302 PLy_free(proc->args[i].in.r.atts);
1303 if (proc->args[i].out.r.atts)
1304 PLy_free(proc->args[i].out.r.atts);
1310 /* conversion functions. remember output from python is
1311 * input to postgresql, and vis versa.
1314 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1320 if (arg->is_rowtype == 0)
1321 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1323 arg->is_rowtype = 1;
1324 arg->in.r.natts = desc->natts;
1325 arg->in.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1327 for (i = 0; i < desc->natts; i++)
1330 Form_pg_type typeStruct;
1332 if (desc->attrs[i]->attisdropped)
1335 typeTup = SearchSysCache(TYPEOID,
1336 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1338 if (!HeapTupleIsValid(typeTup))
1339 elog(ERROR, "cache lookup failed for type %u",
1340 desc->attrs[i]->atttypid);
1341 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1343 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1344 desc->attrs[i]->atttypid,
1347 ReleaseSysCache(typeTup);
1352 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1358 if (arg->is_rowtype == 0)
1359 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1361 arg->is_rowtype = 1;
1362 arg->out.r.natts = desc->natts;
1363 arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1365 for (i = 0; i < desc->natts; i++)
1368 Form_pg_type typeStruct;
1370 if (desc->attrs[i]->attisdropped)
1373 typeTup = SearchSysCache(TYPEOID,
1374 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1376 if (!HeapTupleIsValid(typeTup))
1377 elog(ERROR, "cache lookup failed for type %u",
1378 desc->attrs[i]->atttypid);
1379 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1381 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeStruct);
1383 ReleaseSysCache(typeTup);
1388 PLy_output_datum_func(PLyTypeInfo * arg, Form_pg_type typeStruct)
1392 if (arg->is_rowtype > 0)
1393 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1394 arg->is_rowtype = 0;
1395 PLy_output_datum_func2(&(arg->out.d), typeStruct);
1399 PLy_output_datum_func2(PLyObToDatum * arg, Form_pg_type typeStruct)
1403 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1404 arg->typelem = typeStruct->typelem;
1405 arg->typbyval = typeStruct->typbyval;
1409 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, Form_pg_type typeStruct)
1413 if (arg->is_rowtype > 0)
1414 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1415 arg->is_rowtype = 0;
1416 PLy_input_datum_func2(&(arg->in.d), typeOid, typeStruct);
1420 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, Form_pg_type typeStruct)
1422 /* Get the type's conversion information */
1423 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1424 arg->typelem = typeStruct->typelem;
1425 arg->typbyval = typeStruct->typbyval;
1427 /* Determine which kind of Python object we will convert to */
1431 arg->func = PLyBool_FromString;
1436 arg->func = PLyFloat_FromString;
1440 arg->func = PLyInt_FromString;
1443 arg->func = PLyLong_FromString;
1446 arg->func = PLyString_FromString;
1452 PLy_typeinfo_init(PLyTypeInfo * arg)
1454 arg->is_rowtype = -1;
1455 arg->in.r.natts = arg->out.r.natts = 0;
1456 arg->in.r.atts = NULL;
1457 arg->out.r.atts = NULL;
1461 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1463 if (arg->is_rowtype == 1)
1466 PLy_free(arg->in.r.atts);
1467 if (arg->out.r.atts)
1468 PLy_free(arg->out.r.atts);
1472 /* assumes that a bool is always returned as a 't' or 'f'
1475 PLyBool_FromString(const char *src)
1480 return PyInt_FromLong(1);
1481 return PyInt_FromLong(0);
1485 PLyFloat_FromString(const char *src)
1493 v = strtod(src, &eptr);
1494 if ((*eptr != '\0') || (errno))
1496 return PyFloat_FromDouble(v);
1500 PLyInt_FromString(const char *src)
1508 v = strtol(src, &eptr, 0);
1509 if ((*eptr != '\0') || (errno))
1511 return PyInt_FromLong(v);
1515 PLyLong_FromString(const char *src)
1517 return PyLong_FromString((char *) src, NULL, 0);
1521 PLyString_FromString(const char *src)
1523 return PyString_FromString(src);
1527 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1530 PyObject *volatile dict;
1535 if (info->is_rowtype != 1)
1536 elog(ERROR, "PLyTypeInfo structure describes a datum");
1538 dict = PyDict_New();
1540 PLy_elog(ERROR, "could not create tuple dictionary");
1551 for (i = 0; i < info->in.r.natts; i++)
1560 if (desc->attrs[i]->attisdropped)
1563 key = NameStr(desc->attrs[i]->attname);
1564 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1566 if ((is_null) || (info->in.r.atts[i].func == NULL))
1567 PyDict_SetItemString(dict, key, Py_None);
1570 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1572 ObjectIdGetDatum(info->in.r.atts[i].typelem),
1573 Int32GetDatum(desc->attrs[i]->atttypmod));
1574 vsrc = DatumGetCString(vdat);
1577 * no exceptions allowed
1579 value = info->in.r.atts[i].func(vsrc);
1581 PyDict_SetItemString(dict, key, value);
1591 /* initialization, some python variables function declared here
1594 /* interface to postgresql elog
1596 static PyObject *PLy_debug(PyObject *, PyObject *);
1597 static PyObject *PLy_log(PyObject *, PyObject *);
1598 static PyObject *PLy_info(PyObject *, PyObject *);
1599 static PyObject *PLy_notice(PyObject *, PyObject *);
1600 static PyObject *PLy_warning(PyObject *, PyObject *);
1601 static PyObject *PLy_error(PyObject *, PyObject *);
1602 static PyObject *PLy_fatal(PyObject *, PyObject *);
1604 /* PLyPlanObject, PLyResultObject and SPI interface
1606 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1607 static PyObject *PLy_plan_new(void);
1608 static void PLy_plan_dealloc(PyObject *);
1609 static PyObject *PLy_plan_getattr(PyObject *, char *);
1610 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1612 static PyObject *PLy_result_new(void);
1613 static void PLy_result_dealloc(PyObject *);
1614 static PyObject *PLy_result_getattr(PyObject *, char *);
1617 /* Appear to be unused */
1618 static PyObject *PLy_result_fetch(PyObject *, PyObject *);
1619 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1620 static PyObject *PLy_result_status(PyObject *, PyObject *);
1622 static int PLy_result_length(PyObject *);
1623 static PyObject *PLy_result_item(PyObject *, int);
1624 static PyObject *PLy_result_slice(PyObject *, int, int);
1625 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1626 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1629 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1630 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1631 static const char *PLy_spi_error_string(int);
1632 static PyObject *PLy_spi_execute_query(char *query, int limit);
1633 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, int);
1634 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1637 static PyTypeObject PLy_PlanType = {
1638 PyObject_HEAD_INIT(NULL)
1640 "PLyPlan", /* tp_name */
1641 sizeof(PLyPlanObject), /* tp_size */
1642 0, /* tp_itemsize */
1647 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1649 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1653 0, /* tp_as_number */
1654 0, /* tp_as_sequence */
1655 0, /* tp_as_mapping */
1659 0, /* tp_getattro */
1660 0, /* tp_setattro */
1661 0, /* tp_as_buffer */
1663 PLy_plan_doc, /* tp_doc */
1666 static PyMethodDef PLy_plan_methods[] = {
1667 {"status", (PyCFunction) PLy_plan_status, METH_VARARGS, NULL},
1668 {NULL, NULL, 0, NULL}
1672 static PySequenceMethods PLy_result_as_sequence = {
1673 (inquiry) PLy_result_length, /* sq_length */
1674 (binaryfunc) 0, /* sq_concat */
1675 (intargfunc) 0, /* sq_repeat */
1676 (intargfunc) PLy_result_item, /* sq_item */
1677 (intintargfunc) PLy_result_slice, /* sq_slice */
1678 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1679 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1682 static PyTypeObject PLy_ResultType = {
1683 PyObject_HEAD_INIT(NULL)
1685 "PLyResult", /* tp_name */
1686 sizeof(PLyResultObject), /* tp_size */
1687 0, /* tp_itemsize */
1692 (destructor) PLy_result_dealloc, /* tp_dealloc */
1694 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1698 0, /* tp_as_number */
1699 &PLy_result_as_sequence, /* tp_as_sequence */
1700 0, /* tp_as_mapping */
1704 0, /* tp_getattro */
1705 0, /* tp_setattro */
1706 0, /* tp_as_buffer */
1708 PLy_result_doc, /* tp_doc */
1712 /* Appear to be unused */
1713 static PyMethodDef PLy_result_methods[] = {
1714 {"fetch", (PyCFunction) PLy_result_fetch, METH_VARARGS, NULL,},
1715 {"nrows", (PyCFunction) PLy_result_nrows, METH_VARARGS, NULL},
1716 {"status", (PyCFunction) PLy_result_status, METH_VARARGS, NULL},
1717 {NULL, NULL, 0, NULL}
1721 static PyMethodDef PLy_methods[] = {
1725 {"debug", PLy_debug, METH_VARARGS, NULL},
1726 {"log", PLy_log, METH_VARARGS, NULL},
1727 {"info", PLy_info, METH_VARARGS, NULL},
1728 {"notice", PLy_notice, METH_VARARGS, NULL},
1729 {"warning", PLy_warning, METH_VARARGS, NULL},
1730 {"error", PLy_error, METH_VARARGS, NULL},
1731 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1734 * create a stored plan
1736 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1739 * execute a plan or query
1741 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1743 {NULL, NULL, 0, NULL}
1747 /* plan object methods
1756 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1764 return (PyObject *) ob;
1769 PLy_plan_dealloc(PyObject * arg)
1771 PLyPlanObject *ob = (PLyPlanObject *) arg;
1776 SPI_freeplan(ob->plan);
1778 PLy_free(ob->types);
1783 for (i = 0; i < ob->nargs; i++)
1784 PLy_typeinfo_dealloc(&ob->args[i]);
1795 PLy_plan_getattr(PyObject * self, char *name)
1797 return Py_FindMethod(PLy_plan_methods, self, name);
1801 PLy_plan_status(PyObject * self, PyObject * args)
1803 if (PyArg_ParseTuple(args, ""))
1807 /* return PyInt_FromLong(self->status); */
1809 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1815 /* result object methods
1819 PLy_result_new(void)
1821 PLyResultObject *ob;
1825 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1828 /* ob->tuples = NULL; */
1831 ob->status = Py_None;
1832 ob->nrows = PyInt_FromLong(-1);
1833 ob->rows = PyList_New(0);
1835 return (PyObject *) ob;
1839 PLy_result_dealloc(PyObject * arg)
1841 PLyResultObject *ob = (PLyResultObject *) arg;
1845 Py_XDECREF(ob->nrows);
1846 Py_XDECREF(ob->rows);
1847 Py_XDECREF(ob->status);
1853 PLy_result_getattr(PyObject * self, char *attr)
1859 /* Appear to be unused */
1861 PLy_result_fetch(PyObject * self, PyObject * args)
1867 PLy_result_nrows(PyObject * self, PyObject * args)
1869 PLyResultObject *ob = (PLyResultObject *) self;
1871 Py_INCREF(ob->nrows);
1876 PLy_result_status(PyObject * self, PyObject * args)
1878 PLyResultObject *ob = (PLyResultObject *) self;
1880 Py_INCREF(ob->status);
1885 PLy_result_length(PyObject * arg)
1887 PLyResultObject *ob = (PLyResultObject *) arg;
1889 return PyList_Size(ob->rows);
1893 PLy_result_item(PyObject * arg, int idx)
1896 PLyResultObject *ob = (PLyResultObject *) arg;
1898 rv = PyList_GetItem(ob->rows, idx);
1905 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1908 PLyResultObject *ob = (PLyResultObject *) arg;
1911 rv = PyList_SetItem(ob->rows, idx, item);
1916 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1919 PLyResultObject *ob = (PLyResultObject *) arg;
1921 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1929 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1932 PLyResultObject *ob = (PLyResultObject *) arg;
1934 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1941 PLy_spi_prepare(PyObject * self, PyObject * args)
1944 PLyPlanObject *plan;
1945 PyObject *list = NULL;
1946 PyObject *volatile optr = NULL;
1952 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1954 PyErr_SetString(PLy_exc_spi_error,
1955 "Invalid arguments for plpy.prepare()");
1959 if ((list) && (!PySequence_Check(list)))
1961 PyErr_SetString(PLy_exc_spi_error,
1962 "Second argument in plpy.prepare() must be a sequence");
1967 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1976 if (!PyErr_Occurred())
1977 PyErr_SetString(PLy_exc_spi_error,
1978 "Unknown error in PLy_spi_prepare");
1979 /* XXX this oughta be replaced with errcontext mechanism */
1980 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
1989 nargs = PySequence_Length(list);
1992 plan->nargs = nargs;
1993 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1994 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1995 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1998 * the other loop might throw an exception, if PLyTypeInfo
1999 * member isn't properly initialized the Py_DECREF(plan) will
2002 for (i = 0; i < nargs; i++)
2004 PLy_typeinfo_init(&plan->args[i]);
2005 plan->values[i] = (Datum) NULL;
2008 for (i = 0; i < nargs; i++)
2012 Form_pg_type typeStruct;
2014 optr = PySequence_GetItem(list, i);
2015 if (!PyString_Check(optr))
2017 PyErr_SetString(PLy_exc_spi_error,
2018 "Type names must be strings.");
2021 sptr = PyString_AsString(optr);
2022 /* XXX should extend this to allow qualified type names */
2023 typeTup = typenameType(makeTypeName(sptr));
2025 optr = NULL; /* this is important */
2027 plan->types[i] = HeapTupleGetOid(typeTup);
2028 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2029 if (typeStruct->typtype != 'c')
2030 PLy_output_datum_func(&plan->args[i], typeStruct);
2033 PyErr_SetString(PLy_exc_spi_error,
2034 "tuples not handled in plpy.prepare, yet.");
2037 ReleaseSysCache(typeTup);
2042 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2043 if (plan->plan == NULL)
2045 PLy_exception_set(PLy_exc_spi_error,
2046 "Unable to prepare plan. SPI_prepare failed -- %s.",
2047 PLy_spi_error_string(SPI_result));
2051 /* transfer plan from procCxt to topCxt */
2052 tmpplan = plan->plan;
2053 plan->plan = SPI_saveplan(tmpplan);
2054 SPI_freeplan(tmpplan);
2055 if (plan->plan == NULL)
2057 PLy_exception_set(PLy_exc_spi_error,
2058 "Unable to save plan. SPI_saveplan failed -- %s.",
2059 PLy_spi_error_string(SPI_result));
2065 return (PyObject *) plan;
2068 /* execute(query="select * from foo", limit=5)
2069 * execute(plan=plan, values=(foo, bar), limit=5)
2072 PLy_spi_execute(PyObject * self, PyObject * args)
2076 PyObject *list = NULL;
2084 * there should - hahaha - be an python exception set so just return
2085 * NULL. FIXME -- is this needed?
2087 if (PLy_restart_in_progress)
2091 if (PyArg_ParseTuple(args, "s|i", &query, &limit))
2092 return PLy_spi_execute_query(query, limit);
2096 if ((PyArg_ParseTuple(args, "O|Oi", &plan, &list, &limit)) &&
2097 (is_PLyPlanObject(plan)))
2099 PyObject *rv = PLy_spi_execute_plan(plan, list, limit);
2104 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2109 PLy_spi_execute_plan(PyObject * ob, PyObject * list, int limit)
2115 PLyPlanObject *plan;
2122 if ((!PySequence_Check(list)) || (PyString_Check(list)))
2124 char *msg = "plpy.execute() takes a sequence as its second argument";
2126 PyErr_SetString(PLy_exc_spi_error, msg);
2129 nargs = PySequence_Length(list);
2134 plan = (PLyPlanObject *) ob;
2136 if (nargs != plan->nargs)
2140 PyObject *so = PyObject_Str(list);
2142 sv = PyString_AsString(so);
2143 PLy_exception_set(PLy_exc_spi_error,
2144 "Expected sequence of %d arguments, got %d. %s",
2145 plan->nargs, nargs, sv);
2157 * cleanup plan->values array
2159 for (i = 0; i < nargs; i++)
2161 if (!plan->args[i].out.d.typbyval &&
2162 (plan->values[i] != (Datum) NULL))
2164 pfree(DatumGetPointer(plan->values[i]));
2165 plan->values[i] = (Datum) NULL;
2169 if (!PyErr_Occurred())
2170 PyErr_SetString(PLy_exc_error,
2171 "Unknown error in PLy_spi_execute_plan");
2172 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2176 nulls = palloc(nargs * sizeof(char));
2178 for (i = 0; i < nargs; i++)
2184 elem = PySequence_GetItem(list, i);
2185 if (elem != Py_None)
2187 so = PyObject_Str(elem);
2188 sv = PyString_AsString(so);
2191 * FIXME -- if this can elog, we have leak
2194 FunctionCall3(&(plan->args[i].out.d.typfunc),
2195 CStringGetDatum(sv),
2196 ObjectIdGetDatum(plan->args[i].out.d.typelem),
2207 plan->values[i] = (Datum) 0;
2212 rv = SPI_execp(plan->plan, plan->values, nulls, limit);
2218 for (i = 0; i < nargs; i++)
2220 if (!plan->args[i].out.d.typbyval &&
2221 (plan->values[i] != (Datum) NULL))
2223 pfree(DatumGetPointer(plan->values[i]));
2224 plan->values[i] = (Datum) NULL;
2230 PLy_exception_set(PLy_exc_spi_error,
2231 "Unable to execute plan. SPI_execp failed -- %s",
2232 PLy_spi_error_string(rv));
2236 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2240 PLy_spi_execute_query(char *query, int limit)
2249 if ((!PLy_restart_in_progress) && (!PyErr_Occurred()))
2250 PyErr_SetString(PLy_exc_spi_error,
2251 "Unknown error in PLy_spi_execute_query");
2252 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2256 rv = SPI_exec(query, limit);
2260 PLy_exception_set(PLy_exc_spi_error,
2261 "Unable to execute query. SPI_exec failed -- %s",
2262 PLy_spi_error_string(rv));
2266 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2270 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2272 PLyResultObject *result;
2276 result = (PLyResultObject *) PLy_result_new();
2277 Py_DECREF(result->status);
2278 result->status = PyInt_FromLong(status);
2280 if (status == SPI_OK_UTILITY)
2282 Py_DECREF(result->nrows);
2283 result->nrows = PyInt_FromLong(0);
2285 else if (status != SPI_OK_SELECT)
2287 Py_DECREF(result->nrows);
2288 result->nrows = PyInt_FromLong(rows);
2296 PLy_typeinfo_init(&args);
2297 Py_DECREF(result->nrows);
2298 result->nrows = PyInt_FromLong(rows);
2305 if (!PyErr_Occurred())
2306 PyErr_SetString(PLy_exc_error,
2307 "Unknown error in PLy_spi_execute_fetch_result");
2309 PLy_typeinfo_dealloc(&args);
2315 Py_DECREF(result->rows);
2316 result->rows = PyList_New(rows);
2318 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2319 for (i = 0; i < rows; i++)
2321 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2324 PyList_SetItem(result->rows, i, row);
2326 PLy_typeinfo_dealloc(&args);
2328 SPI_freetuptable(tuptable);
2333 return (PyObject *) result;
2337 PLy_spi_error_string(int code)
2341 case SPI_ERROR_TYPUNKNOWN:
2342 return "SPI_ERROR_TYPUNKNOWN";
2343 case SPI_ERROR_NOOUTFUNC:
2344 return "SPI_ERROR_NOOUTFUNC";
2345 case SPI_ERROR_NOATTRIBUTE:
2346 return "SPI_ERROR_NOATTRIBUTE";
2347 case SPI_ERROR_TRANSACTION:
2348 return "SPI_ERROR_TRANSACTION";
2349 case SPI_ERROR_PARAM:
2350 return "SPI_ERROR_PARAM";
2351 case SPI_ERROR_ARGUMENT:
2352 return "SPI_ERROR_ARGUMENT";
2353 case SPI_ERROR_CURSOR:
2354 return "SPI_ERROR_CURSOR";
2355 case SPI_ERROR_UNCONNECTED:
2356 return "SPI_ERROR_UNCONNECTED";
2357 case SPI_ERROR_OPUNKNOWN:
2358 return "SPI_ERROR_OPUNKNOWN";
2359 case SPI_ERROR_COPY:
2360 return "SPI_ERROR_COPY";
2361 case SPI_ERROR_CONNECT:
2362 return "SPI_ERROR_CONNECT";
2364 return "Unknown or Invalid code";
2367 /* language handler and interpreter initialization
2371 * plpython_init() - Initialize everything that can be
2372 * safely initialized during postmaster
2375 * DO NOT make this static --- it has to be callable by preload
2380 static volatile int init_active = 0;
2382 /* Do initialization only once */
2383 if (!PLy_first_call)
2389 elog(FATAL, "initialization of language module failed");
2395 if (PyErr_Occurred())
2396 PLy_elog(FATAL, "untrapped error in initialization");
2397 PLy_procedure_cache = PyDict_New();
2398 if (PLy_procedure_cache == NULL)
2399 PLy_elog(ERROR, "could not create procedure cache");
2409 /* Execute postmaster-startup safe initialization */
2414 * Any other initialization that must be done each time a new backend
2415 * starts -- currently none
2421 PLy_init_interp(void)
2427 mainmod = PyImport_AddModule("__main__");
2428 if ((mainmod == NULL) || (PyErr_Occurred()))
2429 PLy_elog(ERROR, "could not import \"__main__\" module.");
2431 PLy_interp_globals = PyModule_GetDict(mainmod);
2432 PLy_interp_safe_globals = PyDict_New();
2433 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2435 if ((PLy_interp_globals == NULL) || (PyErr_Occurred()))
2436 PLy_elog(ERROR, "could not initialize globals");
2451 * initialize plpy module
2453 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2454 plpy = Py_InitModule("plpy", PLy_methods);
2455 plpy_dict = PyModule_GetDict(plpy);
2457 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2459 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2460 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2461 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2462 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2463 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2464 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2467 * initialize main module, and add plpy
2469 main_mod = PyImport_AddModule("__main__");
2470 main_dict = PyModule_GetDict(main_mod);
2471 plpy_mod = PyImport_AddModule("plpy");
2472 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2473 if (PyErr_Occurred())
2474 elog(ERROR, "could not init plpy");
2477 /* the python interface to the elog function
2478 * don't confuse these with PLy_elog
2480 static PyObject *PLy_output(int, PyObject *, PyObject *);
2483 PLy_debug(PyObject * self, PyObject * args)
2485 return PLy_output(DEBUG2, self, args);
2489 PLy_log(PyObject * self, PyObject * args)
2491 return PLy_output(LOG, self, args);
2495 PLy_info(PyObject * self, PyObject * args)
2497 return PLy_output(INFO, self, args);
2501 PLy_notice(PyObject * self, PyObject * args)
2503 return PLy_output(NOTICE, self, args);
2507 PLy_warning(PyObject * self, PyObject * args)
2509 return PLy_output(WARNING, self, args);
2513 PLy_error(PyObject * self, PyObject * args)
2515 return PLy_output(ERROR, self, args);
2519 PLy_fatal(PyObject * self, PyObject * args)
2521 return PLy_output(FATAL, self, args);
2526 PLy_output(volatile int level, PyObject * self, PyObject * args)
2535 elog(WARNING, "args is NULL");
2537 so = PyObject_Str(args);
2538 if ((so == NULL) || ((sv = PyString_AsString(so)) == NULL))
2541 sv = "Unable to parse error message in `plpy.elog'";
2545 * returning NULL here causes the python interpreter to bail. when
2546 * control passes back into plpython_*_handler, we check for python
2547 * exceptions and do the actual elog call. actually PLy_elog.
2551 PyErr_SetString(PLy_exc_error, sv);
2554 else if (level >= FATAL)
2556 PyErr_SetString(PLy_exc_fatal, sv);
2561 * ok, this is a WARNING, or LOG message
2563 * but just in case DON'T long jump out of the interpreter!
2573 * the real error message should already be written into the
2574 * postgresql log, no? whatever, this shouldn't happen so die
2577 elog(FATAL, "elog threw an unknown exception");
2581 elog(level, "%s", sv);
2589 * return a legal object so the interpreter will continue on its merry
2597 * Get the last procedure name called by the backend ( the innermost,
2598 * If a plpython procedure call calls the backend and the backend calls
2599 * another plpython procedure )
2601 * NB: this returns SQL name, not the internal Python procedure name
2605 PLy_procedure_name(PLyProcedure * proc)
2608 return "<unknown procedure>";
2609 return proc->proname;
2612 /* output a python traceback/exception via the postgresql elog
2613 * function. not pretty.
2616 static char *PLy_traceback(int *);
2617 static char *PLy_vprintf(const char *fmt, va_list ap);
2618 static char *PLy_printf(const char *fmt,...);
2621 PLy_exception_set(PyObject * exc, const char *fmt,...)
2627 vsnprintf(buf, sizeof(buf), fmt, ap);
2630 PyErr_SetString(exc, buf);
2634 PLy_elog(int elevel, const char *fmt,...)
2644 xmsg = PLy_traceback(&xlevel);
2647 emsg = PLy_vprintf(fmt, ap);
2657 * elog called siglongjmp. cleanup, restore and reraise
2659 PLy_restart_in_progress += 1;
2667 (errmsg("plpython: %s", emsg),
2668 (xmsg) ? errdetail("%s", xmsg) : 0));
2680 PLy_traceback(int *xlevel)
2694 * get the current exception
2696 PyErr_Fetch(&e, &v, &tb);
2699 * oops, no exception, return
2707 PyErr_NormalizeException(&e, &v, &tb);
2709 eob = PyObject_Str(e);
2710 if ((v) && ((vob = PyObject_Str(v)) != NULL))
2711 vstr = PyString_AsString(vob);
2715 estr = PyString_AsString(eob);
2716 xstr = PLy_printf("%s: %s", estr, vstr);
2722 * intuit an appropriate error level for based on the exception type
2724 if ((PLy_exc_error) && (PyErr_GivenExceptionMatches(e, PLy_exc_error)))
2726 else if ((PLy_exc_fatal) && (PyErr_GivenExceptionMatches(e, PLy_exc_fatal)))
2737 PLy_printf(const char *fmt,...)
2743 emsg = PLy_vprintf(fmt, ap);
2749 PLy_vprintf(const char *fmt, va_list ap)
2756 blen = strlen(fmt) * 2;
2759 buf = PLy_malloc(blen * sizeof(char));
2763 bchar = vsnprintf(buf, blen, fmt, ap);
2764 if ((bchar > 0) && (bchar < blen))
2772 buf = PLy_realloc(buf, blen);
2778 /* python module code
2782 /* some dumb utility functions
2786 PLy_malloc(size_t bytes)
2788 void *ptr = malloc(bytes);
2792 (errcode(ERRCODE_OUT_OF_MEMORY),
2793 errmsg("out of memory")));
2798 PLy_realloc(void *optr, size_t bytes)
2800 void *nptr = realloc(optr, bytes);
2804 (errcode(ERRCODE_OUT_OF_MEMORY),
2805 errmsg("out of memory")));