1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * This software is copyright by Andrew Bosma
5 * but is really shamelessly cribbed from pltcl.c by Jan Wieck, 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.74 2006/03/01 06:30:32 neilc 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/memutils.h"
56 #include "utils/syscache.h"
57 #include "utils/typcache.h"
62 /* convert Postgresql Datum or tuple into a PyObject.
63 * input to Python. Tuples are converted to dictionary
67 typedef PyObject *(*PLyDatumToObFunc) (const char *);
69 typedef struct PLyDatumToOb
71 PLyDatumToObFunc func;
77 typedef struct PLyTupleToOb
83 typedef union PLyTypeInput
89 /* convert PyObject to a Postgresql Datum or tuple.
92 typedef struct PLyObToDatum
94 FmgrInfo typfunc; /* The type's input function */
95 Oid typoid; /* The OID of the type */
100 typedef struct PLyObToTuple
106 typedef union PLyTypeOutput
112 /* all we need to move Postgresql data to Python objects,
115 typedef struct PLyTypeInfo
122 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
123 * 1 rowtype 2 rowtype, but I/O functions not set up yet
128 /* cached procedure data */
129 typedef struct PLyProcedure
131 char *proname; /* SQL name of procedure */
132 char *pyname; /* Python name of procedure */
133 TransactionId fn_xmin;
136 PLyTypeInfo result; /* also used to store info for trigger tuple
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 scope */
143 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 */
171 /* Two exported functions: first is the magic telling Postgresql
172 * what function call interface it implements. Second allows
173 * preinitialization of the interpreter during postmaster startup.
175 Datum plpython_call_handler(PG_FUNCTION_ARGS);
176 void plpython_init(void);
178 PG_FUNCTION_INFO_V1(plpython_call_handler);
180 /* most of the remaining of the declarations, all static */
182 /* these should only be called once at the first call
183 * of plpython_call_handler. initialize the python interpreter
186 static void PLy_init_all(void);
187 static void PLy_init_interp(void);
188 static void PLy_init_plpy(void);
190 /* call PyErr_SetString with a vprint interface */
192 PLy_exception_set(PyObject *, const char *,...)
193 __attribute__((format(printf, 2, 3)));
195 /* Get the innermost python procedure called from the backend */
196 static char *PLy_procedure_name(PLyProcedure *);
198 /* some utility functions */
199 static void PLy_elog(int, const char *,...);
200 static char *PLy_traceback(int *);
201 static char *PLy_vprintf(const char *fmt, va_list ap);
202 static char *PLy_printf(const char *fmt,...);
204 static void *PLy_malloc(size_t);
205 static void *PLy_realloc(void *, size_t);
206 static char *PLy_strdup(const char *);
207 static void PLy_free(void *);
209 /* sub handlers for functions and triggers */
210 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
211 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
213 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
214 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
216 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
217 TriggerData *, HeapTuple);
219 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
221 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
224 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
226 HeapTuple procTup, char *key);
228 static void PLy_procedure_compile(PLyProcedure *, const char *);
229 static char *PLy_procedure_munge_source(const char *, const char *);
230 static void PLy_procedure_delete(PLyProcedure *);
232 static void PLy_typeinfo_init(PLyTypeInfo *);
233 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
234 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
235 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
236 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
237 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
238 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
239 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
241 /* conversion functions */
242 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
243 static PyObject *PLyBool_FromString(const char *);
244 static PyObject *PLyFloat_FromString(const char *);
245 static PyObject *PLyInt_FromString(const char *);
246 static PyObject *PLyLong_FromString(const char *);
247 static PyObject *PLyString_FromString(const char *);
251 static bool PLy_first_call = true;
254 * Currently active plpython function
256 static PLyProcedure *PLy_curr_procedure = NULL;
259 * When a callback from Python into PG incurs an error, we temporarily store
260 * the error information here, and return NULL to the Python interpreter.
261 * Any further callback attempts immediately fail, and when the Python
262 * interpreter returns to the calling function, we re-throw the error (even if
263 * Python thinks it trapped the error and doesn't return NULL). Eventually
264 * this ought to be improved to let Python code really truly trap the error,
265 * but that's more of a change from the pre-8.0 semantics than I have time for
266 * now --- it will only be possible if the callback query is executed inside a
269 static ErrorData *PLy_error_in_progress = NULL;
271 static PyObject *PLy_interp_globals = NULL;
272 static PyObject *PLy_interp_safe_globals = NULL;
273 static PyObject *PLy_procedure_cache = NULL;
275 /* Python exceptions */
276 static PyObject *PLy_exc_error = NULL;
277 static PyObject *PLy_exc_fatal = NULL;
278 static PyObject *PLy_exc_spi_error = NULL;
280 /* some globals for the python module */
281 static char PLy_plan_doc[] = {
282 "Store a PostgreSQL plan"
285 static char PLy_result_doc[] = {
286 "Results of a PostgreSQL query"
291 * the function definitions
295 * This routine is a crock, and so is everyplace that calls it. The problem
296 * is that the cached form of plpython functions/queries is allocated permanently
297 * (mostly via malloc()) and never released until backend exit. Subsidiary
298 * data structures such as fmgr info records therefore must live forever
299 * as well. A better implementation would store all this stuff in a per-
300 * function memory context that could be reclaimed at need. In the meantime,
301 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
302 * it might allocate, and whatever the eventual function might allocate using
303 * fn_mcxt, will live forever too.
306 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
308 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
312 plpython_call_handler(PG_FUNCTION_ARGS)
315 PLyProcedure *save_curr_proc;
316 PLyProcedure *volatile proc = NULL;
320 if (SPI_connect() != SPI_OK_CONNECT)
321 elog(ERROR, "could not connect to SPI manager");
323 save_curr_proc = PLy_curr_procedure;
327 if (CALLED_AS_TRIGGER(fcinfo))
329 TriggerData *tdata = (TriggerData *) fcinfo->context;
332 proc = PLy_procedure_get(fcinfo,
333 RelationGetRelid(tdata->tg_relation));
334 PLy_curr_procedure = proc;
335 trv = PLy_trigger_handler(fcinfo, proc);
336 retval = PointerGetDatum(trv);
340 proc = PLy_procedure_get(fcinfo, InvalidOid);
341 PLy_curr_procedure = proc;
342 retval = PLy_function_handler(fcinfo, proc);
347 PLy_curr_procedure = save_curr_proc;
350 /* note: Py_DECREF needs braces around it, as of 2003/08 */
358 PLy_curr_procedure = save_curr_proc;
365 /* trigger and function sub handlers
367 * the python function is expected to return Py_None if the tuple is
368 * acceptable and unmodified. Otherwise it should return a PyString
369 * object who's value is SKIP, or MODIFY. SKIP means don't perform
370 * this action. MODIFY means the tuple has been modified, so update
371 * tuple and perform action. SKIP and MODIFY assume the trigger fires
372 * BEFORE the event and is ROW level. postgres expects the function
373 * to take no arguments and return an argument of type trigger.
376 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
379 PyObject *volatile plargs = NULL;
380 PyObject *volatile plrv = NULL;
384 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
385 plrv = PLy_procedure_call(proc, "TD", plargs);
387 Assert(plrv != NULL);
388 Assert(!PLy_error_in_progress);
391 * Disconnect from SPI manager
393 if (SPI_finish() != SPI_OK_FINISH)
394 elog(ERROR, "SPI_finish failed");
397 * return of None means we're happy with the tuple
403 if (!PyString_Check(plrv))
405 (errcode(ERRCODE_DATA_EXCEPTION),
406 errmsg("unexpected return value from trigger procedure"),
407 errdetail("Expected None or a String.")));
409 srv = PyString_AsString(plrv);
410 if (pg_strcasecmp(srv, "SKIP") == 0)
412 else if (pg_strcasecmp(srv, "MODIFY") == 0)
414 TriggerData *tdata = (TriggerData *) fcinfo->context;
416 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
417 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
418 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
420 elog(WARNING, "ignoring modified tuple in DELETE trigger");
422 else if (pg_strcasecmp(srv, "OK") != 0)
425 * accept "OK" as an alternative to None; otherwise,
429 (errcode(ERRCODE_DATA_EXCEPTION),
430 errmsg("unexpected return value from trigger procedure"),
431 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
451 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
454 PyObject *volatile plntup;
455 PyObject *volatile plkeys;
456 PyObject *volatile platt;
457 PyObject *volatile plval;
458 PyObject *volatile plstr;
464 int *volatile modattrs;
465 Datum *volatile modvalues;
466 char *volatile modnulls;
469 plntup = plkeys = platt = plval = plstr = NULL;
476 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
477 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
478 if (!PyDict_Check(plntup))
479 elog(ERROR, "TD[\"new\"] is not a dictionary object");
482 plkeys = PyDict_Keys(plntup);
483 natts = PyList_Size(plkeys);
485 modattrs = (int *) palloc(natts * sizeof(int));
486 modvalues = (Datum *) palloc(natts * sizeof(Datum));
487 modnulls = (char *) palloc(natts * sizeof(char));
489 tupdesc = tdata->tg_relation->rd_att;
491 for (i = 0; i < natts; i++)
495 platt = PyList_GetItem(plkeys, i);
496 if (!PyString_Check(platt))
497 elog(ERROR, "attribute name is not a string");
498 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
499 if (attn == SPI_ERROR_NOATTRIBUTE)
500 elog(ERROR, "invalid attribute \"%s\" in tuple",
501 PyString_AsString(platt));
504 plval = PyDict_GetItem(plntup, platt);
506 elog(FATAL, "python interpreter is probably corrupted");
512 if (plval != Py_None && !tupdesc->attrs[atti]->attisdropped)
514 plstr = PyObject_Str(plval);
516 PLy_elog(ERROR, "function \"%s\" could not modify tuple", proc->proname);
517 src = PyString_AsString(plstr);
519 modvalues[i] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
520 CStringGetDatum(src),
521 ObjectIdGetDatum(proc->result.out.r.atts[atti].typioparam),
522 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
530 modvalues[i] = PointerGetDatum(NULL);
538 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
539 modattrs, modvalues, modnulls);
541 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
572 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
574 TriggerData *tdata = (TriggerData *) fcinfo->context;
583 PyObject *volatile pltdata = NULL;
588 pltdata = PyDict_New();
590 PLy_elog(ERROR, "could not build arguments for trigger procedure");
592 pltname = PyString_FromString(tdata->tg_trigger->tgname);
593 PyDict_SetItemString(pltdata, "name", pltname);
596 stroid = DatumGetCString(DirectFunctionCall1(oidout,
597 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
598 pltrelid = PyString_FromString(stroid);
599 PyDict_SetItemString(pltdata, "relid", pltrelid);
603 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
604 pltwhen = PyString_FromString("BEFORE");
605 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
606 pltwhen = PyString_FromString("AFTER");
609 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
610 pltwhen = NULL; /* keep compiler quiet */
612 PyDict_SetItemString(pltdata, "when", pltwhen);
615 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
617 pltlevel = PyString_FromString("ROW");
618 PyDict_SetItemString(pltdata, "level", pltlevel);
621 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
623 pltevent = PyString_FromString("INSERT");
625 PyDict_SetItemString(pltdata, "old", Py_None);
626 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
627 tdata->tg_relation->rd_att);
628 PyDict_SetItemString(pltdata, "new", pytnew);
630 *rv = tdata->tg_trigtuple;
632 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
634 pltevent = PyString_FromString("DELETE");
636 PyDict_SetItemString(pltdata, "new", Py_None);
637 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
638 tdata->tg_relation->rd_att);
639 PyDict_SetItemString(pltdata, "old", pytold);
641 *rv = tdata->tg_trigtuple;
643 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
645 pltevent = PyString_FromString("UPDATE");
647 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
648 tdata->tg_relation->rd_att);
649 PyDict_SetItemString(pltdata, "new", pytnew);
651 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
652 tdata->tg_relation->rd_att);
653 PyDict_SetItemString(pltdata, "old", pytold);
655 *rv = tdata->tg_newtuple;
659 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
660 pltevent = NULL; /* keep compiler quiet */
663 PyDict_SetItemString(pltdata, "event", pltevent);
666 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
668 pltlevel = PyString_FromString("STATEMENT");
669 PyDict_SetItemString(pltdata, "level", pltlevel);
672 PyDict_SetItemString(pltdata, "old", Py_None);
673 PyDict_SetItemString(pltdata, "new", Py_None);
676 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
677 pltevent = PyString_FromString("INSERT");
678 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
679 pltevent = PyString_FromString("DELETE");
680 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
681 pltevent = PyString_FromString("UPDATE");
684 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
685 pltevent = NULL; /* keep compiler quiet */
688 PyDict_SetItemString(pltdata, "event", pltevent);
692 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
694 if (tdata->tg_trigger->tgnargs)
702 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
703 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
705 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
708 * stolen, don't Py_DECREF
710 PyList_SetItem(pltargs, i, pltarg);
718 PyDict_SetItemString(pltdata, "args", pltargs);
733 /* function handler and friends */
735 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
738 PyObject *volatile plargs = NULL;
739 PyObject *volatile plrv = NULL;
740 PyObject *volatile plrv_so = NULL;
745 plargs = PLy_function_build_args(fcinfo, proc);
746 plrv = PLy_procedure_call(proc, "args", plargs);
748 Assert(plrv != NULL);
749 Assert(!PLy_error_in_progress);
752 * Disconnect from SPI manager and then create the return values datum
753 * (if the input function does a palloc for it this must not be
754 * allocated in the SPI memory context because SPI_finish would free
757 if (SPI_finish() != SPI_OK_FINISH)
758 elog(ERROR, "SPI_finish failed");
761 * If the function is declared to return void, the Python
762 * return value must be None. For void-returning functions, we
763 * also treat a None return value as a special "void datum"
764 * rather than NULL (as is the case for non-void-returning
767 if (proc->result.out.d.typoid == VOIDOID)
771 (errcode(ERRCODE_DATATYPE_MISMATCH),
772 errmsg("invalid return value from plpython function"),
773 errdetail("Functions returning type \"void\" must return None.")));
775 fcinfo->isnull = false;
778 else if (plrv == Py_None)
780 fcinfo->isnull = true;
781 rv = PointerGetDatum(NULL);
785 fcinfo->isnull = false;
786 plrv_so = PyObject_Str(plrv);
788 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
789 plrv_sc = PyString_AsString(plrv_so);
790 rv = FunctionCall3(&proc->result.out.d.typfunc,
791 PointerGetDatum(plrv_sc),
792 ObjectIdGetDatum(proc->result.out.d.typioparam),
814 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
818 PyDict_SetItemString(proc->globals, kargs, vargs);
819 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
820 proc->globals, proc->globals);
823 * If there was an error in a PG callback, propagate that no matter what
824 * Python claims about its success.
826 if (PLy_error_in_progress)
828 ErrorData *edata = PLy_error_in_progress;
830 PLy_error_in_progress = NULL;
834 if (rv == NULL || PyErr_Occurred())
837 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
844 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
846 PyObject *volatile arg = NULL;
847 PyObject *volatile args = NULL;
852 args = PyList_New(proc->nargs);
853 for (i = 0; i < proc->nargs; i++)
855 if (proc->args[i].is_rowtype > 0)
857 if (fcinfo->argnull[i])
865 HeapTupleData tmptup;
867 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
868 /* Extract rowtype info and find a tupdesc */
869 tupType = HeapTupleHeaderGetTypeId(td);
870 tupTypmod = HeapTupleHeaderGetTypMod(td);
871 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
873 /* Set up I/O funcs if not done yet */
874 if (proc->args[i].is_rowtype != 1)
875 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
877 /* Build a temporary HeapTuple control structure */
878 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
881 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
886 if (fcinfo->argnull[i])
893 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
895 ObjectIdGetDatum(proc->args[i].in.d.typioparam),
897 ct = DatumGetCString(dt);
898 arg = (proc->args[i].in.d.func) (ct);
910 * FIXME -- error check this
912 PyList_SetItem(args, i, arg);
930 * PLyProcedure functions
933 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
934 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
935 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
938 static PLyProcedure *
939 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
945 PLyProcedure *proc = NULL;
948 fn_oid = fcinfo->flinfo->fn_oid;
949 procTup = SearchSysCache(PROCOID,
950 ObjectIdGetDatum(fn_oid),
952 if (!HeapTupleIsValid(procTup))
953 elog(ERROR, "cache lookup failed for function %u", fn_oid);
955 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
956 if (rv >= sizeof(key) || rv < 0)
957 elog(ERROR, "key too long");
959 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
964 if (!PyCObject_Check(plproc))
965 elog(FATAL, "expected a PyCObject, didn't get one");
967 proc = PyCObject_AsVoidPtr(plproc);
968 if (proc->me != plproc)
969 elog(FATAL, "proc->me != plproc");
970 /* did we find an up-to-date cache entry? */
971 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
972 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
980 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
982 ReleaseSysCache(procTup);
987 static PLyProcedure *
988 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
989 HeapTuple procTup, char *key)
991 char procName[NAMEDATALEN + 256];
992 Form_pg_proc procStruct;
993 PLyProcedure *volatile proc;
994 char *volatile procSource = NULL;
1000 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1002 if (OidIsValid(tgreloid))
1003 rv = snprintf(procName, sizeof(procName),
1004 "__plpython_procedure_%s_%u_trigger_%u",
1005 NameStr(procStruct->proname),
1006 fcinfo->flinfo->fn_oid,
1009 rv = snprintf(procName, sizeof(procName),
1010 "__plpython_procedure_%s_%u",
1011 NameStr(procStruct->proname),
1012 fcinfo->flinfo->fn_oid);
1013 if (rv >= sizeof(procName) || rv < 0)
1014 elog(ERROR, "procedure name would overrun buffer");
1016 proc = PLy_malloc(sizeof(PLyProcedure));
1017 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1018 proc->pyname = PLy_strdup(procName);
1019 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1020 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1021 /* Remember if function is STABLE/IMMUTABLE */
1023 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1024 PLy_typeinfo_init(&proc->result);
1025 for (i = 0; i < FUNC_MAX_ARGS; i++)
1026 PLy_typeinfo_init(&proc->args[i]);
1028 proc->code = proc->statics = NULL;
1029 proc->globals = proc->me = NULL;
1034 * get information required for output conversion of the return value,
1035 * but only if this isn't a trigger.
1037 if (!CALLED_AS_TRIGGER(fcinfo))
1039 HeapTuple rvTypeTup;
1040 Form_pg_type rvTypeStruct;
1042 rvTypeTup = SearchSysCache(TYPEOID,
1043 ObjectIdGetDatum(procStruct->prorettype),
1045 if (!HeapTupleIsValid(rvTypeTup))
1046 elog(ERROR, "cache lookup failed for type %u",
1047 procStruct->prorettype);
1048 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1050 /* Disallow pseudotype result, except for void */
1051 if (rvTypeStruct->typtype == 'p' &&
1052 procStruct->prorettype != VOIDOID)
1054 if (procStruct->prorettype == TRIGGEROID)
1056 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1057 errmsg("trigger functions may only be called as triggers")));
1060 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1061 errmsg("plpython functions cannot return type %s",
1062 format_type_be(procStruct->prorettype))));
1065 if (rvTypeStruct->typtype == 'c')
1067 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1068 errmsg("plpython functions cannot return tuples yet")));
1070 PLy_output_datum_func(&proc->result, rvTypeTup);
1072 ReleaseSysCache(rvTypeTup);
1077 * input/output conversion for trigger tuples. use the result
1078 * TypeInfo variable to store the tuple conversion info.
1080 TriggerData *tdata = (TriggerData *) fcinfo->context;
1082 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1083 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1087 * now get information required for input conversion of the procedure's
1090 proc->nargs = fcinfo->nargs;
1091 for (i = 0; i < fcinfo->nargs; i++)
1093 HeapTuple argTypeTup;
1094 Form_pg_type argTypeStruct;
1096 argTypeTup = SearchSysCache(TYPEOID,
1097 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1099 if (!HeapTupleIsValid(argTypeTup))
1100 elog(ERROR, "cache lookup failed for type %u",
1101 procStruct->proargtypes.values[i]);
1102 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1104 /* Disallow pseudotype argument */
1105 if (argTypeStruct->typtype == 'p')
1107 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1108 errmsg("plpython functions cannot take type %s",
1109 format_type_be(procStruct->proargtypes.values[i]))));
1111 if (argTypeStruct->typtype != 'c')
1112 PLy_input_datum_func(&(proc->args[i]),
1113 procStruct->proargtypes.values[i],
1116 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1118 ReleaseSysCache(argTypeTup);
1123 * get the text of the function.
1125 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1126 Anum_pg_proc_prosrc, &isnull);
1128 elog(ERROR, "null prosrc");
1129 procSource = DatumGetCString(DirectFunctionCall1(textout,
1132 PLy_procedure_compile(proc, procSource);
1136 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1137 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1141 PLy_procedure_delete(proc);
1153 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1155 PyObject *crv = NULL;
1158 proc->globals = PyDict_Copy(PLy_interp_globals);
1161 * SD is private preserved data between calls. GD is global data
1162 * shared by all functions
1164 proc->statics = PyDict_New();
1165 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1168 * insert the function code into the interpreter
1170 msrc = PLy_procedure_munge_source(proc->pyname, src);
1171 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1174 if (crv != NULL && (!PyErr_Occurred()))
1177 char call[NAMEDATALEN + 256];
1182 * compile a call to the function
1184 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1185 if (clen < 0 || clen >= sizeof(call))
1186 elog(ERROR, "string would overflow buffer");
1187 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1188 if (proc->code != NULL && (!PyErr_Occurred()))
1194 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1198 PLy_procedure_munge_source(const char *name, const char *src)
1207 * room for function source and the def statement
1209 mlen = (strlen(src) * 2) + strlen(name) + 16;
1211 mrc = PLy_malloc(mlen);
1212 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1213 Assert(plen >= 0 && plen < mlen);
1220 if (*sp == '\r' && *(sp + 1) == '\n')
1223 if (*sp == '\n' || *sp == '\r')
1236 if (mp > (mrc + mlen))
1237 elog(FATAL, "buffer overrun in PLy_munge_source");
1243 PLy_procedure_delete(PLyProcedure * proc)
1247 Py_XDECREF(proc->code);
1248 Py_XDECREF(proc->statics);
1249 Py_XDECREF(proc->globals);
1250 Py_XDECREF(proc->me);
1252 PLy_free(proc->proname);
1254 PLy_free(proc->pyname);
1255 for (i = 0; i < proc->nargs; i++)
1256 if (proc->args[i].is_rowtype == 1)
1258 if (proc->args[i].in.r.atts)
1259 PLy_free(proc->args[i].in.r.atts);
1260 if (proc->args[i].out.r.atts)
1261 PLy_free(proc->args[i].out.r.atts);
1265 /* conversion functions. remember output from python is
1266 * input to postgresql, and vis versa.
1269 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1273 if (arg->is_rowtype == 0)
1274 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1276 arg->is_rowtype = 1;
1277 arg->in.r.natts = desc->natts;
1278 arg->in.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1280 for (i = 0; i < desc->natts; i++)
1284 if (desc->attrs[i]->attisdropped)
1287 typeTup = SearchSysCache(TYPEOID,
1288 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1290 if (!HeapTupleIsValid(typeTup))
1291 elog(ERROR, "cache lookup failed for type %u",
1292 desc->attrs[i]->atttypid);
1294 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1295 desc->attrs[i]->atttypid,
1298 ReleaseSysCache(typeTup);
1303 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1307 if (arg->is_rowtype == 0)
1308 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1310 arg->is_rowtype = 1;
1311 arg->out.r.natts = desc->natts;
1312 arg->out.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1314 for (i = 0; i < desc->natts; i++)
1318 if (desc->attrs[i]->attisdropped)
1321 typeTup = SearchSysCache(TYPEOID,
1322 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1324 if (!HeapTupleIsValid(typeTup))
1325 elog(ERROR, "cache lookup failed for type %u",
1326 desc->attrs[i]->atttypid);
1328 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1330 ReleaseSysCache(typeTup);
1335 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1337 if (arg->is_rowtype > 0)
1338 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1339 arg->is_rowtype = 0;
1340 PLy_output_datum_func2(&(arg->out.d), typeTup);
1344 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1346 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1348 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1349 arg->typoid = HeapTupleGetOid(typeTup);
1350 arg->typioparam = getTypeIOParam(typeTup);
1351 arg->typbyval = typeStruct->typbyval;
1355 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1357 if (arg->is_rowtype > 0)
1358 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1359 arg->is_rowtype = 0;
1360 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1364 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1366 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1368 /* Get the type's conversion information */
1369 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1370 arg->typioparam = getTypeIOParam(typeTup);
1371 arg->typbyval = typeStruct->typbyval;
1373 /* Determine which kind of Python object we will convert to */
1377 arg->func = PLyBool_FromString;
1382 arg->func = PLyFloat_FromString;
1386 arg->func = PLyInt_FromString;
1389 arg->func = PLyLong_FromString;
1392 arg->func = PLyString_FromString;
1398 PLy_typeinfo_init(PLyTypeInfo * arg)
1400 arg->is_rowtype = -1;
1401 arg->in.r.natts = arg->out.r.natts = 0;
1402 arg->in.r.atts = NULL;
1403 arg->out.r.atts = NULL;
1407 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1409 if (arg->is_rowtype == 1)
1412 PLy_free(arg->in.r.atts);
1413 if (arg->out.r.atts)
1414 PLy_free(arg->out.r.atts);
1418 /* assumes that a bool is always returned as a 't' or 'f' */
1420 PLyBool_FromString(const char *src)
1423 return PyInt_FromLong(1);
1424 return PyInt_FromLong(0);
1428 PLyFloat_FromString(const char *src)
1434 v = strtod(src, &eptr);
1435 if (*eptr != '\0' || errno)
1437 return PyFloat_FromDouble(v);
1441 PLyInt_FromString(const char *src)
1447 v = strtol(src, &eptr, 0);
1448 if (*eptr != '\0' || errno)
1450 return PyInt_FromLong(v);
1454 PLyLong_FromString(const char *src)
1456 return PyLong_FromString((char *) src, NULL, 0);
1460 PLyString_FromString(const char *src)
1462 return PyString_FromString(src);
1466 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1468 PyObject *volatile dict;
1471 if (info->is_rowtype != 1)
1472 elog(ERROR, "PLyTypeInfo structure describes a datum");
1474 dict = PyDict_New();
1476 PLy_elog(ERROR, "could not create tuple dictionary");
1480 for (i = 0; i < info->in.r.natts; i++)
1489 if (desc->attrs[i]->attisdropped)
1492 key = NameStr(desc->attrs[i]->attname);
1493 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1495 if (is_null || info->in.r.atts[i].func == NULL)
1496 PyDict_SetItemString(dict, key, Py_None);
1499 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1501 ObjectIdGetDatum(info->in.r.atts[i].typioparam),
1502 Int32GetDatum(desc->attrs[i]->atttypmod));
1503 vsrc = DatumGetCString(vdat);
1506 * no exceptions allowed
1508 value = info->in.r.atts[i].func(vsrc);
1510 PyDict_SetItemString(dict, key, value);
1525 /* initialization, some python variables function declared here */
1527 /* interface to postgresql elog */
1528 static PyObject *PLy_debug(PyObject *, PyObject *);
1529 static PyObject *PLy_log(PyObject *, PyObject *);
1530 static PyObject *PLy_info(PyObject *, PyObject *);
1531 static PyObject *PLy_notice(PyObject *, PyObject *);
1532 static PyObject *PLy_warning(PyObject *, PyObject *);
1533 static PyObject *PLy_error(PyObject *, PyObject *);
1534 static PyObject *PLy_fatal(PyObject *, PyObject *);
1536 /* PLyPlanObject, PLyResultObject and SPI interface */
1537 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1538 static PyObject *PLy_plan_new(void);
1539 static void PLy_plan_dealloc(PyObject *);
1540 static PyObject *PLy_plan_getattr(PyObject *, char *);
1541 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1543 static PyObject *PLy_result_new(void);
1544 static void PLy_result_dealloc(PyObject *);
1545 static PyObject *PLy_result_getattr(PyObject *, char *);
1546 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1547 static PyObject *PLy_result_status(PyObject *, PyObject *);
1548 static int PLy_result_length(PyObject *);
1549 static PyObject *PLy_result_item(PyObject *, int);
1550 static PyObject *PLy_result_slice(PyObject *, int, int);
1551 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1552 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1555 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1556 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1557 static PyObject *PLy_spi_execute_query(char *query, long limit);
1558 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1559 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1562 static PyTypeObject PLy_PlanType = {
1563 PyObject_HEAD_INIT(NULL)
1565 "PLyPlan", /* tp_name */
1566 sizeof(PLyPlanObject), /* tp_size */
1567 0, /* tp_itemsize */
1572 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1574 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1578 0, /* tp_as_number */
1579 0, /* tp_as_sequence */
1580 0, /* tp_as_mapping */
1584 0, /* tp_getattro */
1585 0, /* tp_setattro */
1586 0, /* tp_as_buffer */
1588 PLy_plan_doc, /* tp_doc */
1591 static PyMethodDef PLy_plan_methods[] = {
1592 {"status", PLy_plan_status, METH_VARARGS, NULL},
1593 {NULL, NULL, 0, NULL}
1597 static PySequenceMethods PLy_result_as_sequence = {
1598 (inquiry) PLy_result_length, /* sq_length */
1599 (binaryfunc) 0, /* sq_concat */
1600 (intargfunc) 0, /* sq_repeat */
1601 (intargfunc) PLy_result_item, /* sq_item */
1602 (intintargfunc) PLy_result_slice, /* sq_slice */
1603 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1604 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1607 static PyTypeObject PLy_ResultType = {
1608 PyObject_HEAD_INIT(NULL)
1610 "PLyResult", /* tp_name */
1611 sizeof(PLyResultObject), /* tp_size */
1612 0, /* tp_itemsize */
1617 (destructor) PLy_result_dealloc, /* tp_dealloc */
1619 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1623 0, /* tp_as_number */
1624 &PLy_result_as_sequence, /* tp_as_sequence */
1625 0, /* tp_as_mapping */
1629 0, /* tp_getattro */
1630 0, /* tp_setattro */
1631 0, /* tp_as_buffer */
1633 PLy_result_doc, /* tp_doc */
1636 static PyMethodDef PLy_result_methods[] = {
1637 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
1638 {"status", PLy_result_status, METH_VARARGS, NULL},
1639 {NULL, NULL, 0, NULL}
1642 static PyMethodDef PLy_methods[] = {
1646 {"debug", PLy_debug, METH_VARARGS, NULL},
1647 {"log", PLy_log, METH_VARARGS, NULL},
1648 {"info", PLy_info, METH_VARARGS, NULL},
1649 {"notice", PLy_notice, METH_VARARGS, NULL},
1650 {"warning", PLy_warning, METH_VARARGS, NULL},
1651 {"error", PLy_error, METH_VARARGS, NULL},
1652 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1655 * create a stored plan
1657 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1660 * execute a plan or query
1662 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1664 {NULL, NULL, 0, NULL}
1668 /* plan object methods */
1674 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1682 return (PyObject *) ob;
1687 PLy_plan_dealloc(PyObject * arg)
1689 PLyPlanObject *ob = (PLyPlanObject *) arg;
1692 SPI_freeplan(ob->plan);
1694 PLy_free(ob->types);
1699 for (i = 0; i < ob->nargs; i++)
1700 PLy_typeinfo_dealloc(&ob->args[i]);
1709 PLy_plan_getattr(PyObject * self, char *name)
1711 return Py_FindMethod(PLy_plan_methods, self, name);
1715 PLy_plan_status(PyObject * self, PyObject * args)
1717 if (PyArg_ParseTuple(args, ""))
1721 /* return PyInt_FromLong(self->status); */
1723 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1729 /* result object methods */
1732 PLy_result_new(void)
1734 PLyResultObject *ob;
1736 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1739 /* ob->tuples = NULL; */
1742 ob->status = Py_None;
1743 ob->nrows = PyInt_FromLong(-1);
1744 ob->rows = PyList_New(0);
1746 return (PyObject *) ob;
1750 PLy_result_dealloc(PyObject * arg)
1752 PLyResultObject *ob = (PLyResultObject *) arg;
1754 Py_XDECREF(ob->nrows);
1755 Py_XDECREF(ob->rows);
1756 Py_XDECREF(ob->status);
1762 PLy_result_getattr(PyObject * self, char *name)
1764 return Py_FindMethod(PLy_result_methods, self, name);
1768 PLy_result_nrows(PyObject * self, PyObject * args)
1770 PLyResultObject *ob = (PLyResultObject *) self;
1772 Py_INCREF(ob->nrows);
1777 PLy_result_status(PyObject * self, PyObject * args)
1779 PLyResultObject *ob = (PLyResultObject *) self;
1781 Py_INCREF(ob->status);
1786 PLy_result_length(PyObject * arg)
1788 PLyResultObject *ob = (PLyResultObject *) arg;
1790 return PyList_Size(ob->rows);
1794 PLy_result_item(PyObject * arg, int idx)
1797 PLyResultObject *ob = (PLyResultObject *) arg;
1799 rv = PyList_GetItem(ob->rows, idx);
1806 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1809 PLyResultObject *ob = (PLyResultObject *) arg;
1812 rv = PyList_SetItem(ob->rows, idx, item);
1817 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1820 PLyResultObject *ob = (PLyResultObject *) arg;
1822 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1830 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1833 PLyResultObject *ob = (PLyResultObject *) arg;
1835 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1841 PLy_spi_prepare(PyObject * self, PyObject * args)
1843 PLyPlanObject *plan;
1844 PyObject *list = NULL;
1845 PyObject *volatile optr = NULL;
1848 MemoryContext oldcontext;
1850 /* Can't execute more if we have an unhandled error */
1851 if (PLy_error_in_progress)
1853 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1857 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1859 PyErr_SetString(PLy_exc_spi_error,
1860 "Invalid arguments for plpy.prepare()");
1864 if (list && (!PySequence_Check(list)))
1866 PyErr_SetString(PLy_exc_spi_error,
1867 "Second argument in plpy.prepare() must be a sequence");
1871 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1874 oldcontext = CurrentMemoryContext;
1882 nargs = PySequence_Length(list);
1885 plan->nargs = nargs;
1886 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1887 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1888 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1891 * the other loop might throw an exception, if PLyTypeInfo
1892 * member isn't properly initialized the Py_DECREF(plan) will
1895 for (i = 0; i < nargs; i++)
1897 PLy_typeinfo_init(&plan->args[i]);
1898 plan->values[i] = PointerGetDatum(NULL);
1901 for (i = 0; i < nargs; i++)
1905 Form_pg_type typeStruct;
1907 optr = PySequence_GetItem(list, i);
1908 if (!PyString_Check(optr))
1909 elog(ERROR, "Type names must be strings.");
1910 sptr = PyString_AsString(optr);
1913 * XXX should extend this to allow qualified type names
1915 typeTup = typenameType(makeTypeName(sptr));
1917 optr = NULL; /* this is important */
1919 plan->types[i] = HeapTupleGetOid(typeTup);
1920 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1921 if (typeStruct->typtype != 'c')
1922 PLy_output_datum_func(&plan->args[i], typeTup);
1924 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
1925 ReleaseSysCache(typeTup);
1930 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1931 if (plan->plan == NULL)
1932 elog(ERROR, "SPI_prepare failed: %s",
1933 SPI_result_code_string(SPI_result));
1935 /* transfer plan from procCxt to topCxt */
1936 tmpplan = plan->plan;
1937 plan->plan = SPI_saveplan(tmpplan);
1938 SPI_freeplan(tmpplan);
1939 if (plan->plan == NULL)
1940 elog(ERROR, "SPI_saveplan failed: %s",
1941 SPI_result_code_string(SPI_result));
1945 MemoryContextSwitchTo(oldcontext);
1946 PLy_error_in_progress = CopyErrorData();
1950 if (!PyErr_Occurred())
1951 PyErr_SetString(PLy_exc_spi_error,
1952 "Unknown error in PLy_spi_prepare");
1953 /* XXX this oughta be replaced with errcontext mechanism */
1954 PLy_elog(WARNING, "in function %s:",
1955 PLy_procedure_name(PLy_curr_procedure));
1960 return (PyObject *) plan;
1963 /* execute(query="select * from foo", limit=5)
1964 * execute(plan=plan, values=(foo, bar), limit=5)
1967 PLy_spi_execute(PyObject * self, PyObject * args)
1971 PyObject *list = NULL;
1974 /* Can't execute more if we have an unhandled error */
1975 if (PLy_error_in_progress)
1977 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1981 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
1982 return PLy_spi_execute_query(query, limit);
1986 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
1987 is_PLyPlanObject(plan))
1988 return PLy_spi_execute_plan(plan, list, limit);
1990 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
1995 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
2000 PLyPlanObject *plan;
2001 MemoryContext oldcontext;
2005 if (!PySequence_Check(list) || PyString_Check(list))
2007 char *msg = "plpy.execute() takes a sequence as its second argument";
2009 PyErr_SetString(PLy_exc_spi_error, msg);
2012 nargs = PySequence_Length(list);
2017 plan = (PLyPlanObject *) ob;
2019 if (nargs != plan->nargs)
2022 PyObject *so = PyObject_Str(list);
2025 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2026 PLy_procedure_name(PLy_curr_procedure));
2027 sv = PyString_AsString(so);
2028 PLy_exception_set(PLy_exc_spi_error,
2029 "Expected sequence of %d arguments, got %d. %s",
2030 plan->nargs, nargs, sv);
2036 oldcontext = CurrentMemoryContext;
2039 char *nulls = palloc(nargs * sizeof(char));
2041 for (i = 0; i < nargs; i++)
2046 elem = PySequence_GetItem(list, i);
2047 if (elem != Py_None)
2049 so = PyObject_Str(elem);
2051 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2052 PLy_procedure_name(PLy_curr_procedure));
2057 char *sv = PyString_AsString(so);
2060 FunctionCall3(&(plan->args[i].out.d.typfunc),
2061 CStringGetDatum(sv),
2062 ObjectIdGetDatum(plan->args[i].out.d.typioparam),
2078 plan->values[i] = PointerGetDatum(NULL);
2083 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2084 PLy_curr_procedure->fn_readonly, limit);
2090 MemoryContextSwitchTo(oldcontext);
2091 PLy_error_in_progress = CopyErrorData();
2095 * cleanup plan->values array
2097 for (i = 0; i < nargs; i++)
2099 if (!plan->args[i].out.d.typbyval &&
2100 (plan->values[i] != PointerGetDatum(NULL)))
2102 pfree(DatumGetPointer(plan->values[i]));
2103 plan->values[i] = PointerGetDatum(NULL);
2107 if (!PyErr_Occurred())
2108 PyErr_SetString(PLy_exc_error,
2109 "Unknown error in PLy_spi_execute_plan");
2110 /* XXX this oughta be replaced with errcontext mechanism */
2111 PLy_elog(WARNING, "in function %s:",
2112 PLy_procedure_name(PLy_curr_procedure));
2117 for (i = 0; i < nargs; i++)
2119 if (!plan->args[i].out.d.typbyval &&
2120 (plan->values[i] != PointerGetDatum(NULL)))
2122 pfree(DatumGetPointer(plan->values[i]));
2123 plan->values[i] = PointerGetDatum(NULL);
2129 PLy_exception_set(PLy_exc_spi_error,
2130 "SPI_execute_plan failed: %s",
2131 SPI_result_code_string(rv));
2135 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2139 PLy_spi_execute_query(char *query, long limit)
2142 MemoryContext oldcontext;
2144 oldcontext = CurrentMemoryContext;
2147 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2151 MemoryContextSwitchTo(oldcontext);
2152 PLy_error_in_progress = CopyErrorData();
2154 if (!PyErr_Occurred())
2155 PyErr_SetString(PLy_exc_spi_error,
2156 "Unknown error in PLy_spi_execute_query");
2157 /* XXX this oughta be replaced with errcontext mechanism */
2158 PLy_elog(WARNING, "in function %s:",
2159 PLy_procedure_name(PLy_curr_procedure));
2166 PLy_exception_set(PLy_exc_spi_error,
2167 "SPI_execute failed: %s",
2168 SPI_result_code_string(rv));
2172 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2176 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2178 PLyResultObject *result;
2179 MemoryContext oldcontext;
2181 result = (PLyResultObject *) PLy_result_new();
2182 Py_DECREF(result->status);
2183 result->status = PyInt_FromLong(status);
2185 if (status == SPI_OK_UTILITY)
2187 Py_DECREF(result->nrows);
2188 result->nrows = PyInt_FromLong(0);
2190 else if (status != SPI_OK_SELECT)
2192 Py_DECREF(result->nrows);
2193 result->nrows = PyInt_FromLong(rows);
2200 PLy_typeinfo_init(&args);
2201 Py_DECREF(result->nrows);
2202 result->nrows = PyInt_FromLong(rows);
2204 oldcontext = CurrentMemoryContext;
2209 Py_DECREF(result->rows);
2210 result->rows = PyList_New(rows);
2212 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2213 for (i = 0; i < rows; i++)
2215 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2218 PyList_SetItem(result->rows, i, row);
2220 PLy_typeinfo_dealloc(&args);
2222 SPI_freetuptable(tuptable);
2227 MemoryContextSwitchTo(oldcontext);
2228 PLy_error_in_progress = CopyErrorData();
2230 if (!PyErr_Occurred())
2231 PyErr_SetString(PLy_exc_error,
2232 "Unknown error in PLy_spi_execute_fetch_result");
2234 PLy_typeinfo_dealloc(&args);
2240 return (PyObject *) result;
2245 * language handler and interpreter initialization
2249 * plpython_init() - Initialize everything that can be
2250 * safely initialized during postmaster
2253 * DO NOT make this static --- it has to be callable by preload
2258 static volatile bool init_active = false;
2260 /* Do initialization only once */
2261 if (!PLy_first_call)
2265 elog(FATAL, "initialization of language module failed");
2271 if (PyErr_Occurred())
2272 PLy_elog(FATAL, "untrapped error in initialization");
2273 PLy_procedure_cache = PyDict_New();
2274 if (PLy_procedure_cache == NULL)
2275 PLy_elog(ERROR, "could not create procedure cache");
2277 PLy_first_call = false;
2283 /* Execute postmaster-startup safe initialization */
2288 * Any other initialization that must be done each time a new backend
2289 * starts -- currently none
2294 PLy_init_interp(void)
2298 mainmod = PyImport_AddModule("__main__");
2299 if (mainmod == NULL || PyErr_Occurred())
2300 PLy_elog(ERROR, "could not import \"__main__\" module.");
2302 PLy_interp_globals = PyModule_GetDict(mainmod);
2303 PLy_interp_safe_globals = PyDict_New();
2304 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2306 if (PLy_interp_globals == NULL || PyErr_Occurred())
2307 PLy_elog(ERROR, "could not initialize globals");
2320 * initialize plpy module
2322 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2323 plpy = Py_InitModule("plpy", PLy_methods);
2324 plpy_dict = PyModule_GetDict(plpy);
2326 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2328 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2329 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2330 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2331 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2332 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2333 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2336 * initialize main module, and add plpy
2338 main_mod = PyImport_AddModule("__main__");
2339 main_dict = PyModule_GetDict(main_mod);
2340 plpy_mod = PyImport_AddModule("plpy");
2341 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2342 if (PyErr_Occurred())
2343 elog(ERROR, "could not init plpy");
2346 /* the python interface to the elog function
2347 * don't confuse these with PLy_elog
2349 static PyObject *PLy_output(int, PyObject *, PyObject *);
2352 PLy_debug(PyObject * self, PyObject * args)
2354 return PLy_output(DEBUG2, self, args);
2358 PLy_log(PyObject * self, PyObject * args)
2360 return PLy_output(LOG, self, args);
2364 PLy_info(PyObject * self, PyObject * args)
2366 return PLy_output(INFO, self, args);
2370 PLy_notice(PyObject * self, PyObject * args)
2372 return PLy_output(NOTICE, self, args);
2376 PLy_warning(PyObject * self, PyObject * args)
2378 return PLy_output(WARNING, self, args);
2382 PLy_error(PyObject * self, PyObject * args)
2384 return PLy_output(ERROR, self, args);
2388 PLy_fatal(PyObject * self, PyObject * args)
2390 return PLy_output(FATAL, self, args);
2395 PLy_output(volatile int level, PyObject * self, PyObject * args)
2399 MemoryContext oldcontext;
2401 so = PyObject_Str(args);
2402 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2405 sv = "Unable to parse error message in `plpy.elog'";
2408 oldcontext = CurrentMemoryContext;
2411 elog(level, "%s", sv);
2415 MemoryContextSwitchTo(oldcontext);
2416 PLy_error_in_progress = CopyErrorData();
2421 * returning NULL here causes the python interpreter to bail. when
2422 * control passes back to PLy_procedure_call, we check for PG
2423 * exceptions and re-throw the error.
2425 PyErr_SetString(PLy_exc_error, sv);
2433 * return a legal object so the interpreter will continue on its merry way
2441 * Get the name of the last procedure called by the backend (the
2442 * innermost, if a plpython procedure call calls the backend and the
2443 * backend calls another plpython procedure).
2445 * NB: this returns the SQL name, not the internal Python procedure name
2448 PLy_procedure_name(PLyProcedure * proc)
2451 return "<unknown procedure>";
2452 return proc->proname;
2455 /* output a python traceback/exception via the postgresql elog
2456 * function. not pretty.
2459 PLy_exception_set(PyObject * exc, const char *fmt,...)
2465 vsnprintf(buf, sizeof(buf), fmt, ap);
2468 PyErr_SetString(exc, buf);
2471 /* Emit a PG error or notice, together with any available info about the
2472 * current Python error. This should be used to propagate Python errors
2476 PLy_elog(int elevel, const char *fmt,...)
2483 xmsg = PLy_traceback(&xlevel);
2486 emsg = PLy_vprintf(fmt, ap);
2492 (errmsg("plpython: %s", emsg),
2493 (xmsg) ? errdetail("%s", xmsg) : 0));
2510 PLy_traceback(int *xlevel)
2522 * get the current exception
2524 PyErr_Fetch(&e, &v, &tb);
2527 * oops, no exception, return
2535 PyErr_NormalizeException(&e, &v, &tb);
2538 eob = PyObject_Str(e);
2539 if (v && ((vob = PyObject_Str(v)) != NULL))
2540 vstr = PyString_AsString(vob);
2545 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
2546 * because that function calls us, so we could end up with infinite
2547 * recursion. I'm not even sure if eob could be NULL here -- would an
2548 * Assert() be more appropriate?
2550 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
2551 xstr = PLy_printf("%s: %s", estr, vstr);
2558 * intuit an appropriate error level based on the exception type
2560 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
2562 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
2572 PLy_printf(const char *fmt,...)
2578 emsg = PLy_vprintf(fmt, ap);
2584 PLy_vprintf(const char *fmt, va_list ap)
2591 blen = strlen(fmt) * 2;
2594 buf = PLy_malloc(blen * sizeof(char));
2598 bchar = vsnprintf(buf, blen, fmt, ap);
2599 if (bchar > 0 && bchar < blen)
2607 buf = PLy_realloc(buf, blen);
2613 /* python module code */
2615 /* some dumb utility functions */
2617 PLy_malloc(size_t bytes)
2619 void *ptr = malloc(bytes);
2623 (errcode(ERRCODE_OUT_OF_MEMORY),
2624 errmsg("out of memory")));
2629 PLy_realloc(void *optr, size_t bytes)
2631 void *nptr = realloc(optr, bytes);
2635 (errcode(ERRCODE_OUT_OF_MEMORY),
2636 errmsg("out of memory")));
2641 PLy_strdup(const char *str)
2646 len = strlen(str) + 1;
2647 result = PLy_malloc(len);
2648 memcpy(result, str, len);
2653 /* define this away */