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.49 2004/06/06 00:41:28 tgl Exp $
34 *********************************************************************
44 /* postgreSQL stuff */
45 #include "access/heapam.h"
46 #include "catalog/pg_proc.h"
47 #include "catalog/pg_type.h"
48 #include "commands/trigger.h"
49 #include "executor/spi.h"
51 #include "nodes/makefuncs.h"
52 #include "parser/parse_type.h"
53 #include "tcop/tcopprot.h"
54 #include "utils/lsyscache.h"
55 #include "utils/syscache.h"
56 #include "utils/typcache.h"
63 /* convert Postgresql Datum or tuple into a PyObject.
64 * input to Python. Tuples are converted to dictionary
68 typedef PyObject *(*PLyDatumToObFunc) (const char *);
70 typedef struct PLyDatumToOb
72 PLyDatumToObFunc func;
78 typedef struct PLyTupleToOb
84 typedef union PLyTypeInput
90 /* convert PyObject to a Postgresql Datum or tuple.
93 typedef struct PLyObToDatum
100 typedef struct PLyObToTuple
106 typedef union PLyTypeOutput
112 /* all we need to move Postgresql data to Python objects,
115 typedef struct PLyTypeInfo
122 * -1 not known yet (initial state)
125 * 2 rowtype, but I/O functions not set up yet
130 /* cached procedure data
132 typedef struct PLyProcedure
134 char *proname; /* SQL name of procedure */
135 char *pyname; /* Python name of procedure */
136 TransactionId fn_xmin;
138 PLyTypeInfo result; /* also used to store info for trigger
140 PLyTypeInfo args[FUNC_MAX_ARGS];
142 PyObject *code; /* compiled procedure code */
143 PyObject *statics; /* data saved across calls, local scope */
144 PyObject *globals; /* data saved across calls, global score */
145 PyObject *me; /* PyCObject containing pointer to this
152 typedef struct PLyPlanObject
155 void *plan; /* return of an SPI_saveplan */
162 typedef struct PLyResultObject
165 /* HeapTuple *tuples; */
166 PyObject *nrows; /* number of rows returned by query */
167 PyObject *rows; /* data rows, or None if no data returned */
168 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
172 /* function declarations
175 /* Two exported functions: first is the magic telling Postgresql
176 * what function call interface it implements. Second allows
177 * preinitialization of the interpreter during postmaster startup.
179 Datum plpython_call_handler(PG_FUNCTION_ARGS);
180 void plpython_init(void);
182 PG_FUNCTION_INFO_V1(plpython_call_handler);
184 /* most of the remaining of the declarations, all static
187 /* these should only be called once at the first call
188 * of plpython_call_handler. initialize the python interpreter
191 static void PLy_init_all(void);
192 static void PLy_init_interp(void);
193 static void PLy_init_plpy(void);
195 /* error handler. collects the current Python exception, if any,
196 * and appends it to the error and sends it to elog
198 static void PLy_elog(int, const char *,...);
200 /* call PyErr_SetString with a vprint interface
203 PLy_exception_set(PyObject *, const char *,...)
204 __attribute__((format(printf, 2, 3)));
206 /* Get the innermost python procedure called from the backend.
208 static char *PLy_procedure_name(PLyProcedure *);
210 /* some utility functions
212 static void *PLy_malloc(size_t);
213 static void *PLy_realloc(void *, size_t);
214 static void PLy_free(void *);
216 /* sub handlers for functions and triggers
218 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
219 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
221 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
222 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
224 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
225 TriggerData *, HeapTuple);
227 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
229 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
232 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
234 HeapTuple procTup, char *key);
236 static void PLy_procedure_compile(PLyProcedure *, const char *);
237 static char *PLy_procedure_munge_source(const char *, const char *);
238 static void PLy_procedure_delete(PLyProcedure *);
240 static void PLy_typeinfo_init(PLyTypeInfo *);
241 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
242 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
243 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
244 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
245 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
246 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
247 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
249 /* conversion functions
251 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
252 static PyObject *PLyBool_FromString(const char *);
253 static PyObject *PLyFloat_FromString(const char *);
254 static PyObject *PLyInt_FromString(const char *);
255 static PyObject *PLyLong_FromString(const char *);
256 static PyObject *PLyString_FromString(const char *);
261 static int PLy_first_call = 1;
262 static volatile int PLy_call_level = 0;
265 * Last function called by postgres backend
267 static PLyProcedure *PLy_last_procedure = NULL;
269 /* this gets modified in plpython_call_handler and PLy_elog.
270 * test it any old where, but do NOT modify it anywhere except
271 * those two functions
273 static volatile int PLy_restart_in_progress = 0;
275 static PyObject *PLy_interp_globals = NULL;
276 static PyObject *PLy_interp_safe_globals = NULL;
277 static PyObject *PLy_procedure_cache = NULL;
281 static PyObject *PLy_exc_error = NULL;
282 static PyObject *PLy_exc_fatal = NULL;
283 static PyObject *PLy_exc_spi_error = NULL;
285 /* some globals for the python module
287 static char PLy_plan_doc[] = {
288 "Store a PostgreSQL plan"
291 static char PLy_result_doc[] = {
292 "Results of a PostgreSQL query"
297 volatile int exc_save_calls = 0;
298 volatile int exc_restore_calls = 0;
299 volatile int func_enter_calls = 0;
300 volatile int func_leave_calls = 0;
304 * the function definitions
308 * This routine is a crock, and so is everyplace that calls it. The problem
309 * is that the cached form of plpython functions/queries is allocated permanently
310 * (mostly via malloc()) and never released until backend exit. Subsidiary
311 * data structures such as fmgr info records therefore must live forever
312 * as well. A better implementation would store all this stuff in a per-
313 * function memory context that could be reclaimed at need. In the meantime,
314 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
315 * it might allocate, and whatever the eventual function might allocate using
316 * fn_mcxt, will live forever too.
319 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
321 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
325 plpython_call_handler(PG_FUNCTION_ARGS)
329 PLyProcedure *volatile proc = NULL;
335 if (SPI_connect() != SPI_OK_CONNECT)
336 elog(ERROR, "could not connect to SPI manager");
345 if (PLy_call_level == 0)
347 PLy_restart_in_progress = 0;
351 PLy_restart_in_progress += 1;
354 /* note: Py_DECREF needs braces around it, as of 2003/08 */
361 * elog(DEBUG3, "PLy_restart_in_progress is %d",
362 * PLy_restart_in_progress);
365 if (CALLED_AS_TRIGGER(fcinfo))
367 TriggerData *tdata = (TriggerData *) fcinfo->context;
370 proc = PLy_procedure_get(fcinfo,
371 RelationGetRelid(tdata->tg_relation));
372 trv = PLy_trigger_handler(fcinfo, proc);
373 retval = PointerGetDatum(trv);
377 proc = PLy_procedure_get(fcinfo, InvalidOid);
378 retval = PLy_function_handler(fcinfo, proc);
390 /* trigger and function sub handlers
392 * the python function is expected to return Py_None if the tuple is
393 * acceptable and unmodified. Otherwise it should return a PyString
394 * object who's value is SKIP, or MODIFY. SKIP means don't perform
395 * this action. MODIFY means the tuple has been modified, so update
396 * tuple and perform action. SKIP and MODIFY assume the trigger fires
397 * BEFORE the event and is ROW level. postgres expects the function
398 * to take no arguments and return an argument of type trigger.
401 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
405 PyObject *volatile plargs = NULL;
406 PyObject *volatile plrv = NULL;
421 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
422 plrv = PLy_procedure_call(proc, "TD", plargs);
425 * Disconnect from SPI manager
427 if (SPI_finish() != SPI_OK_FINISH)
428 elog(ERROR, "SPI_finish failed");
431 elog(FATAL, "PLy_procedure_call returned NULL");
433 if (PLy_restart_in_progress)
434 elog(FATAL, "restart in progress not expected");
437 * return of None means we're happy with the tuple
443 if (!PyString_Check(plrv))
444 elog(ERROR, "expected trigger to return None or a String");
446 srv = PyString_AsString(plrv);
447 if (pg_strcasecmp(srv, "SKIP") == 0)
449 else if (pg_strcasecmp(srv, "MODIFY") == 0)
451 TriggerData *tdata = (TriggerData *) fcinfo->context;
453 if ((TRIGGER_FIRED_BY_INSERT(tdata->tg_event)) ||
454 (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event)))
455 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
457 elog(WARNING, "ignoring modified tuple in DELETE trigger");
459 else if (pg_strcasecmp(srv, "OK") != 0)
462 * hmmm, perhaps they only read the pltcl page, not a
463 * surprising thing since i've written no documentation, so
464 * accept a belated OK
466 elog(ERROR, "expected return to be \"SKIP\" or \"MODIFY\"");
479 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
483 PyObject *volatile plntup;
484 PyObject *volatile plkeys;
485 PyObject *volatile platt;
486 PyObject *volatile plval;
487 PyObject *volatile plstr;
493 int *volatile modattrs;
494 Datum *volatile modvalues;
495 char *volatile modnulls;
498 plntup = plkeys = platt = plval = plstr = NULL;
526 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
527 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
528 if (!PyDict_Check(plntup))
529 elog(ERROR, "TD[\"new\"] is not a dictionary object");
532 plkeys = PyDict_Keys(plntup);
533 natts = PyList_Size(plkeys);
535 modattrs = (int *) palloc(natts * sizeof(int));
536 modvalues = (Datum *) palloc(natts * sizeof(Datum));
537 modnulls = (char *) palloc(natts * sizeof(char));
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].typioparam),
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.typioparam),
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.typioparam),
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, rvTypeTup);
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++)
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);
1342 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1343 desc->attrs[i]->atttypid,
1346 ReleaseSysCache(typeTup);
1351 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1357 if (arg->is_rowtype == 0)
1358 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1360 arg->is_rowtype = 1;
1361 arg->out.r.natts = desc->natts;
1362 arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1364 for (i = 0; i < desc->natts; i++)
1368 if (desc->attrs[i]->attisdropped)
1371 typeTup = SearchSysCache(TYPEOID,
1372 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1374 if (!HeapTupleIsValid(typeTup))
1375 elog(ERROR, "cache lookup failed for type %u",
1376 desc->attrs[i]->atttypid);
1378 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1380 ReleaseSysCache(typeTup);
1385 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1389 if (arg->is_rowtype > 0)
1390 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1391 arg->is_rowtype = 0;
1392 PLy_output_datum_func2(&(arg->out.d), typeTup);
1396 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1398 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1402 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1403 arg->typioparam = getTypeIOParam(typeTup);
1404 arg->typbyval = typeStruct->typbyval;
1408 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1412 if (arg->is_rowtype > 0)
1413 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1414 arg->is_rowtype = 0;
1415 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1419 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1421 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1423 /* Get the type's conversion information */
1424 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1425 arg->typioparam = getTypeIOParam(typeTup);
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].typioparam),
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], typeTup);
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));
2177 nulls = palloc(nargs * sizeof(char));
2179 for (i = 0; i < nargs; i++)
2185 elem = PySequence_GetItem(list, i);
2186 if (elem != Py_None)
2188 so = PyObject_Str(elem);
2189 sv = PyString_AsString(so);
2192 * FIXME -- if this can elog, we have leak
2195 FunctionCall3(&(plan->args[i].out.d.typfunc),
2196 CStringGetDatum(sv),
2197 ObjectIdGetDatum(plan->args[i].out.d.typioparam),
2208 plan->values[i] = (Datum) 0;
2213 rv = SPI_execp(plan->plan, plan->values, nulls, limit);
2219 for (i = 0; i < nargs; i++)
2221 if (!plan->args[i].out.d.typbyval &&
2222 (plan->values[i] != (Datum) NULL))
2224 pfree(DatumGetPointer(plan->values[i]));
2225 plan->values[i] = (Datum) NULL;
2231 PLy_exception_set(PLy_exc_spi_error,
2232 "Unable to execute plan. SPI_execp failed -- %s",
2233 PLy_spi_error_string(rv));
2237 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2241 PLy_spi_execute_query(char *query, int limit)
2250 if ((!PLy_restart_in_progress) && (!PyErr_Occurred()))
2251 PyErr_SetString(PLy_exc_spi_error,
2252 "Unknown error in PLy_spi_execute_query");
2253 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2257 rv = SPI_exec(query, limit);
2261 PLy_exception_set(PLy_exc_spi_error,
2262 "Unable to execute query. SPI_exec failed -- %s",
2263 PLy_spi_error_string(rv));
2267 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2271 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2273 PLyResultObject *result;
2277 result = (PLyResultObject *) PLy_result_new();
2278 Py_DECREF(result->status);
2279 result->status = PyInt_FromLong(status);
2281 if (status == SPI_OK_UTILITY)
2283 Py_DECREF(result->nrows);
2284 result->nrows = PyInt_FromLong(0);
2286 else if (status != SPI_OK_SELECT)
2288 Py_DECREF(result->nrows);
2289 result->nrows = PyInt_FromLong(rows);
2297 PLy_typeinfo_init(&args);
2298 Py_DECREF(result->nrows);
2299 result->nrows = PyInt_FromLong(rows);
2306 if (!PyErr_Occurred())
2307 PyErr_SetString(PLy_exc_error,
2308 "Unknown error in PLy_spi_execute_fetch_result");
2310 PLy_typeinfo_dealloc(&args);
2316 Py_DECREF(result->rows);
2317 result->rows = PyList_New(rows);
2319 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2320 for (i = 0; i < rows; i++)
2322 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2325 PyList_SetItem(result->rows, i, row);
2327 PLy_typeinfo_dealloc(&args);
2329 SPI_freetuptable(tuptable);
2334 return (PyObject *) result;
2338 PLy_spi_error_string(int code)
2342 case SPI_ERROR_TYPUNKNOWN:
2343 return "SPI_ERROR_TYPUNKNOWN";
2344 case SPI_ERROR_NOOUTFUNC:
2345 return "SPI_ERROR_NOOUTFUNC";
2346 case SPI_ERROR_NOATTRIBUTE:
2347 return "SPI_ERROR_NOATTRIBUTE";
2348 case SPI_ERROR_TRANSACTION:
2349 return "SPI_ERROR_TRANSACTION";
2350 case SPI_ERROR_PARAM:
2351 return "SPI_ERROR_PARAM";
2352 case SPI_ERROR_ARGUMENT:
2353 return "SPI_ERROR_ARGUMENT";
2354 case SPI_ERROR_CURSOR:
2355 return "SPI_ERROR_CURSOR";
2356 case SPI_ERROR_UNCONNECTED:
2357 return "SPI_ERROR_UNCONNECTED";
2358 case SPI_ERROR_OPUNKNOWN:
2359 return "SPI_ERROR_OPUNKNOWN";
2360 case SPI_ERROR_COPY:
2361 return "SPI_ERROR_COPY";
2362 case SPI_ERROR_CONNECT:
2363 return "SPI_ERROR_CONNECT";
2365 return "Unknown or Invalid code";
2368 /* language handler and interpreter initialization
2372 * plpython_init() - Initialize everything that can be
2373 * safely initialized during postmaster
2376 * DO NOT make this static --- it has to be callable by preload
2381 static volatile int init_active = 0;
2383 /* Do initialization only once */
2384 if (!PLy_first_call)
2390 elog(FATAL, "initialization of language module failed");
2396 if (PyErr_Occurred())
2397 PLy_elog(FATAL, "untrapped error in initialization");
2398 PLy_procedure_cache = PyDict_New();
2399 if (PLy_procedure_cache == NULL)
2400 PLy_elog(ERROR, "could not create procedure cache");
2410 /* Execute postmaster-startup safe initialization */
2415 * Any other initialization that must be done each time a new backend
2416 * starts -- currently none
2422 PLy_init_interp(void)
2428 mainmod = PyImport_AddModule("__main__");
2429 if ((mainmod == NULL) || (PyErr_Occurred()))
2430 PLy_elog(ERROR, "could not import \"__main__\" module.");
2432 PLy_interp_globals = PyModule_GetDict(mainmod);
2433 PLy_interp_safe_globals = PyDict_New();
2434 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2436 if ((PLy_interp_globals == NULL) || (PyErr_Occurred()))
2437 PLy_elog(ERROR, "could not initialize globals");
2452 * initialize plpy module
2454 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2455 plpy = Py_InitModule("plpy", PLy_methods);
2456 plpy_dict = PyModule_GetDict(plpy);
2458 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2460 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2461 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2462 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2463 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2464 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2465 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2468 * initialize main module, and add plpy
2470 main_mod = PyImport_AddModule("__main__");
2471 main_dict = PyModule_GetDict(main_mod);
2472 plpy_mod = PyImport_AddModule("plpy");
2473 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2474 if (PyErr_Occurred())
2475 elog(ERROR, "could not init plpy");
2478 /* the python interface to the elog function
2479 * don't confuse these with PLy_elog
2481 static PyObject *PLy_output(int, PyObject *, PyObject *);
2484 PLy_debug(PyObject * self, PyObject * args)
2486 return PLy_output(DEBUG2, self, args);
2490 PLy_log(PyObject * self, PyObject * args)
2492 return PLy_output(LOG, self, args);
2496 PLy_info(PyObject * self, PyObject * args)
2498 return PLy_output(INFO, self, args);
2502 PLy_notice(PyObject * self, PyObject * args)
2504 return PLy_output(NOTICE, self, args);
2508 PLy_warning(PyObject * self, PyObject * args)
2510 return PLy_output(WARNING, self, args);
2514 PLy_error(PyObject * self, PyObject * args)
2516 return PLy_output(ERROR, self, args);
2520 PLy_fatal(PyObject * self, PyObject * args)
2522 return PLy_output(FATAL, self, args);
2527 PLy_output(volatile int level, PyObject * self, PyObject * args)
2536 elog(WARNING, "args is NULL");
2538 so = PyObject_Str(args);
2539 if ((so == NULL) || ((sv = PyString_AsString(so)) == NULL))
2542 sv = "Unable to parse error message in `plpy.elog'";
2546 * returning NULL here causes the python interpreter to bail. when
2547 * control passes back into plpython_*_handler, we check for python
2548 * exceptions and do the actual elog call. actually PLy_elog.
2552 PyErr_SetString(PLy_exc_error, sv);
2555 else if (level >= FATAL)
2557 PyErr_SetString(PLy_exc_fatal, sv);
2562 * ok, this is a WARNING, or LOG message
2564 * but just in case DON'T long jump out of the interpreter!
2574 * the real error message should already be written into the
2575 * postgresql log, no? whatever, this shouldn't happen so die
2578 elog(FATAL, "elog threw an unknown exception");
2582 elog(level, "%s", sv);
2590 * return a legal object so the interpreter will continue on its merry
2598 * Get the last procedure name called by the backend ( the innermost,
2599 * If a plpython procedure call calls the backend and the backend calls
2600 * another plpython procedure )
2602 * NB: this returns SQL name, not the internal Python procedure name
2606 PLy_procedure_name(PLyProcedure * proc)
2609 return "<unknown procedure>";
2610 return proc->proname;
2613 /* output a python traceback/exception via the postgresql elog
2614 * function. not pretty.
2617 static char *PLy_traceback(int *);
2618 static char *PLy_vprintf(const char *fmt, va_list ap);
2619 static char *PLy_printf(const char *fmt,...);
2622 PLy_exception_set(PyObject * exc, const char *fmt,...)
2628 vsnprintf(buf, sizeof(buf), fmt, ap);
2631 PyErr_SetString(exc, buf);
2635 PLy_elog(int elevel, const char *fmt,...)
2645 xmsg = PLy_traceback(&xlevel);
2648 emsg = PLy_vprintf(fmt, ap);
2658 * elog called siglongjmp. cleanup, restore and reraise
2660 PLy_restart_in_progress += 1;
2668 (errmsg("plpython: %s", emsg),
2669 (xmsg) ? errdetail("%s", xmsg) : 0));
2681 PLy_traceback(int *xlevel)
2695 * get the current exception
2697 PyErr_Fetch(&e, &v, &tb);
2700 * oops, no exception, return
2708 PyErr_NormalizeException(&e, &v, &tb);
2710 eob = PyObject_Str(e);
2711 if ((v) && ((vob = PyObject_Str(v)) != NULL))
2712 vstr = PyString_AsString(vob);
2716 estr = PyString_AsString(eob);
2717 xstr = PLy_printf("%s: %s", estr, vstr);
2723 * intuit an appropriate error level for based on the exception type
2725 if ((PLy_exc_error) && (PyErr_GivenExceptionMatches(e, PLy_exc_error)))
2727 else if ((PLy_exc_fatal) && (PyErr_GivenExceptionMatches(e, PLy_exc_fatal)))
2738 PLy_printf(const char *fmt,...)
2744 emsg = PLy_vprintf(fmt, ap);
2750 PLy_vprintf(const char *fmt, va_list ap)
2757 blen = strlen(fmt) * 2;
2760 buf = PLy_malloc(blen * sizeof(char));
2764 bchar = vsnprintf(buf, blen, fmt, ap);
2765 if ((bchar > 0) && (bchar < blen))
2773 buf = PLy_realloc(buf, blen);
2779 /* python module code
2783 /* some dumb utility functions
2787 PLy_malloc(size_t bytes)
2789 void *ptr = malloc(bytes);
2793 (errcode(ERRCODE_OUT_OF_MEMORY),
2794 errmsg("out of memory")));
2799 PLy_realloc(void *optr, size_t bytes)
2801 void *nptr = realloc(optr, bytes);
2805 (errcode(ERRCODE_OUT_OF_MEMORY),
2806 errmsg("out of memory")));