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.47 2004/05/07 00:24:59 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 /* +1 to avoid palloc(0) on empty tuple */
535 modattrs = palloc(natts * sizeof(int) + 1);
536 modvalues = palloc(natts * sizeof(Datum) + 1);
537 modnulls = palloc(natts + 1);
539 tupdesc = tdata->tg_relation->rd_att;
541 for (i = 0; i < natts; i++)
545 platt = PyList_GetItem(plkeys, i);
546 if (!PyString_Check(platt))
547 elog(ERROR, "attribute name is not a string");
548 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
549 if (attn == SPI_ERROR_NOATTRIBUTE)
550 elog(ERROR, "invalid attribute \"%s\" in tuple",
551 PyString_AsString(platt));
554 plval = PyDict_GetItem(plntup, platt);
556 elog(FATAL, "python interpreter is probably corrupted");
562 if (plval != Py_None && !tupdesc->attrs[atti]->attisdropped)
564 plstr = PyObject_Str(plval);
565 src = PyString_AsString(plstr);
567 modvalues[i] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
568 CStringGetDatum(src),
569 ObjectIdGetDatum(proc->result.out.r.atts[atti].typelem),
570 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
578 modvalues[i] = (Datum) 0;
586 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
587 modattrs, modvalues, modnulls);
590 * FIXME -- these leak if not explicitly pfree'd by other elog calls,
591 * no? (No, I think, but might as well leave the pfrees here...)
598 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
609 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
621 PyObject *volatile pltdata = NULL;
636 tdata = (TriggerData *) fcinfo->context;
638 pltdata = PyDict_New();
640 PLy_elog(ERROR, "could not build arguments for trigger procedure");
642 pltname = PyString_FromString(tdata->tg_trigger->tgname);
643 PyDict_SetItemString(pltdata, "name", pltname);
646 stroid = DatumGetCString(DirectFunctionCall1(oidout,
647 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
648 pltrelid = PyString_FromString(stroid);
649 PyDict_SetItemString(pltdata, "relid", pltrelid);
653 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
654 pltwhen = PyString_FromString("BEFORE");
655 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
656 pltwhen = PyString_FromString("AFTER");
659 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
660 pltwhen = NULL; /* keep compiler quiet */
662 PyDict_SetItemString(pltdata, "when", pltwhen);
665 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
667 pltlevel = PyString_FromString("ROW");
668 PyDict_SetItemString(pltdata, "level", pltlevel);
671 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
673 pltevent = PyString_FromString("INSERT");
675 PyDict_SetItemString(pltdata, "old", Py_None);
676 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
677 tdata->tg_relation->rd_att);
678 PyDict_SetItemString(pltdata, "new", pytnew);
680 *rv = tdata->tg_trigtuple;
682 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
684 pltevent = PyString_FromString("DELETE");
686 PyDict_SetItemString(pltdata, "new", Py_None);
687 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
688 tdata->tg_relation->rd_att);
689 PyDict_SetItemString(pltdata, "old", pytold);
691 *rv = tdata->tg_trigtuple;
693 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
695 pltevent = PyString_FromString("UPDATE");
697 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
698 tdata->tg_relation->rd_att);
699 PyDict_SetItemString(pltdata, "new", pytnew);
701 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
702 tdata->tg_relation->rd_att);
703 PyDict_SetItemString(pltdata, "old", pytold);
705 *rv = tdata->tg_newtuple;
709 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
710 pltevent = NULL; /* keep compiler quiet */
713 PyDict_SetItemString(pltdata, "event", pltevent);
716 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
718 pltlevel = PyString_FromString("STATEMENT");
719 PyDict_SetItemString(pltdata, "level", pltlevel);
722 PyDict_SetItemString(pltdata, "old", Py_None);
723 PyDict_SetItemString(pltdata, "new", Py_None);
726 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
727 pltevent = PyString_FromString("INSERT");
728 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
729 pltevent = PyString_FromString("DELETE");
730 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
731 pltevent = PyString_FromString("UPDATE");
734 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
735 pltevent = NULL; /* keep compiler quiet */
738 PyDict_SetItemString(pltdata, "event", pltevent);
742 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
744 if (tdata->tg_trigger->tgnargs)
752 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
753 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
755 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
758 * stolen, don't Py_DECREF
760 PyList_SetItem(pltargs, i, pltarg);
768 PyDict_SetItemString(pltdata, "args", pltargs);
778 /* function handler and friends
781 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
785 PyObject *volatile plargs = NULL;
786 PyObject *volatile plrv = NULL;
787 PyObject *volatile plrv_so = NULL;
793 * setup to catch elog in while building function arguments, and
794 * DECREF the plargs if the function call fails
808 plargs = PLy_function_build_args(fcinfo, proc);
809 plrv = PLy_procedure_call(proc, "args", plargs);
812 * Disconnect from SPI manager and then create the return values datum
813 * (if the input function does a palloc for it this must not be
814 * allocated in the SPI memory context because SPI_finish would free
817 if (SPI_finish() != SPI_OK_FINISH)
818 elog(ERROR, "SPI_finish failed");
822 elog(FATAL, "PLy_procedure_call returned NULL");
824 if (!PLy_restart_in_progress)
825 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
828 * FIXME is this dead code? i'm pretty sure it is for unnested
829 * calls, but not for nested calls
836 * convert the python PyObject to a postgresql Datum FIXME returning a
837 * NULL, ie PG_RETURN_NULL() blows the backend to small messy bits...
838 * it this a bug or expected? so just call with the string value of
844 fcinfo->isnull = true;
849 fcinfo->isnull = false;
850 plrv_so = PyObject_Str(plrv);
851 plrv_sc = PyString_AsString(plrv_so);
852 rv = FunctionCall3(&proc->result.out.d.typfunc,
853 PointerGetDatum(plrv_sc),
854 ObjectIdGetDatum(proc->result.out.d.typelem),
868 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
871 PLyProcedure *current;
875 current = PLy_last_procedure;
876 PLy_last_procedure = proc;
877 PyDict_SetItemString(proc->globals, kargs, vargs);
878 rv = PyEval_EvalCode((PyCodeObject *) proc->code, proc->globals, proc->globals);
879 PLy_last_procedure = current;
881 if ((rv == NULL) || (PyErr_Occurred()))
884 if (!PLy_restart_in_progress)
885 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
893 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
896 PyObject *volatile arg = NULL;
897 PyObject *volatile args = NULL;
903 * FIXME -- if the setjmp setup is expensive, add the arg and args
904 * field to the procedure struct and cleanup at the start of the next
917 args = PyList_New(proc->nargs);
918 for (i = 0; i < proc->nargs; i++)
920 if (proc->args[i].is_rowtype > 0)
922 if (fcinfo->argnull[i])
930 HeapTupleData tmptup;
932 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
933 /* Extract rowtype info and find a tupdesc */
934 tupType = HeapTupleHeaderGetTypeId(td);
935 tupTypmod = HeapTupleHeaderGetTypMod(td);
936 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
938 /* Set up I/O funcs if not done yet */
939 if (proc->args[i].is_rowtype != 1)
940 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
942 /* Build a temporary HeapTuple control structure */
943 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
946 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
951 if (fcinfo->argnull[i])
958 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
960 ObjectIdGetDatum(proc->args[i].in.d.typelem),
962 ct = DatumGetCString(dt);
963 arg = (proc->args[i].in.d.func) (ct);
975 * FIXME -- error check this
977 PyList_SetItem(args, i, arg);
987 * PLyProcedure functions
990 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
991 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
992 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
995 static PLyProcedure *
996 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
1002 PLyProcedure *proc = NULL;
1007 fn_oid = fcinfo->flinfo->fn_oid;
1008 procTup = SearchSysCache(PROCOID,
1009 ObjectIdGetDatum(fn_oid),
1011 if (!HeapTupleIsValid(procTup))
1012 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1014 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
1015 if ((rv >= sizeof(key)) || (rv < 0))
1016 elog(ERROR, "key too long");
1018 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
1023 if (!PyCObject_Check(plproc))
1024 elog(FATAL, "expected a PyCObject, didn't get one");
1028 proc = PyCObject_AsVoidPtr(plproc);
1029 if (proc->me != plproc)
1030 elog(FATAL, "proc->me != plproc");
1031 /* did we find an up-to-date cache entry? */
1032 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
1033 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
1041 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
1043 ReleaseSysCache(procTup);
1048 static PLyProcedure *
1049 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
1050 HeapTuple procTup, char *key)
1052 char procName[NAMEDATALEN + 256];
1055 Form_pg_proc procStruct;
1056 PLyProcedure *volatile proc;
1057 char *volatile procSource = NULL;
1065 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1067 if (OidIsValid(tgreloid))
1068 rv = snprintf(procName, sizeof(procName),
1069 "__plpython_procedure_%s_%u_trigger_%u",
1070 NameStr(procStruct->proname),
1071 fcinfo->flinfo->fn_oid,
1074 rv = snprintf(procName, sizeof(procName),
1075 "__plpython_procedure_%s_%u",
1076 NameStr(procStruct->proname),
1077 fcinfo->flinfo->fn_oid);
1078 if ((rv >= sizeof(procName)) || (rv < 0))
1079 elog(ERROR, "procedure name would overrun buffer");
1081 proc = PLy_malloc(sizeof(PLyProcedure));
1082 proc->proname = PLy_malloc(strlen(NameStr(procStruct->proname)) + 1);
1083 strcpy(proc->proname, NameStr(procStruct->proname));
1084 proc->pyname = PLy_malloc(strlen(procName) + 1);
1085 strcpy(proc->pyname, procName);
1086 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1087 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1088 PLy_typeinfo_init(&proc->result);
1089 for (i = 0; i < FUNC_MAX_ARGS; i++)
1090 PLy_typeinfo_init(&proc->args[i]);
1092 proc->code = proc->statics = NULL;
1093 proc->globals = proc->me = NULL;
1099 PLy_procedure_delete(proc);
1106 * get information required for output conversion of the return value,
1107 * but only if this isn't a trigger.
1109 if (!CALLED_AS_TRIGGER(fcinfo))
1111 HeapTuple rvTypeTup;
1112 Form_pg_type rvTypeStruct;
1114 rvTypeTup = SearchSysCache(TYPEOID,
1115 ObjectIdGetDatum(procStruct->prorettype),
1117 if (!HeapTupleIsValid(rvTypeTup))
1118 elog(ERROR, "cache lookup failed for type %u",
1119 procStruct->prorettype);
1121 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1122 if (rvTypeStruct->typtype != 'c')
1123 PLy_output_datum_func(&proc->result, rvTypeStruct);
1126 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1127 errmsg("tuple return types are not supported yet")));
1129 ReleaseSysCache(rvTypeTup);
1134 * input/output conversion for trigger tuples. use the result
1135 * TypeInfo variable to store the tuple conversion info.
1137 TriggerData *tdata = (TriggerData *) fcinfo->context;
1139 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1140 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1144 * now get information required for input conversion of the procedures
1147 proc->nargs = fcinfo->nargs;
1148 for (i = 0; i < fcinfo->nargs; i++)
1150 HeapTuple argTypeTup;
1151 Form_pg_type argTypeStruct;
1153 argTypeTup = SearchSysCache(TYPEOID,
1154 ObjectIdGetDatum(procStruct->proargtypes[i]),
1156 if (!HeapTupleIsValid(argTypeTup))
1157 elog(ERROR, "cache lookup failed for type %u",
1158 procStruct->proargtypes[i]);
1159 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1161 if (argTypeStruct->typtype != 'c')
1162 PLy_input_datum_func(&(proc->args[i]),
1163 procStruct->proargtypes[i],
1166 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1168 ReleaseSysCache(argTypeTup);
1173 * get the text of the function.
1175 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1176 Anum_pg_proc_prosrc, &isnull);
1178 elog(ERROR, "null prosrc");
1179 procSource = DatumGetCString(DirectFunctionCall1(textout,
1182 PLy_procedure_compile(proc, procSource);
1186 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1187 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1195 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1197 PyObject *crv = NULL;
1202 proc->globals = PyDict_Copy(PLy_interp_globals);
1205 * SD is private preserved data between calls GD is global data shared
1208 proc->statics = PyDict_New();
1209 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1212 * insert the function code into the interpreter
1214 msrc = PLy_procedure_munge_source(proc->pyname, src);
1215 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1218 if ((crv != NULL) && (!PyErr_Occurred()))
1221 char call[NAMEDATALEN + 256];
1226 * compile a call to the function
1228 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1229 if ((clen < 0) || (clen >= sizeof(call)))
1230 elog(ERROR, "string would overflow buffer");
1231 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1232 if ((proc->code != NULL) && (!PyErr_Occurred()))
1238 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1242 PLy_procedure_munge_source(const char *name, const char *src)
1253 * room for function source and the def statement
1255 mlen = (strlen(src) * 2) + strlen(name) + 16;
1257 mrc = PLy_malloc(mlen);
1258 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1259 Assert(plen >= 0 && plen < mlen);
1278 if (mp > (mrc + mlen))
1279 elog(FATAL, "buffer overrun in PLy_munge_source");
1285 PLy_procedure_delete(PLyProcedure * proc)
1291 Py_XDECREF(proc->code);
1292 Py_XDECREF(proc->statics);
1293 Py_XDECREF(proc->globals);
1294 Py_XDECREF(proc->me);
1296 PLy_free(proc->proname);
1298 PLy_free(proc->pyname);
1299 for (i = 0; i < proc->nargs; i++)
1300 if (proc->args[i].is_rowtype == 1)
1302 if (proc->args[i].in.r.atts)
1303 PLy_free(proc->args[i].in.r.atts);
1304 if (proc->args[i].out.r.atts)
1305 PLy_free(proc->args[i].out.r.atts);
1311 /* conversion functions. remember output from python is
1312 * input to postgresql, and vis versa.
1315 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1321 if (arg->is_rowtype == 0)
1322 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1324 arg->is_rowtype = 1;
1325 arg->in.r.natts = desc->natts;
1326 arg->in.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1328 for (i = 0; i < desc->natts; i++)
1331 Form_pg_type typeStruct;
1333 if (desc->attrs[i]->attisdropped)
1336 typeTup = SearchSysCache(TYPEOID,
1337 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1339 if (!HeapTupleIsValid(typeTup))
1340 elog(ERROR, "cache lookup failed for type %u",
1341 desc->attrs[i]->atttypid);
1342 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1344 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1345 desc->attrs[i]->atttypid,
1348 ReleaseSysCache(typeTup);
1353 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1359 if (arg->is_rowtype == 0)
1360 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1362 arg->is_rowtype = 1;
1363 arg->out.r.natts = desc->natts;
1364 arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1366 for (i = 0; i < desc->natts; i++)
1369 Form_pg_type typeStruct;
1371 if (desc->attrs[i]->attisdropped)
1374 typeTup = SearchSysCache(TYPEOID,
1375 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1377 if (!HeapTupleIsValid(typeTup))
1378 elog(ERROR, "cache lookup failed for type %u",
1379 desc->attrs[i]->atttypid);
1380 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1382 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeStruct);
1384 ReleaseSysCache(typeTup);
1389 PLy_output_datum_func(PLyTypeInfo * arg, Form_pg_type typeStruct)
1393 if (arg->is_rowtype > 0)
1394 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1395 arg->is_rowtype = 0;
1396 PLy_output_datum_func2(&(arg->out.d), typeStruct);
1400 PLy_output_datum_func2(PLyObToDatum * arg, Form_pg_type typeStruct)
1404 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1405 arg->typelem = typeStruct->typelem;
1406 arg->typbyval = typeStruct->typbyval;
1410 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, Form_pg_type typeStruct)
1414 if (arg->is_rowtype > 0)
1415 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1416 arg->is_rowtype = 0;
1417 PLy_input_datum_func2(&(arg->in.d), typeOid, typeStruct);
1421 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, Form_pg_type typeStruct)
1423 /* Get the type's conversion information */
1424 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1425 arg->typelem = typeStruct->typelem;
1426 arg->typbyval = typeStruct->typbyval;
1428 /* Determine which kind of Python object we will convert to */
1432 arg->func = PLyBool_FromString;
1437 arg->func = PLyFloat_FromString;
1441 arg->func = PLyInt_FromString;
1444 arg->func = PLyLong_FromString;
1447 arg->func = PLyString_FromString;
1453 PLy_typeinfo_init(PLyTypeInfo * arg)
1455 arg->is_rowtype = -1;
1456 arg->in.r.natts = arg->out.r.natts = 0;
1457 arg->in.r.atts = NULL;
1458 arg->out.r.atts = NULL;
1462 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1464 if (arg->is_rowtype == 1)
1467 PLy_free(arg->in.r.atts);
1468 if (arg->out.r.atts)
1469 PLy_free(arg->out.r.atts);
1473 /* assumes that a bool is always returned as a 't' or 'f'
1476 PLyBool_FromString(const char *src)
1481 return PyInt_FromLong(1);
1482 return PyInt_FromLong(0);
1486 PLyFloat_FromString(const char *src)
1494 v = strtod(src, &eptr);
1495 if ((*eptr != '\0') || (errno))
1497 return PyFloat_FromDouble(v);
1501 PLyInt_FromString(const char *src)
1509 v = strtol(src, &eptr, 0);
1510 if ((*eptr != '\0') || (errno))
1512 return PyInt_FromLong(v);
1516 PLyLong_FromString(const char *src)
1518 return PyLong_FromString((char *) src, NULL, 0);
1522 PLyString_FromString(const char *src)
1524 return PyString_FromString(src);
1528 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1531 PyObject *volatile dict;
1536 if (info->is_rowtype != 1)
1537 elog(ERROR, "PLyTypeInfo structure describes a datum");
1539 dict = PyDict_New();
1541 PLy_elog(ERROR, "could not create tuple dictionary");
1552 for (i = 0; i < info->in.r.natts; i++)
1561 if (desc->attrs[i]->attisdropped)
1564 key = NameStr(desc->attrs[i]->attname);
1565 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1567 if ((is_null) || (info->in.r.atts[i].func == NULL))
1568 PyDict_SetItemString(dict, key, Py_None);
1571 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1573 ObjectIdGetDatum(info->in.r.atts[i].typelem),
1574 Int32GetDatum(desc->attrs[i]->atttypmod));
1575 vsrc = DatumGetCString(vdat);
1578 * no exceptions allowed
1580 value = info->in.r.atts[i].func(vsrc);
1582 PyDict_SetItemString(dict, key, value);
1592 /* initialization, some python variables function declared here
1595 /* interface to postgresql elog
1597 static PyObject *PLy_debug(PyObject *, PyObject *);
1598 static PyObject *PLy_log(PyObject *, PyObject *);
1599 static PyObject *PLy_info(PyObject *, PyObject *);
1600 static PyObject *PLy_notice(PyObject *, PyObject *);
1601 static PyObject *PLy_warning(PyObject *, PyObject *);
1602 static PyObject *PLy_error(PyObject *, PyObject *);
1603 static PyObject *PLy_fatal(PyObject *, PyObject *);
1605 /* PLyPlanObject, PLyResultObject and SPI interface
1607 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1608 static PyObject *PLy_plan_new(void);
1609 static void PLy_plan_dealloc(PyObject *);
1610 static PyObject *PLy_plan_getattr(PyObject *, char *);
1611 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1613 static PyObject *PLy_result_new(void);
1614 static void PLy_result_dealloc(PyObject *);
1615 static PyObject *PLy_result_getattr(PyObject *, char *);
1618 /* Appear to be unused */
1619 static PyObject *PLy_result_fetch(PyObject *, PyObject *);
1620 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1621 static PyObject *PLy_result_status(PyObject *, PyObject *);
1623 static int PLy_result_length(PyObject *);
1624 static PyObject *PLy_result_item(PyObject *, int);
1625 static PyObject *PLy_result_slice(PyObject *, int, int);
1626 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1627 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1630 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1631 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1632 static const char *PLy_spi_error_string(int);
1633 static PyObject *PLy_spi_execute_query(char *query, int limit);
1634 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, int);
1635 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1638 static PyTypeObject PLy_PlanType = {
1639 PyObject_HEAD_INIT(NULL)
1641 "PLyPlan", /* tp_name */
1642 sizeof(PLyPlanObject), /* tp_size */
1643 0, /* tp_itemsize */
1648 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1650 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1654 0, /* tp_as_number */
1655 0, /* tp_as_sequence */
1656 0, /* tp_as_mapping */
1660 0, /* tp_getattro */
1661 0, /* tp_setattro */
1662 0, /* tp_as_buffer */
1664 PLy_plan_doc, /* tp_doc */
1667 static PyMethodDef PLy_plan_methods[] = {
1668 {"status", (PyCFunction) PLy_plan_status, METH_VARARGS, NULL},
1669 {NULL, NULL, 0, NULL}
1673 static PySequenceMethods PLy_result_as_sequence = {
1674 (inquiry) PLy_result_length, /* sq_length */
1675 (binaryfunc) 0, /* sq_concat */
1676 (intargfunc) 0, /* sq_repeat */
1677 (intargfunc) PLy_result_item, /* sq_item */
1678 (intintargfunc) PLy_result_slice, /* sq_slice */
1679 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1680 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1683 static PyTypeObject PLy_ResultType = {
1684 PyObject_HEAD_INIT(NULL)
1686 "PLyResult", /* tp_name */
1687 sizeof(PLyResultObject), /* tp_size */
1688 0, /* tp_itemsize */
1693 (destructor) PLy_result_dealloc, /* tp_dealloc */
1695 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1699 0, /* tp_as_number */
1700 &PLy_result_as_sequence, /* tp_as_sequence */
1701 0, /* tp_as_mapping */
1705 0, /* tp_getattro */
1706 0, /* tp_setattro */
1707 0, /* tp_as_buffer */
1709 PLy_result_doc, /* tp_doc */
1713 /* Appear to be unused */
1714 static PyMethodDef PLy_result_methods[] = {
1715 {"fetch", (PyCFunction) PLy_result_fetch, METH_VARARGS, NULL,},
1716 {"nrows", (PyCFunction) PLy_result_nrows, METH_VARARGS, NULL},
1717 {"status", (PyCFunction) PLy_result_status, METH_VARARGS, NULL},
1718 {NULL, NULL, 0, NULL}
1722 static PyMethodDef PLy_methods[] = {
1726 {"debug", PLy_debug, METH_VARARGS, NULL},
1727 {"log", PLy_log, METH_VARARGS, NULL},
1728 {"info", PLy_info, METH_VARARGS, NULL},
1729 {"notice", PLy_notice, METH_VARARGS, NULL},
1730 {"warning", PLy_warning, METH_VARARGS, NULL},
1731 {"error", PLy_error, METH_VARARGS, NULL},
1732 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1735 * create a stored plan
1737 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1740 * execute a plan or query
1742 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1744 {NULL, NULL, 0, NULL}
1748 /* plan object methods
1757 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1765 return (PyObject *) ob;
1770 PLy_plan_dealloc(PyObject * arg)
1772 PLyPlanObject *ob = (PLyPlanObject *) arg;
1777 SPI_freeplan(ob->plan);
1779 PLy_free(ob->types);
1784 for (i = 0; i < ob->nargs; i++)
1785 PLy_typeinfo_dealloc(&ob->args[i]);
1796 PLy_plan_getattr(PyObject * self, char *name)
1798 return Py_FindMethod(PLy_plan_methods, self, name);
1802 PLy_plan_status(PyObject * self, PyObject * args)
1804 if (PyArg_ParseTuple(args, ""))
1808 /* return PyInt_FromLong(self->status); */
1810 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1816 /* result object methods
1820 PLy_result_new(void)
1822 PLyResultObject *ob;
1826 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1829 /* ob->tuples = NULL; */
1832 ob->status = Py_None;
1833 ob->nrows = PyInt_FromLong(-1);
1834 ob->rows = PyList_New(0);
1836 return (PyObject *) ob;
1840 PLy_result_dealloc(PyObject * arg)
1842 PLyResultObject *ob = (PLyResultObject *) arg;
1846 Py_XDECREF(ob->nrows);
1847 Py_XDECREF(ob->rows);
1848 Py_XDECREF(ob->status);
1854 PLy_result_getattr(PyObject * self, char *attr)
1860 /* Appear to be unused */
1862 PLy_result_fetch(PyObject * self, PyObject * args)
1868 PLy_result_nrows(PyObject * self, PyObject * args)
1870 PLyResultObject *ob = (PLyResultObject *) self;
1872 Py_INCREF(ob->nrows);
1877 PLy_result_status(PyObject * self, PyObject * args)
1879 PLyResultObject *ob = (PLyResultObject *) self;
1881 Py_INCREF(ob->status);
1886 PLy_result_length(PyObject * arg)
1888 PLyResultObject *ob = (PLyResultObject *) arg;
1890 return PyList_Size(ob->rows);
1894 PLy_result_item(PyObject * arg, int idx)
1897 PLyResultObject *ob = (PLyResultObject *) arg;
1899 rv = PyList_GetItem(ob->rows, idx);
1906 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1909 PLyResultObject *ob = (PLyResultObject *) arg;
1912 rv = PyList_SetItem(ob->rows, idx, item);
1917 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1920 PLyResultObject *ob = (PLyResultObject *) arg;
1922 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1930 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1933 PLyResultObject *ob = (PLyResultObject *) arg;
1935 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1942 PLy_spi_prepare(PyObject * self, PyObject * args)
1945 PLyPlanObject *plan;
1946 PyObject *list = NULL;
1947 PyObject *volatile optr = NULL;
1953 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1955 PyErr_SetString(PLy_exc_spi_error,
1956 "Invalid arguments for plpy.prepare()");
1960 if ((list) && (!PySequence_Check(list)))
1962 PyErr_SetString(PLy_exc_spi_error,
1963 "Second argument in plpy.prepare() must be a sequence");
1968 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1977 if (!PyErr_Occurred())
1978 PyErr_SetString(PLy_exc_spi_error,
1979 "Unknown error in PLy_spi_prepare");
1980 /* XXX this oughta be replaced with errcontext mechanism */
1981 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
1990 nargs = PySequence_Length(list);
1993 plan->nargs = nargs;
1994 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1995 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1996 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1999 * the other loop might throw an exception, if PLyTypeInfo
2000 * member isn't properly initialized the Py_DECREF(plan) will
2003 for (i = 0; i < nargs; i++)
2005 PLy_typeinfo_init(&plan->args[i]);
2006 plan->values[i] = (Datum) NULL;
2009 for (i = 0; i < nargs; i++)
2013 Form_pg_type typeStruct;
2015 optr = PySequence_GetItem(list, i);
2016 if (!PyString_Check(optr))
2018 PyErr_SetString(PLy_exc_spi_error,
2019 "Type names must be strings.");
2022 sptr = PyString_AsString(optr);
2023 /* XXX should extend this to allow qualified type names */
2024 typeTup = typenameType(makeTypeName(sptr));
2026 optr = NULL; /* this is important */
2028 plan->types[i] = HeapTupleGetOid(typeTup);
2029 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2030 if (typeStruct->typtype != 'c')
2031 PLy_output_datum_func(&plan->args[i], typeStruct);
2034 PyErr_SetString(PLy_exc_spi_error,
2035 "tuples not handled in plpy.prepare, yet.");
2038 ReleaseSysCache(typeTup);
2043 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2044 if (plan->plan == NULL)
2046 PLy_exception_set(PLy_exc_spi_error,
2047 "Unable to prepare plan. SPI_prepare failed -- %s.",
2048 PLy_spi_error_string(SPI_result));
2052 /* transfer plan from procCxt to topCxt */
2053 tmpplan = plan->plan;
2054 plan->plan = SPI_saveplan(tmpplan);
2055 SPI_freeplan(tmpplan);
2056 if (plan->plan == NULL)
2058 PLy_exception_set(PLy_exc_spi_error,
2059 "Unable to save plan. SPI_saveplan failed -- %s.",
2060 PLy_spi_error_string(SPI_result));
2066 return (PyObject *) plan;
2069 /* execute(query="select * from foo", limit=5)
2070 * execute(plan=plan, values=(foo, bar), limit=5)
2073 PLy_spi_execute(PyObject * self, PyObject * args)
2077 PyObject *list = NULL;
2085 * there should - hahaha - be an python exception set so just return
2086 * NULL. FIXME -- is this needed?
2088 if (PLy_restart_in_progress)
2092 if (PyArg_ParseTuple(args, "s|i", &query, &limit))
2093 return PLy_spi_execute_query(query, limit);
2097 if ((PyArg_ParseTuple(args, "O|Oi", &plan, &list, &limit)) &&
2098 (is_PLyPlanObject(plan)))
2100 PyObject *rv = PLy_spi_execute_plan(plan, list, limit);
2105 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2110 PLy_spi_execute_plan(PyObject * ob, PyObject * list, int limit)
2116 PLyPlanObject *plan;
2123 if ((!PySequence_Check(list)) || (PyString_Check(list)))
2125 char *msg = "plpy.execute() takes a sequence as its second argument";
2127 PyErr_SetString(PLy_exc_spi_error, msg);
2130 nargs = PySequence_Length(list);
2135 plan = (PLyPlanObject *) ob;
2137 if (nargs != plan->nargs)
2141 PyObject *so = PyObject_Str(list);
2143 sv = PyString_AsString(so);
2144 PLy_exception_set(PLy_exc_spi_error,
2145 "Expected sequence of %d arguments, got %d. %s",
2146 plan->nargs, nargs, sv);
2158 * cleanup plan->values array
2160 for (i = 0; i < nargs; i++)
2162 if (!plan->args[i].out.d.typbyval &&
2163 (plan->values[i] != (Datum) NULL))
2165 pfree(DatumGetPointer(plan->values[i]));
2166 plan->values[i] = (Datum) NULL;
2170 if (!PyErr_Occurred())
2171 PyErr_SetString(PLy_exc_error,
2172 "Unknown error in PLy_spi_execute_plan");
2173 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2179 nulls = palloc((nargs + 1) * sizeof(char));
2181 for (i = 0; i < nargs; i++)
2187 elem = PySequence_GetItem(list, i);
2188 if (elem != Py_None)
2190 so = PyObject_Str(elem);
2191 sv = PyString_AsString(so);
2194 * FIXME -- if this can elog, we have leak
2196 plan->values[i] = FunctionCall3(&(plan->args[i].out.d.typfunc),
2197 CStringGetDatum(sv),
2198 ObjectIdGetDatum(plan->args[i].out.d.typelem),
2209 plan->values[i] = (Datum) 0;
2218 rv = SPI_execp(plan->plan, plan->values, nulls, limit);
2221 for (i = 0; i < nargs; i++)
2223 if (!plan->args[i].out.d.typbyval &&
2224 (plan->values[i] != (Datum) NULL))
2226 pfree(DatumGetPointer(plan->values[i]));
2227 plan->values[i] = (Datum) NULL;
2233 PLy_exception_set(PLy_exc_spi_error,
2234 "Unable to execute plan. SPI_execp failed -- %s",
2235 PLy_spi_error_string(rv));
2239 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2243 PLy_spi_execute_query(char *query, int limit)
2252 if ((!PLy_restart_in_progress) && (!PyErr_Occurred()))
2253 PyErr_SetString(PLy_exc_spi_error,
2254 "Unknown error in PLy_spi_execute_query");
2255 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2259 rv = SPI_exec(query, limit);
2263 PLy_exception_set(PLy_exc_spi_error,
2264 "Unable to execute query. SPI_exec failed -- %s",
2265 PLy_spi_error_string(rv));
2269 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2273 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2275 PLyResultObject *result;
2279 result = (PLyResultObject *) PLy_result_new();
2280 Py_DECREF(result->status);
2281 result->status = PyInt_FromLong(status);
2283 if (status == SPI_OK_UTILITY)
2285 Py_DECREF(result->nrows);
2286 result->nrows = PyInt_FromLong(0);
2288 else if (status != SPI_OK_SELECT)
2290 Py_DECREF(result->nrows);
2291 result->nrows = PyInt_FromLong(rows);
2299 PLy_typeinfo_init(&args);
2300 Py_DECREF(result->nrows);
2301 result->nrows = PyInt_FromLong(rows);
2308 if (!PyErr_Occurred())
2309 PyErr_SetString(PLy_exc_error,
2310 "Unknown error in PLy_spi_execute_fetch_result");
2312 PLy_typeinfo_dealloc(&args);
2318 Py_DECREF(result->rows);
2319 result->rows = PyList_New(rows);
2321 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2322 for (i = 0; i < rows; i++)
2324 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2327 PyList_SetItem(result->rows, i, row);
2329 PLy_typeinfo_dealloc(&args);
2331 SPI_freetuptable(tuptable);
2336 return (PyObject *) result;
2340 PLy_spi_error_string(int code)
2344 case SPI_ERROR_TYPUNKNOWN:
2345 return "SPI_ERROR_TYPUNKNOWN";
2346 case SPI_ERROR_NOOUTFUNC:
2347 return "SPI_ERROR_NOOUTFUNC";
2348 case SPI_ERROR_NOATTRIBUTE:
2349 return "SPI_ERROR_NOATTRIBUTE";
2350 case SPI_ERROR_TRANSACTION:
2351 return "SPI_ERROR_TRANSACTION";
2352 case SPI_ERROR_PARAM:
2353 return "SPI_ERROR_PARAM";
2354 case SPI_ERROR_ARGUMENT:
2355 return "SPI_ERROR_ARGUMENT";
2356 case SPI_ERROR_CURSOR:
2357 return "SPI_ERROR_CURSOR";
2358 case SPI_ERROR_UNCONNECTED:
2359 return "SPI_ERROR_UNCONNECTED";
2360 case SPI_ERROR_OPUNKNOWN:
2361 return "SPI_ERROR_OPUNKNOWN";
2362 case SPI_ERROR_COPY:
2363 return "SPI_ERROR_COPY";
2364 case SPI_ERROR_CONNECT:
2365 return "SPI_ERROR_CONNECT";
2367 return "Unknown or Invalid code";
2370 /* language handler and interpreter initialization
2374 * plpython_init() - Initialize everything that can be
2375 * safely initialized during postmaster
2378 * DO NOT make this static --- it has to be callable by preload
2383 static volatile int init_active = 0;
2385 /* Do initialization only once */
2386 if (!PLy_first_call)
2392 elog(FATAL, "initialization of language module failed");
2398 if (PyErr_Occurred())
2399 PLy_elog(FATAL, "untrapped error in initialization");
2400 PLy_procedure_cache = PyDict_New();
2401 if (PLy_procedure_cache == NULL)
2402 PLy_elog(ERROR, "could not create procedure cache");
2412 /* Execute postmaster-startup safe initialization */
2417 * Any other initialization that must be done each time a new backend
2418 * starts -- currently none
2424 PLy_init_interp(void)
2430 mainmod = PyImport_AddModule("__main__");
2431 if ((mainmod == NULL) || (PyErr_Occurred()))
2432 PLy_elog(ERROR, "could not import \"__main__\" module.");
2434 PLy_interp_globals = PyModule_GetDict(mainmod);
2435 PLy_interp_safe_globals = PyDict_New();
2436 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2438 if ((PLy_interp_globals == NULL) || (PyErr_Occurred()))
2439 PLy_elog(ERROR, "could not initialize globals");
2454 * initialize plpy module
2456 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2457 plpy = Py_InitModule("plpy", PLy_methods);
2458 plpy_dict = PyModule_GetDict(plpy);
2460 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2462 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2463 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2464 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2465 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2466 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2467 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2470 * initialize main module, and add plpy
2472 main_mod = PyImport_AddModule("__main__");
2473 main_dict = PyModule_GetDict(main_mod);
2474 plpy_mod = PyImport_AddModule("plpy");
2475 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2476 if (PyErr_Occurred())
2477 elog(ERROR, "could not init plpy");
2480 /* the python interface to the elog function
2481 * don't confuse these with PLy_elog
2483 static PyObject *PLy_output(int, PyObject *, PyObject *);
2486 PLy_debug(PyObject * self, PyObject * args)
2488 return PLy_output(DEBUG2, self, args);
2492 PLy_log(PyObject * self, PyObject * args)
2494 return PLy_output(LOG, self, args);
2498 PLy_info(PyObject * self, PyObject * args)
2500 return PLy_output(INFO, self, args);
2504 PLy_notice(PyObject * self, PyObject * args)
2506 return PLy_output(NOTICE, self, args);
2510 PLy_warning(PyObject * self, PyObject * args)
2512 return PLy_output(WARNING, self, args);
2516 PLy_error(PyObject * self, PyObject * args)
2518 return PLy_output(ERROR, self, args);
2522 PLy_fatal(PyObject * self, PyObject * args)
2524 return PLy_output(FATAL, self, args);
2529 PLy_output(volatile int level, PyObject * self, PyObject * args)
2538 elog(WARNING, "args is NULL");
2540 so = PyObject_Str(args);
2541 if ((so == NULL) || ((sv = PyString_AsString(so)) == NULL))
2544 sv = "Unable to parse error message in `plpy.elog'";
2548 * returning NULL here causes the python interpreter to bail. when
2549 * control passes back into plpython_*_handler, we check for python
2550 * exceptions and do the actual elog call. actually PLy_elog.
2554 PyErr_SetString(PLy_exc_error, sv);
2557 else if (level >= FATAL)
2559 PyErr_SetString(PLy_exc_fatal, sv);
2564 * ok, this is a WARNING, or LOG message
2566 * but just in case DON'T long jump out of the interpreter!
2576 * the real error message should already be written into the
2577 * postgresql log, no? whatever, this shouldn't happen so die
2580 elog(FATAL, "elog threw an unknown exception");
2584 elog(level, "%s", sv);
2592 * return a legal object so the interpreter will continue on its merry
2600 * Get the last procedure name called by the backend ( the innermost,
2601 * If a plpython procedure call calls the backend and the backend calls
2602 * another plpython procedure )
2604 * NB: this returns SQL name, not the internal Python procedure name
2608 PLy_procedure_name(PLyProcedure * proc)
2611 return "<unknown procedure>";
2612 return proc->proname;
2615 /* output a python traceback/exception via the postgresql elog
2616 * function. not pretty.
2619 static char *PLy_traceback(int *);
2620 static char *PLy_vprintf(const char *fmt, va_list ap);
2621 static char *PLy_printf(const char *fmt,...);
2624 PLy_exception_set(PyObject * exc, const char *fmt,...)
2630 vsnprintf(buf, sizeof(buf), fmt, ap);
2633 PyErr_SetString(exc, buf);
2637 PLy_elog(int elevel, const char *fmt,...)
2647 xmsg = PLy_traceback(&xlevel);
2650 emsg = PLy_vprintf(fmt, ap);
2660 * elog called siglongjmp. cleanup, restore and reraise
2662 PLy_restart_in_progress += 1;
2670 (errmsg("plpython: %s", emsg),
2671 (xmsg) ? errdetail("%s", xmsg) : 0));
2683 PLy_traceback(int *xlevel)
2697 * get the current exception
2699 PyErr_Fetch(&e, &v, &tb);
2702 * oops, no exception, return
2710 PyErr_NormalizeException(&e, &v, &tb);
2712 eob = PyObject_Str(e);
2713 if ((v) && ((vob = PyObject_Str(v)) != NULL))
2714 vstr = PyString_AsString(vob);
2718 estr = PyString_AsString(eob);
2719 xstr = PLy_printf("%s: %s", estr, vstr);
2725 * intuit an appropriate error level for based on the exception type
2727 if ((PLy_exc_error) && (PyErr_GivenExceptionMatches(e, PLy_exc_error)))
2729 else if ((PLy_exc_fatal) && (PyErr_GivenExceptionMatches(e, PLy_exc_fatal)))
2740 PLy_printf(const char *fmt,...)
2746 emsg = PLy_vprintf(fmt, ap);
2752 PLy_vprintf(const char *fmt, va_list ap)
2759 blen = strlen(fmt) * 2;
2762 buf = PLy_malloc(blen * sizeof(char));
2766 bchar = vsnprintf(buf, blen, fmt, ap);
2767 if ((bchar > 0) && (bchar < blen))
2775 buf = PLy_realloc(buf, blen);
2781 /* python module code
2785 /* some dumb utility functions
2789 PLy_malloc(size_t bytes)
2791 void *ptr = malloc(bytes);
2795 (errcode(ERRCODE_OUT_OF_MEMORY),
2796 errmsg("out of memory")));
2801 PLy_realloc(void *optr, size_t bytes)
2803 void *nptr = realloc(optr, bytes);
2807 (errcode(ERRCODE_OUT_OF_MEMORY),
2808 errmsg("out of memory")));