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.57 2004/09/19 23:38:21 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"
61 /* convert Postgresql Datum or tuple into a PyObject.
62 * input to Python. Tuples are converted to dictionary
66 typedef PyObject *(*PLyDatumToObFunc) (const char *);
68 typedef struct PLyDatumToOb
70 PLyDatumToObFunc func;
76 typedef struct PLyTupleToOb
82 typedef union PLyTypeInput
88 /* convert PyObject to a Postgresql Datum or tuple.
91 typedef struct PLyObToDatum
98 typedef struct PLyObToTuple
104 typedef union PLyTypeOutput
110 /* all we need to move Postgresql data to Python objects,
113 typedef struct PLyTypeInfo
120 * is_rowtype can be: -1 not known yet (initial state) 0 scalar
121 * datatype 1 rowtype 2 rowtype, but I/O functions not set up yet
126 /* cached procedure data
128 typedef struct PLyProcedure
130 char *proname; /* SQL name of procedure */
131 char *pyname; /* Python name of procedure */
132 TransactionId fn_xmin;
135 PLyTypeInfo result; /* also used to store info for trigger
137 PLyTypeInfo args[FUNC_MAX_ARGS];
139 PyObject *code; /* compiled procedure code */
140 PyObject *statics; /* data saved across calls, local scope */
141 PyObject *globals; /* data saved across calls, global score */
142 PyObject *me; /* PyCObject containing pointer to this
149 typedef struct PLyPlanObject
152 void *plan; /* return of an SPI_saveplan */
159 typedef struct PLyResultObject
162 /* HeapTuple *tuples; */
163 PyObject * nrows; /* number of rows returned by query */
164 PyObject *rows; /* data rows, or None if no data returned */
165 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
169 /* function declarations
172 /* Two exported functions: first is the magic telling Postgresql
173 * what function call interface it implements. Second allows
174 * preinitialization of the interpreter during postmaster startup.
176 Datum plpython_call_handler(PG_FUNCTION_ARGS);
177 void plpython_init(void);
179 PG_FUNCTION_INFO_V1(plpython_call_handler);
181 /* most of the remaining of the declarations, all static
184 /* these should only be called once at the first call
185 * of plpython_call_handler. initialize the python interpreter
188 static void PLy_init_all(void);
189 static void PLy_init_interp(void);
190 static void PLy_init_plpy(void);
192 /* call PyErr_SetString with a vprint interface
195 PLy_exception_set(PyObject *, const char *,...)
196 __attribute__((format(printf, 2, 3)));
198 /* Get the innermost python procedure called from the backend.
200 static char *PLy_procedure_name(PLyProcedure *);
202 /* some utility functions
204 static void PLy_elog(int, const char *,...);
205 static char *PLy_traceback(int *);
206 static char *PLy_vprintf(const char *fmt, va_list ap);
207 static char *PLy_printf(const char *fmt,...);
209 static void *PLy_malloc(size_t);
210 static void *PLy_realloc(void *, size_t);
211 static void PLy_free(void *);
213 /* sub handlers for functions and triggers
215 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
216 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
218 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
219 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
221 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
222 TriggerData *, HeapTuple);
224 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
226 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
229 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
231 HeapTuple procTup, char *key);
233 static void PLy_procedure_compile(PLyProcedure *, const char *);
234 static char *PLy_procedure_munge_source(const char *, const char *);
235 static void PLy_procedure_delete(PLyProcedure *);
237 static void PLy_typeinfo_init(PLyTypeInfo *);
238 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
239 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
240 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
241 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
242 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
243 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
244 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
246 /* conversion functions
248 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
249 static PyObject *PLyBool_FromString(const char *);
250 static PyObject *PLyFloat_FromString(const char *);
251 static PyObject *PLyInt_FromString(const char *);
252 static PyObject *PLyLong_FromString(const char *);
253 static PyObject *PLyString_FromString(const char *);
258 static int PLy_first_call = 1;
261 * Currently active plpython function
263 static PLyProcedure *PLy_curr_procedure = NULL;
266 * When a callback from Python into PG incurs an error, we temporarily store
267 * the error information here, and return NULL to the Python interpreter.
268 * Any further callback attempts immediately fail, and when the Python
269 * interpreter returns to the calling function, we re-throw the error (even if
270 * Python thinks it trapped the error and doesn't return NULL). Eventually
271 * this ought to be improved to let Python code really truly trap the error,
272 * but that's more of a change from the pre-8.0 semantics than I have time for
273 * now --- it will only be possible if the callback query is executed inside a
276 static ErrorData *PLy_error_in_progress = NULL;
278 static PyObject *PLy_interp_globals = NULL;
279 static PyObject *PLy_interp_safe_globals = NULL;
280 static PyObject *PLy_procedure_cache = NULL;
284 static PyObject *PLy_exc_error = NULL;
285 static PyObject *PLy_exc_fatal = NULL;
286 static PyObject *PLy_exc_spi_error = NULL;
288 /* some globals for the python module
290 static char PLy_plan_doc[] = {
291 "Store a PostgreSQL plan"
294 static char PLy_result_doc[] = {
295 "Results of a PostgreSQL query"
300 * the function definitions
304 * This routine is a crock, and so is everyplace that calls it. The problem
305 * is that the cached form of plpython functions/queries is allocated permanently
306 * (mostly via malloc()) and never released until backend exit. Subsidiary
307 * data structures such as fmgr info records therefore must live forever
308 * as well. A better implementation would store all this stuff in a per-
309 * function memory context that could be reclaimed at need. In the meantime,
310 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
311 * it might allocate, and whatever the eventual function might allocate using
312 * fn_mcxt, will live forever too.
315 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
317 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
321 plpython_call_handler(PG_FUNCTION_ARGS)
324 PLyProcedure *save_curr_proc;
325 PLyProcedure *volatile proc = NULL;
329 if (SPI_connect() != SPI_OK_CONNECT)
330 elog(ERROR, "could not connect to SPI manager");
332 save_curr_proc = PLy_curr_procedure;
336 if (CALLED_AS_TRIGGER(fcinfo))
338 TriggerData *tdata = (TriggerData *) fcinfo->context;
341 proc = PLy_procedure_get(fcinfo,
342 RelationGetRelid(tdata->tg_relation));
343 PLy_curr_procedure = proc;
344 trv = PLy_trigger_handler(fcinfo, proc);
345 retval = PointerGetDatum(trv);
349 proc = PLy_procedure_get(fcinfo, InvalidOid);
350 PLy_curr_procedure = proc;
351 retval = PLy_function_handler(fcinfo, proc);
356 PLy_curr_procedure = save_curr_proc;
359 /* note: Py_DECREF needs braces around it, as of 2003/08 */
367 PLy_curr_procedure = save_curr_proc;
374 /* trigger and function sub handlers
376 * the python function is expected to return Py_None if the tuple is
377 * acceptable and unmodified. Otherwise it should return a PyString
378 * object who's value is SKIP, or MODIFY. SKIP means don't perform
379 * this action. MODIFY means the tuple has been modified, so update
380 * tuple and perform action. SKIP and MODIFY assume the trigger fires
381 * BEFORE the event and is ROW level. postgres expects the function
382 * to take no arguments and return an argument of type trigger.
385 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
388 PyObject *volatile plargs = NULL;
389 PyObject *volatile plrv = NULL;
393 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
394 plrv = PLy_procedure_call(proc, "TD", plargs);
396 Assert(plrv != NULL);
397 Assert(!PLy_error_in_progress);
400 * Disconnect from SPI manager
402 if (SPI_finish() != SPI_OK_FINISH)
403 elog(ERROR, "SPI_finish failed");
406 * return of None means we're happy with the tuple
412 if (!PyString_Check(plrv))
413 elog(ERROR, "expected trigger to return None or a String");
415 srv = PyString_AsString(plrv);
416 if (pg_strcasecmp(srv, "SKIP") == 0)
418 else if (pg_strcasecmp(srv, "MODIFY") == 0)
420 TriggerData *tdata = (TriggerData *) fcinfo->context;
422 if ((TRIGGER_FIRED_BY_INSERT(tdata->tg_event)) ||
423 (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event)))
424 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
426 elog(WARNING, "ignoring modified tuple in DELETE trigger");
428 else if (pg_strcasecmp(srv, "OK") != 0)
431 * hmmm, perhaps they only read the pltcl page, not a
432 * surprising thing since i've written no documentation,
433 * so accept a belated OK
435 elog(ERROR, "expected return to be \"SKIP\" or \"MODIFY\"");
455 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
458 PyObject *volatile plntup;
459 PyObject *volatile plkeys;
460 PyObject *volatile platt;
461 PyObject *volatile plval;
462 PyObject *volatile plstr;
468 int *volatile modattrs;
469 Datum *volatile modvalues;
470 char *volatile modnulls;
473 plntup = plkeys = platt = plval = plstr = NULL;
480 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
481 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
482 if (!PyDict_Check(plntup))
483 elog(ERROR, "TD[\"new\"] is not a dictionary object");
486 plkeys = PyDict_Keys(plntup);
487 natts = PyList_Size(plkeys);
489 modattrs = (int *) palloc(natts * sizeof(int));
490 modvalues = (Datum *) palloc(natts * sizeof(Datum));
491 modnulls = (char *) palloc(natts * sizeof(char));
493 tupdesc = tdata->tg_relation->rd_att;
495 for (i = 0; i < natts; i++)
499 platt = PyList_GetItem(plkeys, i);
500 if (!PyString_Check(platt))
501 elog(ERROR, "attribute name is not a string");
502 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
503 if (attn == SPI_ERROR_NOATTRIBUTE)
504 elog(ERROR, "invalid attribute \"%s\" in tuple",
505 PyString_AsString(platt));
508 plval = PyDict_GetItem(plntup, platt);
510 elog(FATAL, "python interpreter is probably corrupted");
516 if (plval != Py_None && !tupdesc->attrs[atti]->attisdropped)
518 plstr = PyObject_Str(plval);
519 src = PyString_AsString(plstr);
521 modvalues[i] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
522 CStringGetDatum(src),
523 ObjectIdGetDatum(proc->result.out.r.atts[atti].typioparam),
524 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
532 modvalues[i] = (Datum) 0;
540 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
541 modattrs, modvalues, modnulls);
543 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
575 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
577 TriggerData *tdata = (TriggerData *) fcinfo->context;
586 PyObject *volatile pltdata = NULL;
591 pltdata = PyDict_New();
593 PLy_elog(ERROR, "could not build arguments for trigger procedure");
595 pltname = PyString_FromString(tdata->tg_trigger->tgname);
596 PyDict_SetItemString(pltdata, "name", pltname);
599 stroid = DatumGetCString(DirectFunctionCall1(oidout,
600 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
601 pltrelid = PyString_FromString(stroid);
602 PyDict_SetItemString(pltdata, "relid", pltrelid);
606 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
607 pltwhen = PyString_FromString("BEFORE");
608 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
609 pltwhen = PyString_FromString("AFTER");
612 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
613 pltwhen = NULL; /* keep compiler quiet */
615 PyDict_SetItemString(pltdata, "when", pltwhen);
618 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
620 pltlevel = PyString_FromString("ROW");
621 PyDict_SetItemString(pltdata, "level", pltlevel);
624 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
626 pltevent = PyString_FromString("INSERT");
628 PyDict_SetItemString(pltdata, "old", Py_None);
629 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
630 tdata->tg_relation->rd_att);
631 PyDict_SetItemString(pltdata, "new", pytnew);
633 *rv = tdata->tg_trigtuple;
635 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
637 pltevent = PyString_FromString("DELETE");
639 PyDict_SetItemString(pltdata, "new", Py_None);
640 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
641 tdata->tg_relation->rd_att);
642 PyDict_SetItemString(pltdata, "old", pytold);
644 *rv = tdata->tg_trigtuple;
646 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
648 pltevent = PyString_FromString("UPDATE");
650 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
651 tdata->tg_relation->rd_att);
652 PyDict_SetItemString(pltdata, "new", pytnew);
654 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
655 tdata->tg_relation->rd_att);
656 PyDict_SetItemString(pltdata, "old", pytold);
658 *rv = tdata->tg_newtuple;
662 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
663 pltevent = NULL; /* keep compiler quiet */
666 PyDict_SetItemString(pltdata, "event", pltevent);
669 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
671 pltlevel = PyString_FromString("STATEMENT");
672 PyDict_SetItemString(pltdata, "level", pltlevel);
675 PyDict_SetItemString(pltdata, "old", Py_None);
676 PyDict_SetItemString(pltdata, "new", Py_None);
679 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
680 pltevent = PyString_FromString("INSERT");
681 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
682 pltevent = PyString_FromString("DELETE");
683 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
684 pltevent = PyString_FromString("UPDATE");
687 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
688 pltevent = NULL; /* keep compiler quiet */
691 PyDict_SetItemString(pltdata, "event", pltevent);
695 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
697 if (tdata->tg_trigger->tgnargs)
705 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
706 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
708 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
711 * stolen, don't Py_DECREF
713 PyList_SetItem(pltargs, i, pltarg);
721 PyDict_SetItemString(pltdata, "args", pltargs);
736 /* function handler and friends
739 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
742 PyObject *volatile plargs = NULL;
743 PyObject *volatile plrv = NULL;
744 PyObject *volatile plrv_so = NULL;
749 plargs = PLy_function_build_args(fcinfo, proc);
750 plrv = PLy_procedure_call(proc, "args", plargs);
752 Assert(plrv != NULL);
753 Assert(!PLy_error_in_progress);
756 * Disconnect from SPI manager and then create the return values
757 * datum (if the input function does a palloc for it this must not
758 * be allocated in the SPI memory context because SPI_finish would
761 if (SPI_finish() != SPI_OK_FINISH)
762 elog(ERROR, "SPI_finish failed");
765 * convert the python PyObject to a postgresql Datum
769 fcinfo->isnull = true;
774 fcinfo->isnull = false;
775 plrv_so = PyObject_Str(plrv);
776 plrv_sc = PyString_AsString(plrv_so);
777 rv = FunctionCall3(&proc->result.out.d.typfunc,
778 PointerGetDatum(plrv_sc),
779 ObjectIdGetDatum(proc->result.out.d.typioparam),
802 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
806 PyDict_SetItemString(proc->globals, kargs, vargs);
807 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
808 proc->globals, proc->globals);
811 * If there was an error in a PG callback, propagate that no matter
812 * what Python claims about its success.
814 if (PLy_error_in_progress)
816 ErrorData *edata = PLy_error_in_progress;
818 PLy_error_in_progress = NULL;
822 if ((rv == NULL) || (PyErr_Occurred()))
825 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
832 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
834 PyObject *volatile arg = NULL;
835 PyObject *volatile args = NULL;
840 args = PyList_New(proc->nargs);
841 for (i = 0; i < proc->nargs; i++)
843 if (proc->args[i].is_rowtype > 0)
845 if (fcinfo->argnull[i])
853 HeapTupleData tmptup;
855 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
856 /* Extract rowtype info and find a tupdesc */
857 tupType = HeapTupleHeaderGetTypeId(td);
858 tupTypmod = HeapTupleHeaderGetTypMod(td);
859 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
861 /* Set up I/O funcs if not done yet */
862 if (proc->args[i].is_rowtype != 1)
863 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
865 /* Build a temporary HeapTuple control structure */
866 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
869 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
874 if (fcinfo->argnull[i])
881 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
883 ObjectIdGetDatum(proc->args[i].in.d.typioparam),
885 ct = DatumGetCString(dt);
886 arg = (proc->args[i].in.d.func) (ct);
898 * FIXME -- error check this
900 PyList_SetItem(args, i, arg);
917 * PLyProcedure functions
920 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
921 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
922 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
925 static PLyProcedure *
926 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
932 PLyProcedure *proc = NULL;
935 fn_oid = fcinfo->flinfo->fn_oid;
936 procTup = SearchSysCache(PROCOID,
937 ObjectIdGetDatum(fn_oid),
939 if (!HeapTupleIsValid(procTup))
940 elog(ERROR, "cache lookup failed for function %u", fn_oid);
942 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
943 if ((rv >= sizeof(key)) || (rv < 0))
944 elog(ERROR, "key too long");
946 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
951 if (!PyCObject_Check(plproc))
952 elog(FATAL, "expected a PyCObject, didn't get one");
954 proc = PyCObject_AsVoidPtr(plproc);
955 if (proc->me != plproc)
956 elog(FATAL, "proc->me != plproc");
957 /* did we find an up-to-date cache entry? */
958 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
959 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
967 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
969 ReleaseSysCache(procTup);
974 static PLyProcedure *
975 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
976 HeapTuple procTup, char *key)
978 char procName[NAMEDATALEN + 256];
979 Form_pg_proc procStruct;
980 PLyProcedure *volatile proc;
981 char *volatile procSource = NULL;
987 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
989 if (OidIsValid(tgreloid))
990 rv = snprintf(procName, sizeof(procName),
991 "__plpython_procedure_%s_%u_trigger_%u",
992 NameStr(procStruct->proname),
993 fcinfo->flinfo->fn_oid,
996 rv = snprintf(procName, sizeof(procName),
997 "__plpython_procedure_%s_%u",
998 NameStr(procStruct->proname),
999 fcinfo->flinfo->fn_oid);
1000 if ((rv >= sizeof(procName)) || (rv < 0))
1001 elog(ERROR, "procedure name would overrun buffer");
1003 proc = PLy_malloc(sizeof(PLyProcedure));
1004 proc->proname = PLy_malloc(strlen(NameStr(procStruct->proname)) + 1);
1005 strcpy(proc->proname, NameStr(procStruct->proname));
1006 proc->pyname = PLy_malloc(strlen(procName) + 1);
1007 strcpy(proc->pyname, procName);
1008 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1009 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1010 /* Remember if function is STABLE/IMMUTABLE */
1012 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1013 PLy_typeinfo_init(&proc->result);
1014 for (i = 0; i < FUNC_MAX_ARGS; i++)
1015 PLy_typeinfo_init(&proc->args[i]);
1017 proc->code = proc->statics = NULL;
1018 proc->globals = proc->me = NULL;
1023 * get information required for output conversion of the return
1024 * value, but only if this isn't a trigger.
1026 if (!CALLED_AS_TRIGGER(fcinfo))
1028 HeapTuple rvTypeTup;
1029 Form_pg_type rvTypeStruct;
1031 rvTypeTup = SearchSysCache(TYPEOID,
1032 ObjectIdGetDatum(procStruct->prorettype),
1034 if (!HeapTupleIsValid(rvTypeTup))
1035 elog(ERROR, "cache lookup failed for type %u",
1036 procStruct->prorettype);
1037 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1039 /* Disallow pseudotype result */
1040 if (rvTypeStruct->typtype == 'p')
1042 if (procStruct->prorettype == TRIGGEROID)
1044 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1045 errmsg("trigger functions may only be called as triggers")));
1048 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1049 errmsg("plpython functions cannot return type %s",
1050 format_type_be(procStruct->prorettype))));
1053 if (rvTypeStruct->typtype == 'c')
1055 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1056 errmsg("plpython functions cannot return tuples yet")));
1058 PLy_output_datum_func(&proc->result, rvTypeTup);
1060 ReleaseSysCache(rvTypeTup);
1065 * input/output conversion for trigger tuples. use the result
1066 * TypeInfo variable to store the tuple conversion info.
1068 TriggerData *tdata = (TriggerData *) fcinfo->context;
1070 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1071 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1075 * now get information required for input conversion of the
1076 * procedures arguments.
1078 proc->nargs = fcinfo->nargs;
1079 for (i = 0; i < fcinfo->nargs; i++)
1081 HeapTuple argTypeTup;
1082 Form_pg_type argTypeStruct;
1084 argTypeTup = SearchSysCache(TYPEOID,
1085 ObjectIdGetDatum(procStruct->proargtypes[i]),
1087 if (!HeapTupleIsValid(argTypeTup))
1088 elog(ERROR, "cache lookup failed for type %u",
1089 procStruct->proargtypes[i]);
1090 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1092 /* Disallow pseudotype argument */
1093 if (argTypeStruct->typtype == 'p')
1095 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1096 errmsg("plpython functions cannot take type %s",
1097 format_type_be(procStruct->proargtypes[i]))));
1099 if (argTypeStruct->typtype != 'c')
1100 PLy_input_datum_func(&(proc->args[i]),
1101 procStruct->proargtypes[i],
1104 proc->args[i].is_rowtype = 2; /* still need to set I/O
1107 ReleaseSysCache(argTypeTup);
1112 * get the text of the function.
1114 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1115 Anum_pg_proc_prosrc, &isnull);
1117 elog(ERROR, "null prosrc");
1118 procSource = DatumGetCString(DirectFunctionCall1(textout,
1121 PLy_procedure_compile(proc, procSource);
1125 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1126 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1130 PLy_procedure_delete(proc);
1142 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1144 PyObject *crv = NULL;
1147 proc->globals = PyDict_Copy(PLy_interp_globals);
1150 * SD is private preserved data between calls GD is global data shared
1153 proc->statics = PyDict_New();
1154 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1157 * insert the function code into the interpreter
1159 msrc = PLy_procedure_munge_source(proc->pyname, src);
1160 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1163 if ((crv != NULL) && (!PyErr_Occurred()))
1166 char call[NAMEDATALEN + 256];
1171 * compile a call to the function
1173 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1174 if ((clen < 0) || (clen >= sizeof(call)))
1175 elog(ERROR, "string would overflow buffer");
1176 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1177 if ((proc->code != NULL) && (!PyErr_Occurred()))
1183 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1187 PLy_procedure_munge_source(const char *name, const char *src)
1196 * room for function source and the def statement
1198 mlen = (strlen(src) * 2) + strlen(name) + 16;
1200 mrc = PLy_malloc(mlen);
1201 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1202 Assert(plen >= 0 && plen < mlen);
1221 if (mp > (mrc + mlen))
1222 elog(FATAL, "buffer overrun in PLy_munge_source");
1228 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_rowtype == 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);
1250 /* conversion functions. remember output from python is
1251 * input to postgresql, and vis versa.
1254 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1258 if (arg->is_rowtype == 0)
1259 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1261 arg->is_rowtype = 1;
1262 arg->in.r.natts = desc->natts;
1263 arg->in.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1265 for (i = 0; i < desc->natts; i++)
1269 if (desc->attrs[i]->attisdropped)
1272 typeTup = SearchSysCache(TYPEOID,
1273 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1275 if (!HeapTupleIsValid(typeTup))
1276 elog(ERROR, "cache lookup failed for type %u",
1277 desc->attrs[i]->atttypid);
1279 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1280 desc->attrs[i]->atttypid,
1283 ReleaseSysCache(typeTup);
1288 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1292 if (arg->is_rowtype == 0)
1293 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1295 arg->is_rowtype = 1;
1296 arg->out.r.natts = desc->natts;
1297 arg->out.r.atts = malloc(desc->natts * sizeof(PLyDatumToOb));
1299 for (i = 0; i < desc->natts; i++)
1303 if (desc->attrs[i]->attisdropped)
1306 typeTup = SearchSysCache(TYPEOID,
1307 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1309 if (!HeapTupleIsValid(typeTup))
1310 elog(ERROR, "cache lookup failed for type %u",
1311 desc->attrs[i]->atttypid);
1313 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1315 ReleaseSysCache(typeTup);
1320 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1322 if (arg->is_rowtype > 0)
1323 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1324 arg->is_rowtype = 0;
1325 PLy_output_datum_func2(&(arg->out.d), typeTup);
1329 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1331 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1333 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1334 arg->typioparam = getTypeIOParam(typeTup);
1335 arg->typbyval = typeStruct->typbyval;
1339 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1341 if (arg->is_rowtype > 0)
1342 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1343 arg->is_rowtype = 0;
1344 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1348 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1350 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1352 /* Get the type's conversion information */
1353 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1354 arg->typioparam = getTypeIOParam(typeTup);
1355 arg->typbyval = typeStruct->typbyval;
1357 /* Determine which kind of Python object we will convert to */
1361 arg->func = PLyBool_FromString;
1366 arg->func = PLyFloat_FromString;
1370 arg->func = PLyInt_FromString;
1373 arg->func = PLyLong_FromString;
1376 arg->func = PLyString_FromString;
1382 PLy_typeinfo_init(PLyTypeInfo * arg)
1384 arg->is_rowtype = -1;
1385 arg->in.r.natts = arg->out.r.natts = 0;
1386 arg->in.r.atts = NULL;
1387 arg->out.r.atts = NULL;
1391 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1393 if (arg->is_rowtype == 1)
1396 PLy_free(arg->in.r.atts);
1397 if (arg->out.r.atts)
1398 PLy_free(arg->out.r.atts);
1402 /* assumes that a bool is always returned as a 't' or 'f'
1405 PLyBool_FromString(const char *src)
1408 return PyInt_FromLong(1);
1409 return PyInt_FromLong(0);
1413 PLyFloat_FromString(const char *src)
1419 v = strtod(src, &eptr);
1420 if ((*eptr != '\0') || (errno))
1422 return PyFloat_FromDouble(v);
1426 PLyInt_FromString(const char *src)
1432 v = strtol(src, &eptr, 0);
1433 if ((*eptr != '\0') || (errno))
1435 return PyInt_FromLong(v);
1439 PLyLong_FromString(const char *src)
1441 return PyLong_FromString((char *) src, NULL, 0);
1445 PLyString_FromString(const char *src)
1447 return PyString_FromString(src);
1451 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1453 PyObject *volatile dict;
1456 if (info->is_rowtype != 1)
1457 elog(ERROR, "PLyTypeInfo structure describes a datum");
1459 dict = PyDict_New();
1461 PLy_elog(ERROR, "could not create tuple dictionary");
1465 for (i = 0; i < info->in.r.natts; i++)
1474 if (desc->attrs[i]->attisdropped)
1477 key = NameStr(desc->attrs[i]->attname);
1478 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1480 if ((is_null) || (info->in.r.atts[i].func == NULL))
1481 PyDict_SetItemString(dict, key, Py_None);
1484 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1486 ObjectIdGetDatum(info->in.r.atts[i].typioparam),
1487 Int32GetDatum(desc->attrs[i]->atttypmod));
1488 vsrc = DatumGetCString(vdat);
1491 * no exceptions allowed
1493 value = info->in.r.atts[i].func(vsrc);
1495 PyDict_SetItemString(dict, key, value);
1510 /* initialization, some python variables function declared here
1513 /* interface to postgresql elog
1515 static PyObject *PLy_debug(PyObject *, PyObject *);
1516 static PyObject *PLy_log(PyObject *, PyObject *);
1517 static PyObject *PLy_info(PyObject *, PyObject *);
1518 static PyObject *PLy_notice(PyObject *, PyObject *);
1519 static PyObject *PLy_warning(PyObject *, PyObject *);
1520 static PyObject *PLy_error(PyObject *, PyObject *);
1521 static PyObject *PLy_fatal(PyObject *, PyObject *);
1523 /* PLyPlanObject, PLyResultObject and SPI interface
1525 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1526 static PyObject *PLy_plan_new(void);
1527 static void PLy_plan_dealloc(PyObject *);
1528 static PyObject *PLy_plan_getattr(PyObject *, char *);
1529 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1531 static PyObject *PLy_result_new(void);
1532 static void PLy_result_dealloc(PyObject *);
1533 static PyObject *PLy_result_getattr(PyObject *, char *);
1536 /* Appear to be unused */
1537 static PyObject *PLy_result_fetch(PyObject *, PyObject *);
1538 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1539 static PyObject *PLy_result_status(PyObject *, PyObject *);
1541 static int PLy_result_length(PyObject *);
1542 static PyObject *PLy_result_item(PyObject *, int);
1543 static PyObject *PLy_result_slice(PyObject *, int, int);
1544 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1545 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1548 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1549 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1550 static PyObject *PLy_spi_execute_query(char *query, int limit);
1551 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, int);
1552 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1555 static PyTypeObject PLy_PlanType = {
1556 PyObject_HEAD_INIT(NULL)
1558 "PLyPlan", /* tp_name */
1559 sizeof(PLyPlanObject), /* tp_size */
1560 0, /* tp_itemsize */
1565 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1567 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1571 0, /* tp_as_number */
1572 0, /* tp_as_sequence */
1573 0, /* tp_as_mapping */
1577 0, /* tp_getattro */
1578 0, /* tp_setattro */
1579 0, /* tp_as_buffer */
1581 PLy_plan_doc, /* tp_doc */
1584 static PyMethodDef PLy_plan_methods[] = {
1585 {"status", (PyCFunction) PLy_plan_status, METH_VARARGS, NULL},
1586 {NULL, NULL, 0, NULL}
1590 static PySequenceMethods PLy_result_as_sequence = {
1591 (inquiry) PLy_result_length, /* sq_length */
1592 (binaryfunc) 0, /* sq_concat */
1593 (intargfunc) 0, /* sq_repeat */
1594 (intargfunc) PLy_result_item, /* sq_item */
1595 (intintargfunc) PLy_result_slice, /* sq_slice */
1596 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1597 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1600 static PyTypeObject PLy_ResultType = {
1601 PyObject_HEAD_INIT(NULL)
1603 "PLyResult", /* tp_name */
1604 sizeof(PLyResultObject), /* tp_size */
1605 0, /* tp_itemsize */
1610 (destructor) PLy_result_dealloc, /* tp_dealloc */
1612 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1616 0, /* tp_as_number */
1617 &PLy_result_as_sequence, /* tp_as_sequence */
1618 0, /* tp_as_mapping */
1622 0, /* tp_getattro */
1623 0, /* tp_setattro */
1624 0, /* tp_as_buffer */
1626 PLy_result_doc, /* tp_doc */
1630 /* Appear to be unused */
1631 static PyMethodDef PLy_result_methods[] = {
1632 {"fetch", (PyCFunction) PLy_result_fetch, METH_VARARGS, NULL,},
1633 {"nrows", (PyCFunction) PLy_result_nrows, METH_VARARGS, NULL},
1634 {"status", (PyCFunction) PLy_result_status, METH_VARARGS, NULL},
1635 {NULL, NULL, 0, NULL}
1639 static PyMethodDef PLy_methods[] = {
1643 {"debug", PLy_debug, METH_VARARGS, NULL},
1644 {"log", PLy_log, METH_VARARGS, NULL},
1645 {"info", PLy_info, METH_VARARGS, NULL},
1646 {"notice", PLy_notice, METH_VARARGS, NULL},
1647 {"warning", PLy_warning, METH_VARARGS, NULL},
1648 {"error", PLy_error, METH_VARARGS, NULL},
1649 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1652 * create a stored plan
1654 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1657 * execute a plan or query
1659 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1661 {NULL, NULL, 0, NULL}
1665 /* plan object methods
1672 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1680 return (PyObject *) ob;
1685 PLy_plan_dealloc(PyObject * arg)
1687 PLyPlanObject *ob = (PLyPlanObject *) arg;
1690 SPI_freeplan(ob->plan);
1692 PLy_free(ob->types);
1697 for (i = 0; i < ob->nargs; i++)
1698 PLy_typeinfo_dealloc(&ob->args[i]);
1707 PLy_plan_getattr(PyObject * self, char *name)
1709 return Py_FindMethod(PLy_plan_methods, self, name);
1713 PLy_plan_status(PyObject * self, PyObject * args)
1715 if (PyArg_ParseTuple(args, ""))
1719 /* return PyInt_FromLong(self->status); */
1721 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1727 /* result object methods
1731 PLy_result_new(void)
1733 PLyResultObject *ob;
1735 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1738 /* ob->tuples = NULL; */
1741 ob->status = Py_None;
1742 ob->nrows = PyInt_FromLong(-1);
1743 ob->rows = PyList_New(0);
1745 return (PyObject *) ob;
1749 PLy_result_dealloc(PyObject * arg)
1751 PLyResultObject *ob = (PLyResultObject *) arg;
1753 Py_XDECREF(ob->nrows);
1754 Py_XDECREF(ob->rows);
1755 Py_XDECREF(ob->status);
1761 PLy_result_getattr(PyObject * self, char *attr)
1767 /* Appear to be unused */
1769 PLy_result_fetch(PyObject * self, PyObject * args)
1775 PLy_result_nrows(PyObject * self, PyObject * args)
1777 PLyResultObject *ob = (PLyResultObject *) self;
1779 Py_INCREF(ob->nrows);
1784 PLy_result_status(PyObject * self, PyObject * args)
1786 PLyResultObject *ob = (PLyResultObject *) self;
1788 Py_INCREF(ob->status);
1794 PLy_result_length(PyObject * arg)
1796 PLyResultObject *ob = (PLyResultObject *) arg;
1798 return PyList_Size(ob->rows);
1802 PLy_result_item(PyObject * arg, int idx)
1805 PLyResultObject *ob = (PLyResultObject *) arg;
1807 rv = PyList_GetItem(ob->rows, idx);
1814 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1817 PLyResultObject *ob = (PLyResultObject *) arg;
1820 rv = PyList_SetItem(ob->rows, idx, item);
1825 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1828 PLyResultObject *ob = (PLyResultObject *) arg;
1830 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1838 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1841 PLyResultObject *ob = (PLyResultObject *) arg;
1843 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1850 PLy_spi_prepare(PyObject * self, PyObject * args)
1852 PLyPlanObject *plan;
1853 PyObject *list = NULL;
1854 PyObject *volatile optr = NULL;
1857 MemoryContext oldcontext;
1859 /* Can't execute more if we have an unhandled error */
1860 if (PLy_error_in_progress)
1862 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1866 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1868 PyErr_SetString(PLy_exc_spi_error,
1869 "Invalid arguments for plpy.prepare()");
1873 if ((list) && (!PySequence_Check(list)))
1875 PyErr_SetString(PLy_exc_spi_error,
1876 "Second argument in plpy.prepare() must be a sequence");
1880 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1883 oldcontext = CurrentMemoryContext;
1891 nargs = PySequence_Length(list);
1894 plan->nargs = nargs;
1895 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1896 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1897 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1900 * the other loop might throw an exception, if PLyTypeInfo
1901 * member isn't properly initialized the Py_DECREF(plan)
1904 for (i = 0; i < nargs; i++)
1906 PLy_typeinfo_init(&plan->args[i]);
1907 plan->values[i] = (Datum) NULL;
1910 for (i = 0; i < nargs; i++)
1914 Form_pg_type typeStruct;
1916 optr = PySequence_GetItem(list, i);
1917 if (!PyString_Check(optr))
1918 elog(ERROR, "Type names must be strings.");
1919 sptr = PyString_AsString(optr);
1922 * XXX should extend this to allow qualified type
1925 typeTup = typenameType(makeTypeName(sptr));
1927 optr = NULL; /* this is important */
1929 plan->types[i] = HeapTupleGetOid(typeTup);
1930 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1931 if (typeStruct->typtype != 'c')
1932 PLy_output_datum_func(&plan->args[i], typeTup);
1934 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
1935 ReleaseSysCache(typeTup);
1940 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1941 if (plan->plan == NULL)
1942 elog(ERROR, "SPI_prepare failed: %s",
1943 SPI_result_code_string(SPI_result));
1945 /* transfer plan from procCxt to topCxt */
1946 tmpplan = plan->plan;
1947 plan->plan = SPI_saveplan(tmpplan);
1948 SPI_freeplan(tmpplan);
1949 if (plan->plan == NULL)
1950 elog(ERROR, "SPI_saveplan failed: %s",
1951 SPI_result_code_string(SPI_result));
1955 MemoryContextSwitchTo(oldcontext);
1956 PLy_error_in_progress = CopyErrorData();
1960 if (!PyErr_Occurred())
1961 PyErr_SetString(PLy_exc_spi_error,
1962 "Unknown error in PLy_spi_prepare");
1963 /* XXX this oughta be replaced with errcontext mechanism */
1964 PLy_elog(WARNING, "in function %s:",
1965 PLy_procedure_name(PLy_curr_procedure));
1970 return (PyObject *) plan;
1973 /* execute(query="select * from foo", limit=5)
1974 * execute(plan=plan, values=(foo, bar), limit=5)
1977 PLy_spi_execute(PyObject * self, PyObject * args)
1981 PyObject *list = NULL;
1984 /* Can't execute more if we have an unhandled error */
1985 if (PLy_error_in_progress)
1987 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1991 if (PyArg_ParseTuple(args, "s|i", &query, &limit))
1992 return PLy_spi_execute_query(query, limit);
1996 if ((PyArg_ParseTuple(args, "O|Oi", &plan, &list, &limit)) &&
1997 (is_PLyPlanObject(plan)))
1998 return PLy_spi_execute_plan(plan, list, limit);
2000 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2005 PLy_spi_execute_plan(PyObject * ob, PyObject * list, int limit)
2010 PLyPlanObject *plan;
2012 MemoryContext oldcontext;
2016 if ((!PySequence_Check(list)) || (PyString_Check(list)))
2018 char *msg = "plpy.execute() takes a sequence as its second argument";
2020 PyErr_SetString(PLy_exc_spi_error, msg);
2023 nargs = PySequence_Length(list);
2028 plan = (PLyPlanObject *) ob;
2030 if (nargs != plan->nargs)
2034 PyObject *so = PyObject_Str(list);
2036 sv = PyString_AsString(so);
2037 PLy_exception_set(PLy_exc_spi_error,
2038 "Expected sequence of %d arguments, got %d. %s",
2039 plan->nargs, nargs, sv);
2045 oldcontext = CurrentMemoryContext;
2048 nulls = palloc(nargs * sizeof(char));
2050 for (i = 0; i < nargs; i++)
2056 elem = PySequence_GetItem(list, i);
2057 if (elem != Py_None)
2059 so = PyObject_Str(elem);
2060 sv = PyString_AsString(so);
2063 * FIXME -- if this elogs, we have Python reference leak
2066 FunctionCall3(&(plan->args[i].out.d.typfunc),
2067 CStringGetDatum(sv),
2068 ObjectIdGetDatum(plan->args[i].out.d.typioparam),
2079 plan->values[i] = (Datum) 0;
2084 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2085 PLy_curr_procedure->fn_readonly, limit);
2091 MemoryContextSwitchTo(oldcontext);
2092 PLy_error_in_progress = CopyErrorData();
2096 * cleanup plan->values array
2098 for (i = 0; i < nargs; i++)
2100 if (!plan->args[i].out.d.typbyval &&
2101 (plan->values[i] != (Datum) NULL))
2103 pfree(DatumGetPointer(plan->values[i]));
2104 plan->values[i] = (Datum) NULL;
2108 if (!PyErr_Occurred())
2109 PyErr_SetString(PLy_exc_error,
2110 "Unknown error in PLy_spi_execute_plan");
2111 /* XXX this oughta be replaced with errcontext mechanism */
2112 PLy_elog(WARNING, "in function %s:",
2113 PLy_procedure_name(PLy_curr_procedure));
2118 for (i = 0; i < nargs; i++)
2120 if (!plan->args[i].out.d.typbyval &&
2121 (plan->values[i] != (Datum) NULL))
2123 pfree(DatumGetPointer(plan->values[i]));
2124 plan->values[i] = (Datum) NULL;
2130 PLy_exception_set(PLy_exc_spi_error,
2131 "SPI_execute_plan failed: %s",
2132 SPI_result_code_string(rv));
2136 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2140 PLy_spi_execute_query(char *query, int limit)
2143 MemoryContext oldcontext;
2145 oldcontext = CurrentMemoryContext;
2148 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2152 MemoryContextSwitchTo(oldcontext);
2153 PLy_error_in_progress = CopyErrorData();
2155 if (!PyErr_Occurred())
2156 PyErr_SetString(PLy_exc_spi_error,
2157 "Unknown error in PLy_spi_execute_query");
2158 /* XXX this oughta be replaced with errcontext mechanism */
2159 PLy_elog(WARNING, "in function %s:",
2160 PLy_procedure_name(PLy_curr_procedure));
2167 PLy_exception_set(PLy_exc_spi_error,
2168 "SPI_execute failed: %s",
2169 SPI_result_code_string(rv));
2173 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2177 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2179 PLyResultObject *result;
2180 MemoryContext oldcontext;
2182 result = (PLyResultObject *) PLy_result_new();
2183 Py_DECREF(result->status);
2184 result->status = PyInt_FromLong(status);
2186 if (status == SPI_OK_UTILITY)
2188 Py_DECREF(result->nrows);
2189 result->nrows = PyInt_FromLong(0);
2191 else if (status != SPI_OK_SELECT)
2193 Py_DECREF(result->nrows);
2194 result->nrows = PyInt_FromLong(rows);
2201 PLy_typeinfo_init(&args);
2202 Py_DECREF(result->nrows);
2203 result->nrows = PyInt_FromLong(rows);
2205 oldcontext = CurrentMemoryContext;
2210 Py_DECREF(result->rows);
2211 result->rows = PyList_New(rows);
2213 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2214 for (i = 0; i < rows; i++)
2216 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2219 PyList_SetItem(result->rows, i, row);
2221 PLy_typeinfo_dealloc(&args);
2223 SPI_freetuptable(tuptable);
2228 MemoryContextSwitchTo(oldcontext);
2229 PLy_error_in_progress = CopyErrorData();
2231 if (!PyErr_Occurred())
2232 PyErr_SetString(PLy_exc_error,
2233 "Unknown error in PLy_spi_execute_fetch_result");
2235 PLy_typeinfo_dealloc(&args);
2241 return (PyObject *) result;
2246 * language handler and interpreter initialization
2250 * plpython_init() - Initialize everything that can be
2251 * safely initialized during postmaster
2254 * DO NOT make this static --- it has to be callable by preload
2259 static volatile int init_active = 0;
2261 /* Do initialization only once */
2262 if (!PLy_first_call)
2266 elog(FATAL, "initialization of language module failed");
2272 if (PyErr_Occurred())
2273 PLy_elog(FATAL, "untrapped error in initialization");
2274 PLy_procedure_cache = PyDict_New();
2275 if (PLy_procedure_cache == NULL)
2276 PLy_elog(ERROR, "could not create procedure cache");
2284 /* Execute postmaster-startup safe initialization */
2289 * Any other initialization that must be done each time a new backend
2290 * starts -- currently none
2296 PLy_init_interp(void)
2300 mainmod = PyImport_AddModule("__main__");
2301 if ((mainmod == NULL) || (PyErr_Occurred()))
2302 PLy_elog(ERROR, "could not import \"__main__\" module.");
2304 PLy_interp_globals = PyModule_GetDict(mainmod);
2305 PLy_interp_safe_globals = PyDict_New();
2306 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2308 if ((PLy_interp_globals == NULL) || (PyErr_Occurred()))
2309 PLy_elog(ERROR, "could not initialize globals");
2322 * initialize plpy module
2324 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2325 plpy = Py_InitModule("plpy", PLy_methods);
2326 plpy_dict = PyModule_GetDict(plpy);
2328 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2330 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2331 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2332 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2333 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2334 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2335 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2338 * initialize main module, and add plpy
2340 main_mod = PyImport_AddModule("__main__");
2341 main_dict = PyModule_GetDict(main_mod);
2342 plpy_mod = PyImport_AddModule("plpy");
2343 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2344 if (PyErr_Occurred())
2345 elog(ERROR, "could not init plpy");
2348 /* the python interface to the elog function
2349 * don't confuse these with PLy_elog
2351 static PyObject *PLy_output(int, PyObject *, PyObject *);
2354 PLy_debug(PyObject * self, PyObject * args)
2356 return PLy_output(DEBUG2, self, args);
2360 PLy_log(PyObject * self, PyObject * args)
2362 return PLy_output(LOG, self, args);
2366 PLy_info(PyObject * self, PyObject * args)
2368 return PLy_output(INFO, self, args);
2372 PLy_notice(PyObject * self, PyObject * args)
2374 return PLy_output(NOTICE, self, args);
2378 PLy_warning(PyObject * self, PyObject * args)
2380 return PLy_output(WARNING, self, args);
2384 PLy_error(PyObject * self, PyObject * args)
2386 return PLy_output(ERROR, self, args);
2390 PLy_fatal(PyObject * self, PyObject * args)
2392 return PLy_output(FATAL, self, args);
2397 PLy_output(volatile int level, PyObject * self, PyObject * args)
2401 MemoryContext oldcontext;
2403 so = PyObject_Str(args);
2404 if ((so == NULL) || ((sv = PyString_AsString(so)) == NULL))
2407 sv = "Unable to parse error message in `plpy.elog'";
2410 oldcontext = CurrentMemoryContext;
2413 elog(level, "%s", sv);
2417 MemoryContextSwitchTo(oldcontext);
2418 PLy_error_in_progress = CopyErrorData();
2423 * returning NULL here causes the python interpreter to bail. when
2424 * control passes back to PLy_procedure_call, we check for PG
2425 * exceptions and re-throw the error.
2427 PyErr_SetString(PLy_exc_error, sv);
2435 * return a legal object so the interpreter will continue on its merry
2444 * Get the last procedure name called by the backend ( the innermost,
2445 * If a plpython procedure call calls the backend and the backend calls
2446 * another plpython procedure )
2448 * NB: this returns SQL name, not the internal Python procedure name
2452 PLy_procedure_name(PLyProcedure * proc)
2455 return "<unknown procedure>";
2456 return proc->proname;
2459 /* output a python traceback/exception via the postgresql elog
2460 * function. not pretty.
2463 PLy_exception_set(PyObject * exc, const char *fmt,...)
2469 vsnprintf(buf, sizeof(buf), fmt, ap);
2472 PyErr_SetString(exc, buf);
2475 /* Emit a PG error or notice, together with any available info about the
2476 * current Python error. This should be used to propagate Python errors
2480 PLy_elog(int elevel, const char *fmt,...)
2487 xmsg = PLy_traceback(&xlevel);
2490 emsg = PLy_vprintf(fmt, ap);
2496 (errmsg("plpython: %s", emsg),
2497 (xmsg) ? errdetail("%s", xmsg) : 0));
2514 PLy_traceback(int *xlevel)
2526 * get the current exception
2528 PyErr_Fetch(&e, &v, &tb);
2531 * oops, no exception, return
2539 PyErr_NormalizeException(&e, &v, &tb);
2541 eob = PyObject_Str(e);
2542 if ((v) && ((vob = PyObject_Str(v)) != NULL))
2543 vstr = PyString_AsString(vob);
2547 estr = PyString_AsString(eob);
2548 xstr = PLy_printf("%s: %s", estr, vstr);
2554 * intuit an appropriate error level for based on the exception type
2556 if ((PLy_exc_error) && (PyErr_GivenExceptionMatches(e, PLy_exc_error)))
2558 else if ((PLy_exc_fatal) && (PyErr_GivenExceptionMatches(e, PLy_exc_fatal)))
2567 PLy_printf(const char *fmt,...)
2573 emsg = PLy_vprintf(fmt, ap);
2579 PLy_vprintf(const char *fmt, va_list ap)
2586 blen = strlen(fmt) * 2;
2589 buf = PLy_malloc(blen * sizeof(char));
2593 bchar = vsnprintf(buf, blen, fmt, ap);
2594 if ((bchar > 0) && (bchar < blen))
2602 buf = PLy_realloc(buf, blen);
2608 /* python module code
2612 /* some dumb utility functions
2616 PLy_malloc(size_t bytes)
2618 void *ptr = malloc(bytes);
2622 (errcode(ERRCODE_OUT_OF_MEMORY),
2623 errmsg("out of memory")));
2628 PLy_realloc(void *optr, size_t bytes)
2630 void *nptr = realloc(optr, bytes);
2634 (errcode(ERRCODE_OUT_OF_MEMORY),
2635 errmsg("out of memory")));