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 * $Header: /cvsroot/pgsql/src/pl/plpython/plpython.c,v 1.38 2003/08/04 01:57:58 tgl Exp $
34 *********************************************************************
52 #include "access/heapam.h"
53 #include "catalog/pg_proc.h"
54 #include "catalog/pg_type.h"
55 #include "commands/trigger.h"
56 #include "executor/spi.h"
58 #include "nodes/makefuncs.h"
59 #include "parser/parse_type.h"
60 #include "tcop/tcopprot.h"
61 #include "utils/syscache.h"
68 /* convert Postgresql Datum or tuple into a PyObject.
69 * input to Python. Tuples are converted to dictionary
73 typedef PyObject *(*PLyDatumToObFunc) (const char *);
75 typedef struct PLyDatumToOb
77 PLyDatumToObFunc func;
83 typedef struct PLyTupleToOb
89 typedef union PLyTypeInput
95 /* convert PyObject to a Postgresql Datum or tuple.
98 typedef struct PLyObToDatum
105 typedef struct PLyObToTuple
111 typedef union PLyTypeOutput
117 /* all we need to move Postgresql data to Python objects,
120 typedef struct PLyTypeInfo
128 /* cached procedure data
130 typedef struct PLyProcedure
132 char *proname; /* SQL name of procedure */
133 char *pyname; /* Python name of procedure */
134 TransactionId fn_xmin;
136 PLyTypeInfo result; /* also used to store info for trigger
138 PLyTypeInfo args[FUNC_MAX_ARGS];
140 PyObject *code; /* compiled procedure code */
141 PyObject *statics; /* data saved across calls, local scope */
142 PyObject *globals; /* data saved across calls, global score */
143 PyObject *me; /* PyCObject containing pointer to this
150 typedef struct PLyPlanObject
153 void *plan; /* return of an SPI_saveplan */
160 typedef struct PLyResultObject
163 /* HeapTuple *tuples; */
164 PyObject *nrows; /* number of rows returned by query */
165 PyObject *rows; /* data rows, or None if no data returned */
166 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
170 /* function declarations
173 /* Two exported functions: first is the magic telling Postgresql
174 * what function call interface it implements. Second allows
175 * preinitialization of the interpreter during postmaster startup.
177 Datum plpython_call_handler(PG_FUNCTION_ARGS);
178 void plpython_init(void);
180 PG_FUNCTION_INFO_V1(plpython_call_handler);
182 /* most of the remaining of the declarations, all static
185 /* these should only be called once at the first call
186 * of plpython_call_handler. initialize the python interpreter
189 static void PLy_init_all(void);
190 static void PLy_init_interp(void);
191 static void PLy_init_plpy(void);
193 /* error handler. collects the current Python exception, if any,
194 * and appends it to the error and sends it to elog
196 static void PLy_elog(int, const char *,...);
198 /* call PyErr_SetString with a vprint interface
201 PLy_exception_set(PyObject *, const char *,...)
202 __attribute__((format(printf, 2, 3)));
204 /* Get the innermost python procedure called from the backend.
206 static char *PLy_procedure_name(PLyProcedure *);
208 /* some utility functions
210 static void *PLy_malloc(size_t);
211 static void *PLy_realloc(void *, size_t);
212 static void PLy_free(void *);
214 /* sub handlers for functions and triggers
216 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
217 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
219 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
220 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
222 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
223 TriggerData *, HeapTuple);
225 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
227 /* returns a cached PLyProcedure, or creates, stores and returns
228 * a new PLyProcedure.
230 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo, bool);
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 *, Form_pg_type);
243 static void PLy_output_datum_func2(PLyObToDatum *, Form_pg_type);
244 static void PLy_input_datum_func(PLyTypeInfo *, Oid, Form_pg_type);
245 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, Form_pg_type);
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 volatile bool is_trigger;
330 PLyProcedure *volatile proc = NULL;
336 if (SPI_connect() != SPI_OK_CONNECT)
337 elog(ERROR, "could not connect to SPI manager");
340 is_trigger = CALLED_AS_TRIGGER(fcinfo);
347 if (PLy_call_level == 0)
349 PLy_restart_in_progress = 0;
353 PLy_restart_in_progress += 1;
356 /* note: Py_DECREF needs braces around it, as of 2003/08 */
363 * elog(DEBUG3, "PLy_restart_in_progress is %d",
364 * PLy_restart_in_progress);
367 proc = PLy_procedure_get(fcinfo, is_trigger);
371 HeapTuple trv = PLy_trigger_handler(fcinfo, proc);
373 retval = PointerGetDatum(trv);
376 retval = PLy_function_handler(fcinfo, proc);
387 /* trigger and function sub handlers
389 * the python function is expected to return Py_None if the tuple is
390 * acceptable and unmodified. Otherwise it should return a PyString
391 * object who's value is SKIP, or MODIFY. SKIP means don't perform
392 * this action. MODIFY means the tuple has been modified, so update
393 * tuple and perform action. SKIP and MODIFY assume the trigger fires
394 * BEFORE the event and is ROW level. postgres expects the function
395 * to take no arguments and return an argument of type trigger.
398 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
402 PyObject *volatile plargs = NULL;
403 PyObject *volatile plrv = NULL;
418 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
419 plrv = PLy_procedure_call(proc, "TD", plargs);
422 * Disconnect from SPI manager
424 if (SPI_finish() != SPI_OK_FINISH)
425 elog(ERROR, "SPI_finish failed");
428 elog(FATAL, "PLy_procedure_call returned NULL");
430 if (PLy_restart_in_progress)
431 elog(FATAL, "restart in progress not expected");
434 * return of None means we're happy with the tuple
440 if (!PyString_Check(plrv))
441 elog(ERROR, "expected trigger to return None or a String");
443 srv = PyString_AsString(plrv);
444 if (strcasecmp(srv, "SKIP") == 0)
446 else if (strcasecmp(srv, "MODIFY") == 0)
448 TriggerData *tdata = (TriggerData *) fcinfo->context;
450 if ((TRIGGER_FIRED_BY_INSERT(tdata->tg_event)) ||
451 (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event)))
452 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
454 elog(WARNING, "ignoring modified tuple in DELETE trigger");
456 else if (strcasecmp(srv, "OK"))
459 * hmmm, perhaps they only read the pltcl page, not a
460 * surprising thing since i've written no documentation, so
461 * accept a belated OK
463 elog(ERROR, "expected return to be \"SKIP\" or \"MODIFY\"");
476 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
480 PyObject *volatile plntup;
481 PyObject *volatile plkeys;
482 PyObject *volatile platt;
483 PyObject *volatile plval;
484 PyObject *volatile plstr;
491 int *volatile modattrs;
492 Datum *volatile modvalues;
493 char *volatile modnulls;
496 plntup = plkeys = platt = plval = plstr = NULL;
524 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
525 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
526 if (!PyDict_Check(plntup))
527 elog(ERROR, "TD[\"new\"] is not a dictionary object");
530 plkeys = PyDict_Keys(plntup);
531 natts = PyList_Size(plkeys);
533 if (natts != proc->result.out.r.natts)
534 elog(ERROR, "TD[\"new\"] has an incorrect number of keys");
536 modattrs = palloc(natts * sizeof(int));
537 modvalues = palloc(natts * sizeof(Datum));
538 for (i = 0; i < natts; i++)
541 modvalues[i] = (Datum) NULL;
543 modnulls = palloc(natts + 1);
544 memset(modnulls, 'n', natts);
545 modnulls[natts] = '\0';
547 tupdesc = tdata->tg_relation->rd_att;
549 for (j = 0; j < natts; j++)
553 platt = PyList_GetItem(plkeys, j);
554 if (!PyString_Check(platt))
555 elog(ERROR, "attribute is not a string");
556 attn = modattrs[j] = SPI_fnumber(tupdesc, PyString_AsString(platt));
558 if (attn == SPI_ERROR_NOATTRIBUTE)
559 elog(ERROR, "invalid attribute \"%s\" in tuple",
560 PyString_AsString(platt));
563 plval = PyDict_GetItem(plntup, platt);
565 elog(FATAL, "python interpreter is probably corrupted");
569 if (plval != Py_None)
571 plstr = PyObject_Str(plval);
572 src = PyString_AsString(plstr);
574 modvalues[j] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
575 CStringGetDatum(src),
576 ObjectIdGetDatum(proc->result.out.r.atts[atti].typelem),
577 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
587 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts, modattrs,
588 modvalues, modnulls);
591 * FIXME -- these leak if not explicitly pfree'd by other elog calls,
599 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
610 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
622 PyObject *volatile pltdata = NULL;
637 tdata = (TriggerData *) fcinfo->context;
639 pltdata = PyDict_New();
641 PLy_elog(ERROR, "could not build arguments for trigger procedure");
643 pltname = PyString_FromString(tdata->tg_trigger->tgname);
644 PyDict_SetItemString(pltdata, "name", pltname);
647 stroid = DatumGetCString(DirectFunctionCall1(oidout,
648 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
649 pltrelid = PyString_FromString(stroid);
650 PyDict_SetItemString(pltdata, "relid", pltrelid);
656 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
657 pltwhen = PyString_FromString("BEFORE");
658 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
659 pltwhen = PyString_FromString("AFTER");
661 pltwhen = PyString_FromString("UNKNOWN");
662 PyDict_SetItemString(pltdata, "when", pltwhen);
665 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
666 pltlevel = PyString_FromString("ROW");
667 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
668 pltlevel = PyString_FromString("STATEMENT");
670 pltlevel = PyString_FromString("UNKNOWN");
671 PyDict_SetItemString(pltdata, "level", pltlevel);
674 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
676 pltevent = PyString_FromString("INSERT");
677 PyDict_SetItemString(pltdata, "old", Py_None);
678 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
679 tdata->tg_relation->rd_att);
680 PyDict_SetItemString(pltdata, "new", pytnew);
682 *rv = tdata->tg_trigtuple;
684 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
686 pltevent = PyString_FromString("DELETE");
687 PyDict_SetItemString(pltdata, "new", Py_None);
688 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
689 tdata->tg_relation->rd_att);
690 PyDict_SetItemString(pltdata, "old", pytold);
692 *rv = tdata->tg_trigtuple;
694 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
696 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 pltevent = PyString_FromString("UNKNOWN");
710 PyDict_SetItemString(pltdata, "old", Py_None);
711 PyDict_SetItemString(pltdata, "new", Py_None);
712 *rv = tdata->tg_trigtuple;
714 PyDict_SetItemString(pltdata, "event", pltevent);
717 if (tdata->tg_trigger->tgnargs)
725 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
726 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
728 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
731 * stolen, don't Py_DECREF
733 PyList_SetItem(pltargs, i, pltarg);
741 PyDict_SetItemString(pltdata, "args", pltargs);
751 /* function handler and friends
754 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
758 PyObject *volatile plargs = NULL;
759 PyObject *volatile plrv = NULL;
760 PyObject *volatile plrv_so = NULL;
766 * setup to catch elog in while building function arguments, and
767 * DECREF the plargs if the function call fails
781 plargs = PLy_function_build_args(fcinfo, proc);
782 plrv = PLy_procedure_call(proc, "args", plargs);
785 * Disconnect from SPI manager and then create the return values datum
786 * (if the input function does a palloc for it this must not be
787 * allocated in the SPI memory context because SPI_finish would free
790 if (SPI_finish() != SPI_OK_FINISH)
791 elog(ERROR, "SPI_finish failed");
795 elog(FATAL, "PLy_procedure_call returned NULL");
797 if (!PLy_restart_in_progress)
798 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
801 * FIXME is this dead code? i'm pretty sure it is for unnested
802 * calls, but not for nested calls
809 * convert the python PyObject to a postgresql Datum FIXME returning a
810 * NULL, ie PG_RETURN_NULL() blows the backend to small messy bits...
811 * it this a bug or expected? so just call with the string value of
817 fcinfo->isnull = true;
822 fcinfo->isnull = false;
823 plrv_so = PyObject_Str(plrv);
824 plrv_sc = PyString_AsString(plrv_so);
825 rv = FunctionCall3(&proc->result.out.d.typfunc,
826 PointerGetDatum(plrv_sc),
827 ObjectIdGetDatum(proc->result.out.d.typelem),
841 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
844 PLyProcedure *current;
848 current = PLy_last_procedure;
849 PLy_last_procedure = proc;
850 PyDict_SetItemString(proc->globals, kargs, vargs);
851 rv = PyEval_EvalCode((PyCodeObject *) proc->code, proc->globals, proc->globals);
852 PLy_last_procedure = current;
854 if ((rv == NULL) || (PyErr_Occurred()))
857 if (!PLy_restart_in_progress)
858 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
866 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
869 PyObject *volatile arg = NULL;
870 PyObject *volatile args = NULL;
876 * FIXME -- if the setjmp setup is expensive, add the arg and args
877 * field to the procedure struct and cleanup at the start of the next
890 args = PyList_New(proc->nargs);
891 for (i = 0; i < proc->nargs; i++)
893 if (proc->args[i].is_rel == 1)
895 TupleTableSlot *slot = (TupleTableSlot *) fcinfo->arg[i];
897 arg = PLyDict_FromTuple(&(proc->args[i]), slot->val,
898 slot->ttc_tupleDescriptor);
902 if (!fcinfo->argnull[i])
907 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
909 ObjectIdGetDatum(proc->args[i].in.d.typelem),
911 ct = DatumGetCString(dt);
912 arg = (proc->args[i].in.d.func) (ct);
926 * FIXME -- error check this
928 PyList_SetItem(args, i, arg);
937 /* PLyProcedure functions
939 static PLyProcedure *
940 PLy_procedure_get(FunctionCallInfo fcinfo, bool is_trigger)
946 PLyProcedure *proc = NULL;
951 fn_oid = fcinfo->flinfo->fn_oid;
952 procTup = SearchSysCache(PROCOID,
953 ObjectIdGetDatum(fn_oid),
955 if (!HeapTupleIsValid(procTup))
956 elog(ERROR, "cache lookup failed for function %u", fn_oid);
958 rv = snprintf(key, sizeof(key), "%u%s",
960 is_trigger ? "_trigger" : "");
961 if ((rv >= sizeof(key)) || (rv < 0))
962 elog(ERROR, "key too long");
964 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
969 if (!PyCObject_Check(plproc))
970 elog(FATAL, "expected a PyCObject, didn't get one");
974 proc = PyCObject_AsVoidPtr(plproc);
975 if (proc->me != plproc)
976 elog(FATAL, "proc->me != plproc");
977 /* did we find an up-to-date cache entry? */
978 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
979 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
987 proc = PLy_procedure_create(fcinfo, is_trigger, procTup, key);
989 ReleaseSysCache(procTup);
994 static PLyProcedure *
995 PLy_procedure_create(FunctionCallInfo fcinfo, bool is_trigger,
996 HeapTuple procTup, char *key)
998 char procName[NAMEDATALEN + 256];
1001 Form_pg_proc procStruct;
1002 PLyProcedure *volatile proc;
1003 char *volatile procSource = NULL;
1010 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1012 rv = snprintf(procName, sizeof(procName),
1013 "__plpython_procedure_%s_%u%s",
1014 NameStr(procStruct->proname),
1015 fcinfo->flinfo->fn_oid,
1016 is_trigger ? "_trigger" : "");
1017 if ((rv >= sizeof(procName)) || (rv < 0))
1018 elog(ERROR, "procedure name would overrun buffer");
1020 proc = PLy_malloc(sizeof(PLyProcedure));
1021 proc->proname = PLy_malloc(strlen(NameStr(procStruct->proname)) + 1);
1022 strcpy(proc->proname, NameStr(procStruct->proname));
1023 proc->pyname = PLy_malloc(strlen(procName) + 1);
1024 strcpy(proc->pyname, procName);
1025 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1026 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1027 PLy_typeinfo_init(&proc->result);
1028 for (i = 0; i < FUNC_MAX_ARGS; i++)
1029 PLy_typeinfo_init(&proc->args[i]);
1031 proc->code = proc->statics = NULL;
1032 proc->globals = proc->me = NULL;
1038 PLy_procedure_delete(proc);
1045 * get information required for output conversion of the return value,
1046 * but only if this isn't a trigger.
1050 HeapTuple rvTypeTup;
1051 Form_pg_type rvTypeStruct;
1053 rvTypeTup = SearchSysCache(TYPEOID,
1054 ObjectIdGetDatum(procStruct->prorettype),
1056 if (!HeapTupleIsValid(rvTypeTup))
1057 elog(ERROR, "cache lookup failed for type %u",
1058 procStruct->prorettype);
1060 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1061 if (rvTypeStruct->typrelid == InvalidOid)
1062 PLy_output_datum_func(&proc->result, rvTypeStruct);
1065 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1066 errmsg("tuple return types are not supported yet")));
1068 ReleaseSysCache(rvTypeTup);
1073 * input/output conversion for trigger tuples. use the result
1074 * TypeInfo variable to store the tuple conversion info.
1076 TriggerData *tdata = (TriggerData *) fcinfo->context;
1078 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1079 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1083 * now get information required for input conversion of the procedures
1086 proc->nargs = fcinfo->nargs;
1087 for (i = 0; i < fcinfo->nargs; i++)
1089 HeapTuple argTypeTup;
1090 Form_pg_type argTypeStruct;
1092 argTypeTup = SearchSysCache(TYPEOID,
1093 ObjectIdGetDatum(procStruct->proargtypes[i]),
1095 if (!HeapTupleIsValid(argTypeTup))
1096 elog(ERROR, "cache lookup failed for type %u",
1097 procStruct->proargtypes[i]);
1098 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1100 if (argTypeStruct->typrelid == InvalidOid)
1101 PLy_input_datum_func(&(proc->args[i]),
1102 procStruct->proargtypes[i],
1106 TupleTableSlot *slot = (TupleTableSlot *) fcinfo->arg[i];
1108 PLy_input_tuple_funcs(&(proc->args[i]),
1109 slot->ttc_tupleDescriptor);
1112 ReleaseSysCache(argTypeTup);
1117 * get the text of the function.
1119 procDatum = DirectFunctionCall1(textout,
1120 PointerGetDatum(&procStruct->prosrc));
1121 procSource = DatumGetCString(procDatum);
1123 PLy_procedure_compile(proc, procSource);
1127 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1128 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1136 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1138 PyObject *crv = NULL;
1143 proc->globals = PyDict_Copy(PLy_interp_globals);
1146 * SD is private preserved data between calls GD is global data shared
1149 proc->statics = PyDict_New();
1150 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1153 * insert the function code into the interpreter
1155 msrc = PLy_procedure_munge_source(proc->pyname, src);
1156 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1159 if ((crv != NULL) && (!PyErr_Occurred()))
1162 char call[NAMEDATALEN + 256];
1167 * compile a call to the function
1169 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1170 if ((clen < 0) || (clen >= sizeof(call)))
1171 elog(ERROR, "string would overflow buffer");
1172 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1173 if ((proc->code != NULL) && (!PyErr_Occurred()))
1179 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1183 PLy_procedure_munge_source(const char *name, const char *src)
1194 * room for function source and the def statement
1196 mlen = (strlen(src) * 2) + strlen(name) + 16;
1198 mrc = PLy_malloc(mlen);
1199 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1200 Assert(plen >= 0 && plen < mlen);
1219 if (mp > (mrc + mlen))
1220 elog(FATAL, "buffer overrun in PLy_munge_source");
1226 PLy_procedure_delete(PLyProcedure * proc)
1232 Py_XDECREF(proc->code);
1233 Py_XDECREF(proc->statics);
1234 Py_XDECREF(proc->globals);
1235 Py_XDECREF(proc->me);
1237 PLy_free(proc->proname);
1239 PLy_free(proc->pyname);
1240 for (i = 0; i < proc->nargs; i++)
1241 if (proc->args[i].is_rel == 1)
1243 if (proc->args[i].in.r.atts)
1244 PLy_free(proc->args[i].in.r.atts);
1245 if (proc->args[i].out.r.atts)
1246 PLy_free(proc->args[i].out.r.atts);
1252 /* conversion functions. remember output from python is
1253 * input to postgresql, and vis versa.
1256 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1262 if (arg->is_rel == 0)
1263 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1266 arg->in.r.natts = desc->natts;
1267 arg->in.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1269 for (i = 0; i < desc->natts; i++)
1272 Form_pg_type typeStruct;
1274 typeTup = SearchSysCache(TYPEOID,
1275 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1277 if (!HeapTupleIsValid(typeTup))
1278 elog(ERROR, "cache lookup failed for type %u",
1279 desc->attrs[i]->atttypid);
1280 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1282 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1283 desc->attrs[i]->atttypid,
1286 ReleaseSysCache(typeTup);
1291 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1297 if (arg->is_rel == 0)
1298 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1301 arg->out.r.natts = desc->natts;
1302 arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1304 for (i = 0; i < desc->natts; i++)
1307 Form_pg_type typeStruct;
1309 typeTup = SearchSysCache(TYPEOID,
1310 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1312 if (!HeapTupleIsValid(typeTup))
1313 elog(ERROR, "cache lookup failed for type %u",
1314 desc->attrs[i]->atttypid);
1315 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1317 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeStruct);
1319 ReleaseSysCache(typeTup);
1324 PLy_output_datum_func(PLyTypeInfo * arg, Form_pg_type typeStruct)
1328 if (arg->is_rel == 1)
1329 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1331 PLy_output_datum_func2(&(arg->out.d), typeStruct);
1335 PLy_output_datum_func2(PLyObToDatum * arg, Form_pg_type typeStruct)
1339 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1340 arg->typelem = typeStruct->typelem;
1341 arg->typbyval = typeStruct->typbyval;
1345 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, Form_pg_type typeStruct)
1349 if (arg->is_rel == 1)
1350 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1352 PLy_input_datum_func2(&(arg->in.d), typeOid, typeStruct);
1356 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, Form_pg_type typeStruct)
1358 /* Get the type's conversion information */
1359 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1360 arg->typelem = typeStruct->typelem;
1361 arg->typbyval = typeStruct->typbyval;
1363 /* Determine which kind of Python object we will convert to */
1367 arg->func = PLyBool_FromString;
1372 arg->func = PLyFloat_FromString;
1376 arg->func = PLyInt_FromString;
1379 arg->func = PLyLong_FromString;
1382 arg->func = PLyString_FromString;
1388 PLy_typeinfo_init(PLyTypeInfo * arg)
1391 arg->in.r.natts = arg->out.r.natts = 0;
1392 arg->in.r.atts = NULL;
1393 arg->out.r.atts = NULL;
1397 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1399 if (arg->is_rel == 1)
1402 PLy_free(arg->in.r.atts);
1403 if (arg->out.r.atts)
1404 PLy_free(arg->out.r.atts);
1408 /* assumes that a bool is always returned as a 't' or 'f'
1411 PLyBool_FromString(const char *src)
1416 return PyInt_FromLong(1);
1417 return PyInt_FromLong(0);
1421 PLyFloat_FromString(const char *src)
1429 v = strtod(src, &eptr);
1430 if ((*eptr != '\0') || (errno))
1432 return PyFloat_FromDouble(v);
1436 PLyInt_FromString(const char *src)
1444 v = strtol(src, &eptr, 0);
1445 if ((*eptr != '\0') || (errno))
1447 return PyInt_FromLong(v);
1451 PLyLong_FromString(const char *src)
1453 return PyLong_FromString((char *) src, NULL, 0);
1457 PLyString_FromString(const char *src)
1459 return PyString_FromString(src);
1463 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1466 PyObject *volatile dict;
1471 if (info->is_rel != 1)
1472 elog(ERROR, "PLyTypeInfo structure describes a datum");
1474 dict = PyDict_New();
1476 PLy_elog(ERROR, "could not create tuple dictionary");
1487 for (i = 0; i < info->in.r.natts; i++)
1496 key = NameStr(desc->attrs[i]->attname);
1497 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1499 if ((is_null) || (info->in.r.atts[i].func == NULL))
1500 PyDict_SetItemString(dict, key, Py_None);
1503 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1505 ObjectIdGetDatum(info->in.r.atts[i].typelem),
1506 Int32GetDatum(desc->attrs[i]->atttypmod));
1507 vsrc = DatumGetCString(vdat);
1510 * no exceptions allowed
1512 value = info->in.r.atts[i].func(vsrc);
1514 PyDict_SetItemString(dict, key, value);
1524 /* initialization, some python variables function declared here
1527 /* interface to postgresql elog
1529 static PyObject *PLy_debug(PyObject *, PyObject *);
1530 static PyObject *PLy_log(PyObject *, PyObject *);
1531 static PyObject *PLy_info(PyObject *, PyObject *);
1532 static PyObject *PLy_notice(PyObject *, PyObject *);
1533 static PyObject *PLy_warning(PyObject *, PyObject *);
1534 static PyObject *PLy_error(PyObject *, PyObject *);
1535 static PyObject *PLy_fatal(PyObject *, PyObject *);
1537 /* PLyPlanObject, PLyResultObject and SPI interface
1539 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1540 static PyObject *PLy_plan_new(void);
1541 static void PLy_plan_dealloc(PyObject *);
1542 static PyObject *PLy_plan_getattr(PyObject *, char *);
1543 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1545 static PyObject *PLy_result_new(void);
1546 static void PLy_result_dealloc(PyObject *);
1547 static PyObject *PLy_result_getattr(PyObject *, char *);
1550 /* Appear to be unused */
1551 static PyObject *PLy_result_fetch(PyObject *, PyObject *);
1552 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1553 static PyObject *PLy_result_status(PyObject *, PyObject *);
1555 static int PLy_result_length(PyObject *);
1556 static PyObject *PLy_result_item(PyObject *, int);
1557 static PyObject *PLy_result_slice(PyObject *, int, int);
1558 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1559 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1562 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1563 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1564 static const char *PLy_spi_error_string(int);
1565 static PyObject *PLy_spi_execute_query(char *query, int limit);
1566 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, int);
1567 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1570 static PyTypeObject PLy_PlanType = {
1571 PyObject_HEAD_INIT(NULL)
1573 "PLyPlan", /* tp_name */
1574 sizeof(PLyPlanObject), /* tp_size */
1575 0, /* tp_itemsize */
1580 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1582 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1586 0, /* tp_as_number */
1587 0, /* tp_as_sequence */
1588 0, /* tp_as_mapping */
1592 0, /* tp_getattro */
1593 0, /* tp_setattro */
1594 0, /* tp_as_buffer */
1596 PLy_plan_doc, /* tp_doc */
1599 static PyMethodDef PLy_plan_methods[] = {
1600 {"status", (PyCFunction) PLy_plan_status, METH_VARARGS, NULL},
1601 {NULL, NULL, 0, NULL}
1605 static PySequenceMethods PLy_result_as_sequence = {
1606 (inquiry) PLy_result_length, /* sq_length */
1607 (binaryfunc) 0, /* sq_concat */
1608 (intargfunc) 0, /* sq_repeat */
1609 (intargfunc) PLy_result_item, /* sq_item */
1610 (intintargfunc) PLy_result_slice, /* sq_slice */
1611 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1612 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1615 static PyTypeObject PLy_ResultType = {
1616 PyObject_HEAD_INIT(NULL)
1618 "PLyResult", /* tp_name */
1619 sizeof(PLyResultObject), /* tp_size */
1620 0, /* tp_itemsize */
1625 (destructor) PLy_result_dealloc, /* tp_dealloc */
1627 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1631 0, /* tp_as_number */
1632 &PLy_result_as_sequence, /* tp_as_sequence */
1633 0, /* tp_as_mapping */
1637 0, /* tp_getattro */
1638 0, /* tp_setattro */
1639 0, /* tp_as_buffer */
1641 PLy_result_doc, /* tp_doc */
1645 /* Appear to be unused */
1646 static PyMethodDef PLy_result_methods[] = {
1647 {"fetch", (PyCFunction) PLy_result_fetch, METH_VARARGS, NULL,},
1648 {"nrows", (PyCFunction) PLy_result_nrows, METH_VARARGS, NULL},
1649 {"status", (PyCFunction) PLy_result_status, METH_VARARGS, NULL},
1650 {NULL, NULL, 0, NULL}
1654 static PyMethodDef PLy_methods[] = {
1658 {"debug", PLy_debug, METH_VARARGS, NULL},
1659 {"log", PLy_log, METH_VARARGS, NULL},
1660 {"info", PLy_info, METH_VARARGS, NULL},
1661 {"notice", PLy_notice, METH_VARARGS, NULL},
1662 {"warning", PLy_warning, METH_VARARGS, NULL},
1663 {"error", PLy_error, METH_VARARGS, NULL},
1664 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1667 * create a stored plan
1669 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1672 * execute a plan or query
1674 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1676 {NULL, NULL, 0, NULL}
1680 /* plan object methods
1689 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1697 return (PyObject *) ob;
1702 PLy_plan_dealloc(PyObject * arg)
1704 PLyPlanObject *ob = (PLyPlanObject *) arg;
1709 SPI_freeplan(ob->plan);
1711 PLy_free(ob->types);
1716 for (i = 0; i < ob->nargs; i++)
1717 PLy_typeinfo_dealloc(&ob->args[i]);
1728 PLy_plan_getattr(PyObject * self, char *name)
1730 return Py_FindMethod(PLy_plan_methods, self, name);
1734 PLy_plan_status(PyObject * self, PyObject * args)
1736 if (PyArg_ParseTuple(args, ""))
1740 /* return PyInt_FromLong(self->status); */
1742 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1748 /* result object methods
1752 PLy_result_new(void)
1754 PLyResultObject *ob;
1758 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1761 /* ob->tuples = NULL; */
1764 ob->status = Py_None;
1765 ob->nrows = PyInt_FromLong(-1);
1766 ob->rows = PyList_New(0);
1768 return (PyObject *) ob;
1772 PLy_result_dealloc(PyObject * arg)
1774 PLyResultObject *ob = (PLyResultObject *) arg;
1778 Py_XDECREF(ob->nrows);
1779 Py_XDECREF(ob->rows);
1780 Py_XDECREF(ob->status);
1786 PLy_result_getattr(PyObject * self, char *attr)
1792 /* Appear to be unused */
1794 PLy_result_fetch(PyObject * self, PyObject * args)
1800 PLy_result_nrows(PyObject * self, PyObject * args)
1802 PLyResultObject *ob = (PLyResultObject *) self;
1804 Py_INCREF(ob->nrows);
1809 PLy_result_status(PyObject * self, PyObject * args)
1811 PLyResultObject *ob = (PLyResultObject *) self;
1813 Py_INCREF(ob->status);
1818 PLy_result_length(PyObject * arg)
1820 PLyResultObject *ob = (PLyResultObject *) arg;
1822 return PyList_Size(ob->rows);
1826 PLy_result_item(PyObject * arg, int idx)
1829 PLyResultObject *ob = (PLyResultObject *) arg;
1831 rv = PyList_GetItem(ob->rows, idx);
1838 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1841 PLyResultObject *ob = (PLyResultObject *) arg;
1844 rv = PyList_SetItem(ob->rows, idx, item);
1849 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1852 PLyResultObject *ob = (PLyResultObject *) arg;
1854 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1862 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1865 PLyResultObject *ob = (PLyResultObject *) arg;
1867 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1874 PLy_spi_prepare(PyObject * self, PyObject * args)
1877 PLyPlanObject *plan;
1878 PyObject *list = NULL;
1879 PyObject *volatile optr = NULL;
1885 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1887 PyErr_SetString(PLy_exc_spi_error,
1888 "Invalid arguments for plpy.prepare()");
1892 if ((list) && (!PySequence_Check(list)))
1894 PyErr_SetString(PLy_exc_spi_error,
1895 "Second argument in plpy.prepare() must be a sequence");
1900 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1909 if (!PyErr_Occurred())
1910 PyErr_SetString(PLy_exc_spi_error,
1911 "Unknown error in PLy_spi_prepare");
1912 /* XXX this oughta be replaced with errcontext mechanism */
1913 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
1922 nargs = PySequence_Length(list);
1925 plan->nargs = nargs;
1926 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1927 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1928 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1931 * the other loop might throw an exception, if PLyTypeInfo
1932 * member isn't properly initialized the Py_DECREF(plan) will
1935 for (i = 0; i < nargs; i++)
1937 PLy_typeinfo_init(&plan->args[i]);
1938 plan->values[i] = (Datum) NULL;
1941 for (i = 0; i < nargs; i++)
1945 Form_pg_type typeStruct;
1947 optr = PySequence_GetItem(list, i);
1948 if (!PyString_Check(optr))
1950 PyErr_SetString(PLy_exc_spi_error,
1951 "Type names must be strings.");
1954 sptr = PyString_AsString(optr);
1955 /* XXX should extend this to allow qualified type names */
1956 typeTup = typenameType(makeTypeName(sptr));
1958 optr = NULL; /* this is important */
1960 plan->types[i] = HeapTupleGetOid(typeTup);
1961 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1962 if (typeStruct->typrelid == InvalidOid)
1963 PLy_output_datum_func(&plan->args[i], typeStruct);
1966 PyErr_SetString(PLy_exc_spi_error,
1967 "tuples not handled in plpy.prepare, yet.");
1970 ReleaseSysCache(typeTup);
1975 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1976 if (plan->plan == NULL)
1978 PLy_exception_set(PLy_exc_spi_error,
1979 "Unable to prepare plan. SPI_prepare failed -- %s.",
1980 PLy_spi_error_string(SPI_result));
1984 /* transfer plan from procCxt to topCxt */
1985 tmpplan = plan->plan;
1986 plan->plan = SPI_saveplan(tmpplan);
1987 SPI_freeplan(tmpplan);
1988 if (plan->plan == NULL)
1990 PLy_exception_set(PLy_exc_spi_error,
1991 "Unable to save plan. SPI_saveplan failed -- %s.",
1992 PLy_spi_error_string(SPI_result));
1998 return (PyObject *) plan;
2001 /* execute(query="select * from foo", limit=5)
2002 * execute(plan=plan, values=(foo, bar), limit=5)
2005 PLy_spi_execute(PyObject * self, PyObject * args)
2009 PyObject *list = NULL;
2017 * there should - hahaha - be an python exception set so just return
2018 * NULL. FIXME -- is this needed?
2020 if (PLy_restart_in_progress)
2024 if (PyArg_ParseTuple(args, "s|i", &query, &limit))
2025 return PLy_spi_execute_query(query, limit);
2029 if ((PyArg_ParseTuple(args, "O|Oi", &plan, &list, &limit)) &&
2030 (is_PLyPlanObject(plan)))
2032 PyObject *rv = PLy_spi_execute_plan(plan, list, limit);
2037 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2042 PLy_spi_execute_plan(PyObject * ob, PyObject * list, int limit)
2048 PLyPlanObject *plan;
2055 if ((!PySequence_Check(list)) || (PyString_Check(list)))
2057 char *msg = "plpy.execute() takes a sequence as its second argument";
2059 PyErr_SetString(PLy_exc_spi_error, msg);
2062 nargs = PySequence_Length(list);
2067 plan = (PLyPlanObject *) ob;
2069 if (nargs != plan->nargs)
2073 PyObject *so = PyObject_Str(list);
2075 sv = PyString_AsString(so);
2076 PLy_exception_set(PLy_exc_spi_error,
2077 "Expected sequence of %d arguments, got %d. %s",
2078 plan->nargs, nargs, sv);
2090 * cleanup plan->values array
2092 for (i = 0; i < nargs; i++)
2094 if (!plan->args[i].out.d.typbyval &&
2095 (plan->values[i] != (Datum) NULL))
2097 pfree(DatumGetPointer(plan->values[i]));
2098 plan->values[i] = (Datum) NULL;
2102 if (!PyErr_Occurred())
2103 PyErr_SetString(PLy_exc_error,
2104 "Unknown error in PLy_spi_execute_plan");
2105 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2111 nulls = palloc((nargs + 1) * sizeof(char));
2113 for (i = 0; i < nargs; i++)
2119 elem = PySequence_GetItem(list, i);
2120 if (elem != Py_None)
2122 so = PyObject_Str(elem);
2123 sv = PyString_AsString(so);
2126 * FIXME -- if this can elog, we have leak
2128 plan->values[i] = FunctionCall3(&(plan->args[i].out.d.typfunc),
2129 CStringGetDatum(sv),
2130 ObjectIdGetDatum(plan->args[i].out.d.typelem),
2141 plan->values[i] = (Datum) 0;
2150 rv = SPI_execp(plan->plan, plan->values, nulls, limit);
2153 for (i = 0; i < nargs; i++)
2155 if (!plan->args[i].out.d.typbyval &&
2156 (plan->values[i] != (Datum) NULL))
2158 pfree(DatumGetPointer(plan->values[i]));
2159 plan->values[i] = (Datum) NULL;
2165 PLy_exception_set(PLy_exc_spi_error,
2166 "Unable to execute plan. SPI_execp failed -- %s",
2167 PLy_spi_error_string(rv));
2171 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2175 PLy_spi_execute_query(char *query, int limit)
2184 if ((!PLy_restart_in_progress) && (!PyErr_Occurred()))
2185 PyErr_SetString(PLy_exc_spi_error,
2186 "Unknown error in PLy_spi_execute_query");
2187 PLy_elog(WARNING, "in function %s:", PLy_procedure_name(PLy_last_procedure));
2191 rv = SPI_exec(query, limit);
2195 PLy_exception_set(PLy_exc_spi_error,
2196 "Unable to execute query. SPI_exec failed -- %s",
2197 PLy_spi_error_string(rv));
2201 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2205 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2207 PLyResultObject *result;
2211 result = (PLyResultObject *) PLy_result_new();
2212 Py_DECREF(result->status);
2213 result->status = PyInt_FromLong(status);
2215 if (status == SPI_OK_UTILITY)
2217 Py_DECREF(result->nrows);
2218 result->nrows = PyInt_FromLong(0);
2220 else if (status != SPI_OK_SELECT)
2222 Py_DECREF(result->nrows);
2223 result->nrows = PyInt_FromLong(rows);
2231 PLy_typeinfo_init(&args);
2232 Py_DECREF(result->nrows);
2233 result->nrows = PyInt_FromLong(rows);
2240 if (!PyErr_Occurred())
2241 PyErr_SetString(PLy_exc_error,
2242 "Unknown error in PLy_spi_execute_fetch_result");
2244 PLy_typeinfo_dealloc(&args);
2250 Py_DECREF(result->rows);
2251 result->rows = PyList_New(rows);
2253 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2254 for (i = 0; i < rows; i++)
2256 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2259 PyList_SetItem(result->rows, i, row);
2261 PLy_typeinfo_dealloc(&args);
2263 SPI_freetuptable(tuptable);
2268 return (PyObject *) result;
2272 PLy_spi_error_string(int code)
2276 case SPI_ERROR_TYPUNKNOWN:
2277 return "SPI_ERROR_TYPUNKNOWN";
2278 case SPI_ERROR_NOOUTFUNC:
2279 return "SPI_ERROR_NOOUTFUNC";
2280 case SPI_ERROR_NOATTRIBUTE:
2281 return "SPI_ERROR_NOATTRIBUTE";
2282 case SPI_ERROR_TRANSACTION:
2283 return "SPI_ERROR_TRANSACTION";
2284 case SPI_ERROR_PARAM:
2285 return "SPI_ERROR_PARAM";
2286 case SPI_ERROR_ARGUMENT:
2287 return "SPI_ERROR_ARGUMENT";
2288 case SPI_ERROR_CURSOR:
2289 return "SPI_ERROR_CURSOR";
2290 case SPI_ERROR_UNCONNECTED:
2291 return "SPI_ERROR_UNCONNECTED";
2292 case SPI_ERROR_OPUNKNOWN:
2293 return "SPI_ERROR_OPUNKNOWN";
2294 case SPI_ERROR_COPY:
2295 return "SPI_ERROR_COPY";
2296 case SPI_ERROR_CONNECT:
2297 return "SPI_ERROR_CONNECT";
2299 return "Unknown or Invalid code";
2302 /* language handler and interpreter initialization
2306 * plpython_init() - Initialize everything that can be
2307 * safely initialized during postmaster
2310 * DO NOT make this static --- it has to be callable by preload
2315 static volatile int init_active = 0;
2317 /* Do initialization only once */
2318 if (!PLy_first_call)
2324 elog(FATAL, "initialization of language module failed");
2330 if (PyErr_Occurred())
2331 PLy_elog(FATAL, "untrapped error in initialization");
2332 PLy_procedure_cache = PyDict_New();
2333 if (PLy_procedure_cache == NULL)
2334 PLy_elog(ERROR, "could not create procedure cache");
2344 /* Execute postmaster-startup safe initialization */
2349 * Any other initialization that must be done each time a new backend
2350 * starts -- currently none
2356 PLy_init_interp(void)
2362 mainmod = PyImport_AddModule("__main__");
2363 if ((mainmod == NULL) || (PyErr_Occurred()))
2364 PLy_elog(ERROR, "could not import \"__main__\" module.");
2366 PLy_interp_globals = PyModule_GetDict(mainmod);
2367 PLy_interp_safe_globals = PyDict_New();
2368 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2370 if ((PLy_interp_globals == NULL) || (PyErr_Occurred()))
2371 PLy_elog(ERROR, "could not initialize globals");
2386 * initialize plpy module
2388 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2389 plpy = Py_InitModule("plpy", PLy_methods);
2390 plpy_dict = PyModule_GetDict(plpy);
2392 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2394 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2395 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2396 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2397 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2398 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2399 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2402 * initialize main module, and add plpy
2404 main_mod = PyImport_AddModule("__main__");
2405 main_dict = PyModule_GetDict(main_mod);
2406 plpy_mod = PyImport_AddModule("plpy");
2407 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2408 if (PyErr_Occurred())
2409 elog(ERROR, "could not init plpy");
2412 /* the python interface to the elog function
2413 * don't confuse these with PLy_elog
2415 static PyObject *PLy_output(int, PyObject *, PyObject *);
2418 PLy_debug(PyObject * self, PyObject * args)
2420 return PLy_output(DEBUG2, self, args);
2424 PLy_log(PyObject * self, PyObject * args)
2426 return PLy_output(LOG, self, args);
2430 PLy_info(PyObject * self, PyObject * args)
2432 return PLy_output(INFO, self, args);
2436 PLy_notice(PyObject * self, PyObject * args)
2438 return PLy_output(NOTICE, self, args);
2442 PLy_warning(PyObject * self, PyObject * args)
2444 return PLy_output(WARNING, self, args);
2448 PLy_error(PyObject * self, PyObject * args)
2450 return PLy_output(ERROR, self, args);
2454 PLy_fatal(PyObject * self, PyObject * args)
2456 return PLy_output(FATAL, self, args);
2461 PLy_output(volatile int level, PyObject * self, PyObject * args)
2470 elog(WARNING, "args is NULL");
2472 so = PyObject_Str(args);
2473 if ((so == NULL) || ((sv = PyString_AsString(so)) == NULL))
2476 sv = "Unable to parse error message in `plpy.elog'";
2480 * returning NULL here causes the python interpreter to bail. when
2481 * control passes back into plpython_*_handler, we check for python
2482 * exceptions and do the actual elog call. actually PLy_elog.
2486 PyErr_SetString(PLy_exc_error, sv);
2489 else if (level >= FATAL)
2491 PyErr_SetString(PLy_exc_fatal, sv);
2496 * ok, this is a WARNING, or LOG message
2498 * but just in case DON'T long jump out of the interpreter!
2508 * the real error message should already be written into the
2509 * postgresql log, no? whatever, this shouldn't happen so die
2512 elog(FATAL, "elog threw an unknown exception");
2516 elog(level, "%s", sv);
2524 * return a legal object so the interpreter will continue on its merry
2532 * Get the last procedure name called by the backend ( the innermost,
2533 * If a plpython procedure call calls the backend and the backend calls
2534 * another plpython procedure )
2536 * NB: this returns SQL name, not the internal Python procedure name
2540 PLy_procedure_name(PLyProcedure * proc)
2543 return "<unknown procedure>";
2544 return proc->proname;
2547 /* output a python traceback/exception via the postgresql elog
2548 * function. not pretty.
2551 static char *PLy_traceback(int *);
2552 static char *PLy_vprintf(const char *fmt, va_list ap);
2553 static char *PLy_printf(const char *fmt,...);
2556 PLy_exception_set(PyObject * exc, const char *fmt,...)
2562 vsnprintf(buf, sizeof(buf), fmt, ap);
2565 PyErr_SetString(exc, buf);
2569 PLy_elog(int elevel, const char *fmt,...)
2579 xmsg = PLy_traceback(&xlevel);
2582 emsg = PLy_vprintf(fmt, ap);
2592 * elog called siglongjmp. cleanup, restore and reraise
2594 PLy_restart_in_progress += 1;
2602 (errmsg("plpython: %s", emsg),
2603 (xmsg) ? errdetail("%s", xmsg) : 0));
2615 PLy_traceback(int *xlevel)
2629 * get the current exception
2631 PyErr_Fetch(&e, &v, &tb);
2634 * oops, no exception, return
2642 PyErr_NormalizeException(&e, &v, &tb);
2644 eob = PyObject_Str(e);
2645 if ((v) && ((vob = PyObject_Str(v)) != NULL))
2646 vstr = PyString_AsString(vob);
2650 estr = PyString_AsString(eob);
2651 xstr = PLy_printf("%s: %s", estr, vstr);
2657 * intuit an appropriate error level for based on the exception type
2659 if ((PLy_exc_error) && (PyErr_GivenExceptionMatches(e, PLy_exc_error)))
2661 else if ((PLy_exc_fatal) && (PyErr_GivenExceptionMatches(e, PLy_exc_fatal)))
2672 PLy_printf(const char *fmt,...)
2678 emsg = PLy_vprintf(fmt, ap);
2684 PLy_vprintf(const char *fmt, va_list ap)
2691 blen = strlen(fmt) * 2;
2694 buf = PLy_malloc(blen * sizeof(char));
2698 bchar = vsnprintf(buf, blen, fmt, ap);
2699 if ((bchar > 0) && (bchar < blen))
2707 buf = PLy_realloc(buf, blen);
2713 /* python module code
2717 /* some dumb utility functions
2721 PLy_malloc(size_t bytes)
2723 void *ptr = malloc(bytes);
2727 (errcode(ERRCODE_OUT_OF_MEMORY),
2728 errmsg("out of memory")));
2733 PLy_realloc(void *optr, size_t bytes)
2735 void *nptr = realloc(optr, bytes);
2739 (errcode(ERRCODE_OUT_OF_MEMORY),
2740 errmsg("out of memory")));