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.69 2006/01/09 02:47:09 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
99 typedef struct PLyObToTuple
105 typedef union PLyTypeOutput
111 /* all we need to move Postgresql data to Python objects,
114 typedef struct PLyTypeInfo
121 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
122 * 1 rowtype 2 rowtype, but I/O functions not set up yet
127 /* 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 tuple
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
148 typedef struct PLyPlanObject
151 void *plan; /* return of an SPI_saveplan */
158 typedef struct PLyResultObject
161 /* HeapTuple *tuples; */
162 PyObject *nrows; /* number of rows returned by query */
163 PyObject *rows; /* data rows, or None if no data returned */
164 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
168 /* function declarations */
170 /* Two exported functions: first is the magic telling Postgresql
171 * what function call interface it implements. Second allows
172 * preinitialization of the interpreter during postmaster startup.
174 Datum plpython_call_handler(PG_FUNCTION_ARGS);
175 void plpython_init(void);
177 PG_FUNCTION_INFO_V1(plpython_call_handler);
179 /* most of the remaining of the declarations, all static */
181 /* these should only be called once at the first call
182 * of plpython_call_handler. initialize the python interpreter
185 static void PLy_init_all(void);
186 static void PLy_init_interp(void);
187 static void PLy_init_plpy(void);
189 /* call PyErr_SetString with a vprint interface */
191 PLy_exception_set(PyObject *, const char *,...)
192 __attribute__((format(printf, 2, 3)));
194 /* Get the innermost python procedure called from the backend */
195 static char *PLy_procedure_name(PLyProcedure *);
197 /* some utility functions */
198 static void PLy_elog(int, const char *,...);
199 static char *PLy_traceback(int *);
200 static char *PLy_vprintf(const char *fmt, va_list ap);
201 static char *PLy_printf(const char *fmt,...);
203 static void *PLy_malloc(size_t);
204 static void *PLy_realloc(void *, size_t);
205 static char *PLy_strdup(const char *);
206 static void PLy_free(void *);
208 /* sub handlers for functions and triggers */
209 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
210 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
212 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
213 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
215 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
216 TriggerData *, HeapTuple);
218 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
220 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
223 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
225 HeapTuple procTup, char *key);
227 static void PLy_procedure_compile(PLyProcedure *, const char *);
228 static char *PLy_procedure_munge_source(const char *, const char *);
229 static void PLy_procedure_delete(PLyProcedure *);
231 static void PLy_typeinfo_init(PLyTypeInfo *);
232 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
233 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
234 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
235 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
236 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
237 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
238 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
240 /* conversion functions */
241 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
242 static PyObject *PLyBool_FromString(const char *);
243 static PyObject *PLyFloat_FromString(const char *);
244 static PyObject *PLyInt_FromString(const char *);
245 static PyObject *PLyLong_FromString(const char *);
246 static PyObject *PLyString_FromString(const char *);
250 static bool PLy_first_call = true;
253 * Currently active plpython function
255 static PLyProcedure *PLy_curr_procedure = NULL;
258 * When a callback from Python into PG incurs an error, we temporarily store
259 * the error information here, and return NULL to the Python interpreter.
260 * Any further callback attempts immediately fail, and when the Python
261 * interpreter returns to the calling function, we re-throw the error (even if
262 * Python thinks it trapped the error and doesn't return NULL). Eventually
263 * this ought to be improved to let Python code really truly trap the error,
264 * but that's more of a change from the pre-8.0 semantics than I have time for
265 * now --- it will only be possible if the callback query is executed inside a
268 static ErrorData *PLy_error_in_progress = NULL;
270 static PyObject *PLy_interp_globals = NULL;
271 static PyObject *PLy_interp_safe_globals = NULL;
272 static PyObject *PLy_procedure_cache = NULL;
274 /* Python exceptions */
275 static PyObject *PLy_exc_error = NULL;
276 static PyObject *PLy_exc_fatal = NULL;
277 static PyObject *PLy_exc_spi_error = NULL;
279 /* some globals for the python module */
280 static char PLy_plan_doc[] = {
281 "Store a PostgreSQL plan"
284 static char PLy_result_doc[] = {
285 "Results of a PostgreSQL query"
290 * the function definitions
294 * This routine is a crock, and so is everyplace that calls it. The problem
295 * is that the cached form of plpython functions/queries is allocated permanently
296 * (mostly via malloc()) and never released until backend exit. Subsidiary
297 * data structures such as fmgr info records therefore must live forever
298 * as well. A better implementation would store all this stuff in a per-
299 * function memory context that could be reclaimed at need. In the meantime,
300 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
301 * it might allocate, and whatever the eventual function might allocate using
302 * fn_mcxt, will live forever too.
305 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
307 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
311 plpython_call_handler(PG_FUNCTION_ARGS)
314 PLyProcedure *save_curr_proc;
315 PLyProcedure *volatile proc = NULL;
319 if (SPI_connect() != SPI_OK_CONNECT)
320 elog(ERROR, "could not connect to SPI manager");
322 save_curr_proc = PLy_curr_procedure;
326 if (CALLED_AS_TRIGGER(fcinfo))
328 TriggerData *tdata = (TriggerData *) fcinfo->context;
331 proc = PLy_procedure_get(fcinfo,
332 RelationGetRelid(tdata->tg_relation));
333 PLy_curr_procedure = proc;
334 trv = PLy_trigger_handler(fcinfo, proc);
335 retval = PointerGetDatum(trv);
339 proc = PLy_procedure_get(fcinfo, InvalidOid);
340 PLy_curr_procedure = proc;
341 retval = PLy_function_handler(fcinfo, proc);
346 PLy_curr_procedure = save_curr_proc;
349 /* note: Py_DECREF needs braces around it, as of 2003/08 */
357 PLy_curr_procedure = save_curr_proc;
364 /* trigger and function sub handlers
366 * the python function is expected to return Py_None if the tuple is
367 * acceptable and unmodified. Otherwise it should return a PyString
368 * object who's value is SKIP, or MODIFY. SKIP means don't perform
369 * this action. MODIFY means the tuple has been modified, so update
370 * tuple and perform action. SKIP and MODIFY assume the trigger fires
371 * BEFORE the event and is ROW level. postgres expects the function
372 * to take no arguments and return an argument of type trigger.
375 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
378 PyObject *volatile plargs = NULL;
379 PyObject *volatile plrv = NULL;
383 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
384 plrv = PLy_procedure_call(proc, "TD", plargs);
386 Assert(plrv != NULL);
387 Assert(!PLy_error_in_progress);
390 * Disconnect from SPI manager
392 if (SPI_finish() != SPI_OK_FINISH)
393 elog(ERROR, "SPI_finish failed");
396 * return of None means we're happy with the tuple
402 if (!PyString_Check(plrv))
404 (errcode(ERRCODE_DATA_EXCEPTION),
405 errmsg("unexpected return value from trigger procedure"),
406 errdetail("expected None or a String")));
408 srv = PyString_AsString(plrv);
409 if (pg_strcasecmp(srv, "SKIP") == 0)
411 else if (pg_strcasecmp(srv, "MODIFY") == 0)
413 TriggerData *tdata = (TriggerData *) fcinfo->context;
415 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
416 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
417 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
419 elog(WARNING, "ignoring modified tuple in DELETE trigger");
421 else if (pg_strcasecmp(srv, "OK") != 0)
424 * accept "OK" as an alternative to None; otherwise,
428 (errcode(ERRCODE_DATA_EXCEPTION),
429 errmsg("unexpected return value from trigger procedure"),
430 errdetail("expected None, \"OK\", \"SKIP\", or \"MODIFY\"")));
450 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
453 PyObject *volatile plntup;
454 PyObject *volatile plkeys;
455 PyObject *volatile platt;
456 PyObject *volatile plval;
457 PyObject *volatile plstr;
463 int *volatile modattrs;
464 Datum *volatile modvalues;
465 char *volatile modnulls;
468 plntup = plkeys = platt = plval = plstr = NULL;
475 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
476 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
477 if (!PyDict_Check(plntup))
478 elog(ERROR, "TD[\"new\"] is not a dictionary object");
481 plkeys = PyDict_Keys(plntup);
482 natts = PyList_Size(plkeys);
484 modattrs = (int *) palloc(natts * sizeof(int));
485 modvalues = (Datum *) palloc(natts * sizeof(Datum));
486 modnulls = (char *) palloc(natts * sizeof(char));
488 tupdesc = tdata->tg_relation->rd_att;
490 for (i = 0; i < natts; i++)
494 platt = PyList_GetItem(plkeys, i);
495 if (!PyString_Check(platt))
496 elog(ERROR, "attribute name is not a string");
497 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
498 if (attn == SPI_ERROR_NOATTRIBUTE)
499 elog(ERROR, "invalid attribute \"%s\" in tuple",
500 PyString_AsString(platt));
503 plval = PyDict_GetItem(plntup, platt);
505 elog(FATAL, "python interpreter is probably corrupted");
511 if (plval != Py_None && !tupdesc->attrs[atti]->attisdropped)
513 plstr = PyObject_Str(plval);
515 PLy_elog(ERROR, "function \"%s\" could not modify tuple", proc->proname);
516 src = PyString_AsString(plstr);
518 modvalues[i] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
519 CStringGetDatum(src),
520 ObjectIdGetDatum(proc->result.out.r.atts[atti].typioparam),
521 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
529 modvalues[i] = PointerGetDatum(NULL);
537 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
538 modattrs, modvalues, modnulls);
540 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 * convert the python PyObject to a postgresql Datum
765 fcinfo->isnull = true;
766 rv = PointerGetDatum(NULL);
770 fcinfo->isnull = false;
771 plrv_so = PyObject_Str(plrv);
773 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
774 plrv_sc = PyString_AsString(plrv_so);
775 rv = FunctionCall3(&proc->result.out.d.typfunc,
776 PointerGetDatum(plrv_sc),
777 ObjectIdGetDatum(proc->result.out.d.typioparam),
799 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
803 PyDict_SetItemString(proc->globals, kargs, vargs);
804 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
805 proc->globals, proc->globals);
808 * If there was an error in a PG callback, propagate that no matter what
809 * Python claims about its success.
811 if (PLy_error_in_progress)
813 ErrorData *edata = PLy_error_in_progress;
815 PLy_error_in_progress = NULL;
819 if (rv == NULL || PyErr_Occurred())
822 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
829 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
831 PyObject *volatile arg = NULL;
832 PyObject *volatile args = NULL;
837 args = PyList_New(proc->nargs);
838 for (i = 0; i < proc->nargs; i++)
840 if (proc->args[i].is_rowtype > 0)
842 if (fcinfo->argnull[i])
850 HeapTupleData tmptup;
852 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
853 /* Extract rowtype info and find a tupdesc */
854 tupType = HeapTupleHeaderGetTypeId(td);
855 tupTypmod = HeapTupleHeaderGetTypMod(td);
856 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
858 /* Set up I/O funcs if not done yet */
859 if (proc->args[i].is_rowtype != 1)
860 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
862 /* Build a temporary HeapTuple control structure */
863 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
866 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
871 if (fcinfo->argnull[i])
878 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
880 ObjectIdGetDatum(proc->args[i].in.d.typioparam),
882 ct = DatumGetCString(dt);
883 arg = (proc->args[i].in.d.func) (ct);
895 * FIXME -- error check this
897 PyList_SetItem(args, i, arg);
914 * PLyProcedure functions
917 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
918 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
919 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
922 static PLyProcedure *
923 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
929 PLyProcedure *proc = NULL;
932 fn_oid = fcinfo->flinfo->fn_oid;
933 procTup = SearchSysCache(PROCOID,
934 ObjectIdGetDatum(fn_oid),
936 if (!HeapTupleIsValid(procTup))
937 elog(ERROR, "cache lookup failed for function %u", fn_oid);
939 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
940 if (rv >= sizeof(key) || rv < 0)
941 elog(ERROR, "key too long");
943 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
948 if (!PyCObject_Check(plproc))
949 elog(FATAL, "expected a PyCObject, didn't get one");
951 proc = PyCObject_AsVoidPtr(plproc);
952 if (proc->me != plproc)
953 elog(FATAL, "proc->me != plproc");
954 /* did we find an up-to-date cache entry? */
955 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
956 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
964 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
966 ReleaseSysCache(procTup);
971 static PLyProcedure *
972 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
973 HeapTuple procTup, char *key)
975 char procName[NAMEDATALEN + 256];
976 Form_pg_proc procStruct;
977 PLyProcedure *volatile proc;
978 char *volatile procSource = NULL;
984 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
986 if (OidIsValid(tgreloid))
987 rv = snprintf(procName, sizeof(procName),
988 "__plpython_procedure_%s_%u_trigger_%u",
989 NameStr(procStruct->proname),
990 fcinfo->flinfo->fn_oid,
993 rv = snprintf(procName, sizeof(procName),
994 "__plpython_procedure_%s_%u",
995 NameStr(procStruct->proname),
996 fcinfo->flinfo->fn_oid);
997 if (rv >= sizeof(procName) || rv < 0)
998 elog(ERROR, "procedure name would overrun buffer");
1000 proc = PLy_malloc(sizeof(PLyProcedure));
1001 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1002 proc->pyname = PLy_strdup(procName);
1003 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1004 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1005 /* Remember if function is STABLE/IMMUTABLE */
1007 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1008 PLy_typeinfo_init(&proc->result);
1009 for (i = 0; i < FUNC_MAX_ARGS; i++)
1010 PLy_typeinfo_init(&proc->args[i]);
1012 proc->code = proc->statics = NULL;
1013 proc->globals = proc->me = NULL;
1018 * get information required for output conversion of the return value,
1019 * but only if this isn't a trigger.
1021 if (!CALLED_AS_TRIGGER(fcinfo))
1023 HeapTuple rvTypeTup;
1024 Form_pg_type rvTypeStruct;
1026 rvTypeTup = SearchSysCache(TYPEOID,
1027 ObjectIdGetDatum(procStruct->prorettype),
1029 if (!HeapTupleIsValid(rvTypeTup))
1030 elog(ERROR, "cache lookup failed for type %u",
1031 procStruct->prorettype);
1032 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1034 /* Disallow pseudotype result */
1035 if (rvTypeStruct->typtype == 'p')
1037 if (procStruct->prorettype == TRIGGEROID)
1039 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1040 errmsg("trigger functions may only be called as triggers")));
1043 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1044 errmsg("plpython functions cannot return type %s",
1045 format_type_be(procStruct->prorettype))));
1048 if (rvTypeStruct->typtype == 'c')
1050 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1051 errmsg("plpython functions cannot return tuples yet")));
1053 PLy_output_datum_func(&proc->result, rvTypeTup);
1055 ReleaseSysCache(rvTypeTup);
1060 * input/output conversion for trigger tuples. use the result
1061 * TypeInfo variable to store the tuple conversion info.
1063 TriggerData *tdata = (TriggerData *) fcinfo->context;
1065 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1066 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1070 * now get information required for input conversion of the procedures
1073 proc->nargs = fcinfo->nargs;
1074 for (i = 0; i < fcinfo->nargs; i++)
1076 HeapTuple argTypeTup;
1077 Form_pg_type argTypeStruct;
1079 argTypeTup = SearchSysCache(TYPEOID,
1080 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1082 if (!HeapTupleIsValid(argTypeTup))
1083 elog(ERROR, "cache lookup failed for type %u",
1084 procStruct->proargtypes.values[i]);
1085 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1087 /* Disallow pseudotype argument */
1088 if (argTypeStruct->typtype == 'p')
1090 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1091 errmsg("plpython functions cannot take type %s",
1092 format_type_be(procStruct->proargtypes.values[i]))));
1094 if (argTypeStruct->typtype != 'c')
1095 PLy_input_datum_func(&(proc->args[i]),
1096 procStruct->proargtypes.values[i],
1099 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1101 ReleaseSysCache(argTypeTup);
1106 * get the text of the function.
1108 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1109 Anum_pg_proc_prosrc, &isnull);
1111 elog(ERROR, "null prosrc");
1112 procSource = DatumGetCString(DirectFunctionCall1(textout,
1115 PLy_procedure_compile(proc, procSource);
1119 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1120 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1124 PLy_procedure_delete(proc);
1136 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1138 PyObject *crv = NULL;
1141 proc->globals = PyDict_Copy(PLy_interp_globals);
1144 * SD is private preserved data between calls. GD is global data
1145 * shared by all functions
1147 proc->statics = PyDict_New();
1148 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1151 * insert the function code into the interpreter
1153 msrc = PLy_procedure_munge_source(proc->pyname, src);
1154 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1157 if (crv != NULL && (!PyErr_Occurred()))
1160 char call[NAMEDATALEN + 256];
1165 * compile a call to the function
1167 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1168 if (clen < 0 || clen >= sizeof(call))
1169 elog(ERROR, "string would overflow buffer");
1170 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1171 if (proc->code != NULL && (!PyErr_Occurred()))
1177 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1181 PLy_procedure_munge_source(const char *name, const char *src)
1190 * room for function source and the def statement
1192 mlen = (strlen(src) * 2) + strlen(name) + 16;
1194 mrc = PLy_malloc(mlen);
1195 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1196 Assert(plen >= 0 && plen < mlen);
1203 if (*sp == '\r' && *(sp + 1) == '\n')
1206 if (*sp == '\n' || *sp == '\r')
1219 if (mp > (mrc + mlen))
1220 elog(FATAL, "buffer overrun in PLy_munge_source");
1226 PLy_procedure_delete(PLyProcedure * proc)
1230 Py_XDECREF(proc->code);
1231 Py_XDECREF(proc->statics);
1232 Py_XDECREF(proc->globals);
1233 Py_XDECREF(proc->me);
1235 PLy_free(proc->proname);
1237 PLy_free(proc->pyname);
1238 for (i = 0; i < proc->nargs; i++)
1239 if (proc->args[i].is_rowtype == 1)
1241 if (proc->args[i].in.r.atts)
1242 PLy_free(proc->args[i].in.r.atts);
1243 if (proc->args[i].out.r.atts)
1244 PLy_free(proc->args[i].out.r.atts);
1248 /* conversion functions. remember output from python is
1249 * input to postgresql, and vis versa.
1252 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1256 if (arg->is_rowtype == 0)
1257 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1259 arg->is_rowtype = 1;
1260 arg->in.r.natts = desc->natts;
1261 arg->in.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1263 for (i = 0; i < desc->natts; i++)
1267 if (desc->attrs[i]->attisdropped)
1270 typeTup = SearchSysCache(TYPEOID,
1271 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1273 if (!HeapTupleIsValid(typeTup))
1274 elog(ERROR, "cache lookup failed for type %u",
1275 desc->attrs[i]->atttypid);
1277 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1278 desc->attrs[i]->atttypid,
1281 ReleaseSysCache(typeTup);
1286 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1290 if (arg->is_rowtype == 0)
1291 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1293 arg->is_rowtype = 1;
1294 arg->out.r.natts = desc->natts;
1295 arg->out.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1297 for (i = 0; i < desc->natts; i++)
1301 if (desc->attrs[i]->attisdropped)
1304 typeTup = SearchSysCache(TYPEOID,
1305 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1307 if (!HeapTupleIsValid(typeTup))
1308 elog(ERROR, "cache lookup failed for type %u",
1309 desc->attrs[i]->atttypid);
1311 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1313 ReleaseSysCache(typeTup);
1318 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1320 if (arg->is_rowtype > 0)
1321 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1322 arg->is_rowtype = 0;
1323 PLy_output_datum_func2(&(arg->out.d), typeTup);
1327 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1329 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1331 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1332 arg->typioparam = getTypeIOParam(typeTup);
1333 arg->typbyval = typeStruct->typbyval;
1337 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1339 if (arg->is_rowtype > 0)
1340 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1341 arg->is_rowtype = 0;
1342 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1346 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1348 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1350 /* Get the type's conversion information */
1351 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1352 arg->typioparam = getTypeIOParam(typeTup);
1353 arg->typbyval = typeStruct->typbyval;
1355 /* Determine which kind of Python object we will convert to */
1359 arg->func = PLyBool_FromString;
1364 arg->func = PLyFloat_FromString;
1368 arg->func = PLyInt_FromString;
1371 arg->func = PLyLong_FromString;
1374 arg->func = PLyString_FromString;
1380 PLy_typeinfo_init(PLyTypeInfo * arg)
1382 arg->is_rowtype = -1;
1383 arg->in.r.natts = arg->out.r.natts = 0;
1384 arg->in.r.atts = NULL;
1385 arg->out.r.atts = NULL;
1389 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1391 if (arg->is_rowtype == 1)
1394 PLy_free(arg->in.r.atts);
1395 if (arg->out.r.atts)
1396 PLy_free(arg->out.r.atts);
1400 /* assumes that a bool is always returned as a 't' or 'f' */
1402 PLyBool_FromString(const char *src)
1405 return PyInt_FromLong(1);
1406 return PyInt_FromLong(0);
1410 PLyFloat_FromString(const char *src)
1416 v = strtod(src, &eptr);
1417 if (*eptr != '\0' || errno)
1419 return PyFloat_FromDouble(v);
1423 PLyInt_FromString(const char *src)
1429 v = strtol(src, &eptr, 0);
1430 if (*eptr != '\0' || errno)
1432 return PyInt_FromLong(v);
1436 PLyLong_FromString(const char *src)
1438 return PyLong_FromString((char *) src, NULL, 0);
1442 PLyString_FromString(const char *src)
1444 return PyString_FromString(src);
1448 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1450 PyObject *volatile dict;
1453 if (info->is_rowtype != 1)
1454 elog(ERROR, "PLyTypeInfo structure describes a datum");
1456 dict = PyDict_New();
1458 PLy_elog(ERROR, "could not create tuple dictionary");
1462 for (i = 0; i < info->in.r.natts; i++)
1471 if (desc->attrs[i]->attisdropped)
1474 key = NameStr(desc->attrs[i]->attname);
1475 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1477 if (is_null || info->in.r.atts[i].func == NULL)
1478 PyDict_SetItemString(dict, key, Py_None);
1481 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1483 ObjectIdGetDatum(info->in.r.atts[i].typioparam),
1484 Int32GetDatum(desc->attrs[i]->atttypmod));
1485 vsrc = DatumGetCString(vdat);
1488 * no exceptions allowed
1490 value = info->in.r.atts[i].func(vsrc);
1492 PyDict_SetItemString(dict, key, value);
1507 /* initialization, some python variables function declared here */
1509 /* interface to postgresql elog */
1510 static PyObject *PLy_debug(PyObject *, PyObject *);
1511 static PyObject *PLy_log(PyObject *, PyObject *);
1512 static PyObject *PLy_info(PyObject *, PyObject *);
1513 static PyObject *PLy_notice(PyObject *, PyObject *);
1514 static PyObject *PLy_warning(PyObject *, PyObject *);
1515 static PyObject *PLy_error(PyObject *, PyObject *);
1516 static PyObject *PLy_fatal(PyObject *, PyObject *);
1518 /* PLyPlanObject, PLyResultObject and SPI interface */
1519 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1520 static PyObject *PLy_plan_new(void);
1521 static void PLy_plan_dealloc(PyObject *);
1522 static PyObject *PLy_plan_getattr(PyObject *, char *);
1523 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1525 static PyObject *PLy_result_new(void);
1526 static void PLy_result_dealloc(PyObject *);
1527 static PyObject *PLy_result_getattr(PyObject *, char *);
1528 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1529 static PyObject *PLy_result_status(PyObject *, PyObject *);
1530 static int PLy_result_length(PyObject *);
1531 static PyObject *PLy_result_item(PyObject *, int);
1532 static PyObject *PLy_result_slice(PyObject *, int, int);
1533 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1534 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1537 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1538 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1539 static PyObject *PLy_spi_execute_query(char *query, long limit);
1540 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1541 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1544 static PyTypeObject PLy_PlanType = {
1545 PyObject_HEAD_INIT(NULL)
1547 "PLyPlan", /* tp_name */
1548 sizeof(PLyPlanObject), /* tp_size */
1549 0, /* tp_itemsize */
1554 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1556 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1560 0, /* tp_as_number */
1561 0, /* tp_as_sequence */
1562 0, /* tp_as_mapping */
1566 0, /* tp_getattro */
1567 0, /* tp_setattro */
1568 0, /* tp_as_buffer */
1570 PLy_plan_doc, /* tp_doc */
1573 static PyMethodDef PLy_plan_methods[] = {
1574 {"status", PLy_plan_status, METH_VARARGS, NULL},
1575 {NULL, NULL, 0, NULL}
1579 static PySequenceMethods PLy_result_as_sequence = {
1580 (inquiry) PLy_result_length, /* sq_length */
1581 (binaryfunc) 0, /* sq_concat */
1582 (intargfunc) 0, /* sq_repeat */
1583 (intargfunc) PLy_result_item, /* sq_item */
1584 (intintargfunc) PLy_result_slice, /* sq_slice */
1585 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1586 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1589 static PyTypeObject PLy_ResultType = {
1590 PyObject_HEAD_INIT(NULL)
1592 "PLyResult", /* tp_name */
1593 sizeof(PLyResultObject), /* tp_size */
1594 0, /* tp_itemsize */
1599 (destructor) PLy_result_dealloc, /* tp_dealloc */
1601 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1605 0, /* tp_as_number */
1606 &PLy_result_as_sequence, /* tp_as_sequence */
1607 0, /* tp_as_mapping */
1611 0, /* tp_getattro */
1612 0, /* tp_setattro */
1613 0, /* tp_as_buffer */
1615 PLy_result_doc, /* tp_doc */
1618 static PyMethodDef PLy_result_methods[] = {
1619 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
1620 {"status", PLy_result_status, METH_VARARGS, NULL},
1621 {NULL, NULL, 0, NULL}
1624 static PyMethodDef PLy_methods[] = {
1628 {"debug", PLy_debug, METH_VARARGS, NULL},
1629 {"log", PLy_log, METH_VARARGS, NULL},
1630 {"info", PLy_info, METH_VARARGS, NULL},
1631 {"notice", PLy_notice, METH_VARARGS, NULL},
1632 {"warning", PLy_warning, METH_VARARGS, NULL},
1633 {"error", PLy_error, METH_VARARGS, NULL},
1634 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1637 * create a stored plan
1639 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1642 * execute a plan or query
1644 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1646 {NULL, NULL, 0, NULL}
1650 /* plan object methods */
1656 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1664 return (PyObject *) ob;
1669 PLy_plan_dealloc(PyObject * arg)
1671 PLyPlanObject *ob = (PLyPlanObject *) arg;
1674 SPI_freeplan(ob->plan);
1676 PLy_free(ob->types);
1681 for (i = 0; i < ob->nargs; i++)
1682 PLy_typeinfo_dealloc(&ob->args[i]);
1691 PLy_plan_getattr(PyObject * self, char *name)
1693 return Py_FindMethod(PLy_plan_methods, self, name);
1697 PLy_plan_status(PyObject * self, PyObject * args)
1699 if (PyArg_ParseTuple(args, ""))
1703 /* return PyInt_FromLong(self->status); */
1705 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1711 /* result object methods */
1714 PLy_result_new(void)
1716 PLyResultObject *ob;
1718 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1721 /* ob->tuples = NULL; */
1724 ob->status = Py_None;
1725 ob->nrows = PyInt_FromLong(-1);
1726 ob->rows = PyList_New(0);
1728 return (PyObject *) ob;
1732 PLy_result_dealloc(PyObject * arg)
1734 PLyResultObject *ob = (PLyResultObject *) arg;
1736 Py_XDECREF(ob->nrows);
1737 Py_XDECREF(ob->rows);
1738 Py_XDECREF(ob->status);
1744 PLy_result_getattr(PyObject * self, char *name)
1746 return Py_FindMethod(PLy_result_methods, self, name);
1750 PLy_result_nrows(PyObject * self, PyObject * args)
1752 PLyResultObject *ob = (PLyResultObject *) self;
1754 Py_INCREF(ob->nrows);
1759 PLy_result_status(PyObject * self, PyObject * args)
1761 PLyResultObject *ob = (PLyResultObject *) self;
1763 Py_INCREF(ob->status);
1768 PLy_result_length(PyObject * arg)
1770 PLyResultObject *ob = (PLyResultObject *) arg;
1772 return PyList_Size(ob->rows);
1776 PLy_result_item(PyObject * arg, int idx)
1779 PLyResultObject *ob = (PLyResultObject *) arg;
1781 rv = PyList_GetItem(ob->rows, idx);
1788 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1791 PLyResultObject *ob = (PLyResultObject *) arg;
1794 rv = PyList_SetItem(ob->rows, idx, item);
1799 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1802 PLyResultObject *ob = (PLyResultObject *) arg;
1804 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1812 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1815 PLyResultObject *ob = (PLyResultObject *) arg;
1817 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1823 PLy_spi_prepare(PyObject * self, PyObject * args)
1825 PLyPlanObject *plan;
1826 PyObject *list = NULL;
1827 PyObject *volatile optr = NULL;
1830 MemoryContext oldcontext;
1832 /* Can't execute more if we have an unhandled error */
1833 if (PLy_error_in_progress)
1835 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1839 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1841 PyErr_SetString(PLy_exc_spi_error,
1842 "Invalid arguments for plpy.prepare()");
1846 if (list && (!PySequence_Check(list)))
1848 PyErr_SetString(PLy_exc_spi_error,
1849 "Second argument in plpy.prepare() must be a sequence");
1853 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1856 oldcontext = CurrentMemoryContext;
1864 nargs = PySequence_Length(list);
1867 plan->nargs = nargs;
1868 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1869 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1870 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1873 * the other loop might throw an exception, if PLyTypeInfo
1874 * member isn't properly initialized the Py_DECREF(plan) will
1877 for (i = 0; i < nargs; i++)
1879 PLy_typeinfo_init(&plan->args[i]);
1880 plan->values[i] = PointerGetDatum(NULL);
1883 for (i = 0; i < nargs; i++)
1887 Form_pg_type typeStruct;
1889 optr = PySequence_GetItem(list, i);
1890 if (!PyString_Check(optr))
1891 elog(ERROR, "Type names must be strings.");
1892 sptr = PyString_AsString(optr);
1895 * XXX should extend this to allow qualified type names
1897 typeTup = typenameType(makeTypeName(sptr));
1899 optr = NULL; /* this is important */
1901 plan->types[i] = HeapTupleGetOid(typeTup);
1902 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1903 if (typeStruct->typtype != 'c')
1904 PLy_output_datum_func(&plan->args[i], typeTup);
1906 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
1907 ReleaseSysCache(typeTup);
1912 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1913 if (plan->plan == NULL)
1914 elog(ERROR, "SPI_prepare failed: %s",
1915 SPI_result_code_string(SPI_result));
1917 /* transfer plan from procCxt to topCxt */
1918 tmpplan = plan->plan;
1919 plan->plan = SPI_saveplan(tmpplan);
1920 SPI_freeplan(tmpplan);
1921 if (plan->plan == NULL)
1922 elog(ERROR, "SPI_saveplan failed: %s",
1923 SPI_result_code_string(SPI_result));
1927 MemoryContextSwitchTo(oldcontext);
1928 PLy_error_in_progress = CopyErrorData();
1932 if (!PyErr_Occurred())
1933 PyErr_SetString(PLy_exc_spi_error,
1934 "Unknown error in PLy_spi_prepare");
1935 /* XXX this oughta be replaced with errcontext mechanism */
1936 PLy_elog(WARNING, "in function %s:",
1937 PLy_procedure_name(PLy_curr_procedure));
1942 return (PyObject *) plan;
1945 /* execute(query="select * from foo", limit=5)
1946 * execute(plan=plan, values=(foo, bar), limit=5)
1949 PLy_spi_execute(PyObject * self, PyObject * args)
1953 PyObject *list = NULL;
1956 /* Can't execute more if we have an unhandled error */
1957 if (PLy_error_in_progress)
1959 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1963 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
1964 return PLy_spi_execute_query(query, limit);
1968 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
1969 is_PLyPlanObject(plan))
1970 return PLy_spi_execute_plan(plan, list, limit);
1972 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
1977 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
1982 PLyPlanObject *plan;
1983 MemoryContext oldcontext;
1987 if (!PySequence_Check(list) || PyString_Check(list))
1989 char *msg = "plpy.execute() takes a sequence as its second argument";
1991 PyErr_SetString(PLy_exc_spi_error, msg);
1994 nargs = PySequence_Length(list);
1999 plan = (PLyPlanObject *) ob;
2001 if (nargs != plan->nargs)
2004 PyObject *so = PyObject_Str(list);
2007 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2008 PLy_procedure_name(PLy_curr_procedure));
2009 sv = PyString_AsString(so);
2010 PLy_exception_set(PLy_exc_spi_error,
2011 "Expected sequence of %d arguments, got %d. %s",
2012 plan->nargs, nargs, sv);
2018 oldcontext = CurrentMemoryContext;
2021 char *nulls = palloc(nargs * sizeof(char));
2023 for (i = 0; i < nargs; i++)
2028 elem = PySequence_GetItem(list, i);
2029 if (elem != Py_None)
2031 so = PyObject_Str(elem);
2033 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2034 PLy_procedure_name(PLy_curr_procedure));
2039 char *sv = PyString_AsString(so);
2042 FunctionCall3(&(plan->args[i].out.d.typfunc),
2043 CStringGetDatum(sv),
2044 ObjectIdGetDatum(plan->args[i].out.d.typioparam),
2060 plan->values[i] = PointerGetDatum(NULL);
2065 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2066 PLy_curr_procedure->fn_readonly, limit);
2072 MemoryContextSwitchTo(oldcontext);
2073 PLy_error_in_progress = CopyErrorData();
2077 * cleanup plan->values array
2079 for (i = 0; i < nargs; i++)
2081 if (!plan->args[i].out.d.typbyval &&
2082 (plan->values[i] != PointerGetDatum(NULL)))
2084 pfree(DatumGetPointer(plan->values[i]));
2085 plan->values[i] = PointerGetDatum(NULL);
2089 if (!PyErr_Occurred())
2090 PyErr_SetString(PLy_exc_error,
2091 "Unknown error in PLy_spi_execute_plan");
2092 /* XXX this oughta be replaced with errcontext mechanism */
2093 PLy_elog(WARNING, "in function %s:",
2094 PLy_procedure_name(PLy_curr_procedure));
2099 for (i = 0; i < nargs; i++)
2101 if (!plan->args[i].out.d.typbyval &&
2102 (plan->values[i] != PointerGetDatum(NULL)))
2104 pfree(DatumGetPointer(plan->values[i]));
2105 plan->values[i] = PointerGetDatum(NULL);
2111 PLy_exception_set(PLy_exc_spi_error,
2112 "SPI_execute_plan failed: %s",
2113 SPI_result_code_string(rv));
2117 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2121 PLy_spi_execute_query(char *query, long limit)
2124 MemoryContext oldcontext;
2126 oldcontext = CurrentMemoryContext;
2129 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2133 MemoryContextSwitchTo(oldcontext);
2134 PLy_error_in_progress = CopyErrorData();
2136 if (!PyErr_Occurred())
2137 PyErr_SetString(PLy_exc_spi_error,
2138 "Unknown error in PLy_spi_execute_query");
2139 /* XXX this oughta be replaced with errcontext mechanism */
2140 PLy_elog(WARNING, "in function %s:",
2141 PLy_procedure_name(PLy_curr_procedure));
2148 PLy_exception_set(PLy_exc_spi_error,
2149 "SPI_execute failed: %s",
2150 SPI_result_code_string(rv));
2154 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2158 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2160 PLyResultObject *result;
2161 MemoryContext oldcontext;
2163 result = (PLyResultObject *) PLy_result_new();
2164 Py_DECREF(result->status);
2165 result->status = PyInt_FromLong(status);
2167 if (status == SPI_OK_UTILITY)
2169 Py_DECREF(result->nrows);
2170 result->nrows = PyInt_FromLong(0);
2172 else if (status != SPI_OK_SELECT)
2174 Py_DECREF(result->nrows);
2175 result->nrows = PyInt_FromLong(rows);
2182 PLy_typeinfo_init(&args);
2183 Py_DECREF(result->nrows);
2184 result->nrows = PyInt_FromLong(rows);
2186 oldcontext = CurrentMemoryContext;
2191 Py_DECREF(result->rows);
2192 result->rows = PyList_New(rows);
2194 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2195 for (i = 0; i < rows; i++)
2197 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2200 PyList_SetItem(result->rows, i, row);
2202 PLy_typeinfo_dealloc(&args);
2204 SPI_freetuptable(tuptable);
2209 MemoryContextSwitchTo(oldcontext);
2210 PLy_error_in_progress = CopyErrorData();
2212 if (!PyErr_Occurred())
2213 PyErr_SetString(PLy_exc_error,
2214 "Unknown error in PLy_spi_execute_fetch_result");
2216 PLy_typeinfo_dealloc(&args);
2222 return (PyObject *) result;
2227 * language handler and interpreter initialization
2231 * plpython_init() - Initialize everything that can be
2232 * safely initialized during postmaster
2235 * DO NOT make this static --- it has to be callable by preload
2240 static volatile bool init_active = false;
2242 /* Do initialization only once */
2243 if (!PLy_first_call)
2247 elog(FATAL, "initialization of language module failed");
2253 if (PyErr_Occurred())
2254 PLy_elog(FATAL, "untrapped error in initialization");
2255 PLy_procedure_cache = PyDict_New();
2256 if (PLy_procedure_cache == NULL)
2257 PLy_elog(ERROR, "could not create procedure cache");
2259 PLy_first_call = false;
2265 /* Execute postmaster-startup safe initialization */
2270 * Any other initialization that must be done each time a new backend
2271 * starts -- currently none
2276 PLy_init_interp(void)
2280 mainmod = PyImport_AddModule("__main__");
2281 if (mainmod == NULL || PyErr_Occurred())
2282 PLy_elog(ERROR, "could not import \"__main__\" module.");
2284 PLy_interp_globals = PyModule_GetDict(mainmod);
2285 PLy_interp_safe_globals = PyDict_New();
2286 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2288 if (PLy_interp_globals == NULL || PyErr_Occurred())
2289 PLy_elog(ERROR, "could not initialize globals");
2302 * initialize plpy module
2304 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2305 plpy = Py_InitModule("plpy", PLy_methods);
2306 plpy_dict = PyModule_GetDict(plpy);
2308 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2310 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2311 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2312 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2313 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2314 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2315 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2318 * initialize main module, and add plpy
2320 main_mod = PyImport_AddModule("__main__");
2321 main_dict = PyModule_GetDict(main_mod);
2322 plpy_mod = PyImport_AddModule("plpy");
2323 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2324 if (PyErr_Occurred())
2325 elog(ERROR, "could not init plpy");
2328 /* the python interface to the elog function
2329 * don't confuse these with PLy_elog
2331 static PyObject *PLy_output(int, PyObject *, PyObject *);
2334 PLy_debug(PyObject * self, PyObject * args)
2336 return PLy_output(DEBUG2, self, args);
2340 PLy_log(PyObject * self, PyObject * args)
2342 return PLy_output(LOG, self, args);
2346 PLy_info(PyObject * self, PyObject * args)
2348 return PLy_output(INFO, self, args);
2352 PLy_notice(PyObject * self, PyObject * args)
2354 return PLy_output(NOTICE, self, args);
2358 PLy_warning(PyObject * self, PyObject * args)
2360 return PLy_output(WARNING, self, args);
2364 PLy_error(PyObject * self, PyObject * args)
2366 return PLy_output(ERROR, self, args);
2370 PLy_fatal(PyObject * self, PyObject * args)
2372 return PLy_output(FATAL, self, args);
2377 PLy_output(volatile int level, PyObject * self, PyObject * args)
2381 MemoryContext oldcontext;
2383 so = PyObject_Str(args);
2384 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2387 sv = "Unable to parse error message in `plpy.elog'";
2390 oldcontext = CurrentMemoryContext;
2393 elog(level, "%s", sv);
2397 MemoryContextSwitchTo(oldcontext);
2398 PLy_error_in_progress = CopyErrorData();
2403 * returning NULL here causes the python interpreter to bail. when
2404 * control passes back to PLy_procedure_call, we check for PG
2405 * exceptions and re-throw the error.
2407 PyErr_SetString(PLy_exc_error, sv);
2415 * return a legal object so the interpreter will continue on its merry way
2423 * Get the name of the last procedure called by the backend (the
2424 * innermost, if a plpython procedure call calls the backend and the
2425 * backend calls another plpython procedure).
2427 * NB: this returns the SQL name, not the internal Python procedure name
2430 PLy_procedure_name(PLyProcedure * proc)
2433 return "<unknown procedure>";
2434 return proc->proname;
2437 /* output a python traceback/exception via the postgresql elog
2438 * function. not pretty.
2441 PLy_exception_set(PyObject * exc, const char *fmt,...)
2447 vsnprintf(buf, sizeof(buf), fmt, ap);
2450 PyErr_SetString(exc, buf);
2453 /* Emit a PG error or notice, together with any available info about the
2454 * current Python error. This should be used to propagate Python errors
2458 PLy_elog(int elevel, const char *fmt,...)
2465 xmsg = PLy_traceback(&xlevel);
2468 emsg = PLy_vprintf(fmt, ap);
2474 (errmsg("plpython: %s", emsg),
2475 (xmsg) ? errdetail("%s", xmsg) : 0));
2492 PLy_traceback(int *xlevel)
2504 * get the current exception
2506 PyErr_Fetch(&e, &v, &tb);
2509 * oops, no exception, return
2517 PyErr_NormalizeException(&e, &v, &tb);
2519 eob = PyObject_Str(e);
2520 if (v && ((vob = PyObject_Str(v)) != NULL))
2521 vstr = PyString_AsString(vob);
2526 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
2527 * because that function calls us, so we could end up with infinite
2528 * recursion. I'm not even sure if eob could be NULL here -- would an
2529 * Assert() be more appropriate?
2531 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
2532 xstr = PLy_printf("%s: %s", estr, vstr);
2538 * intuit an appropriate error level for based on the exception type
2540 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
2542 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
2551 PLy_printf(const char *fmt,...)
2557 emsg = PLy_vprintf(fmt, ap);
2563 PLy_vprintf(const char *fmt, va_list ap)
2570 blen = strlen(fmt) * 2;
2573 buf = PLy_malloc(blen * sizeof(char));
2577 bchar = vsnprintf(buf, blen, fmt, ap);
2578 if (bchar > 0 && bchar < blen)
2586 buf = PLy_realloc(buf, blen);
2592 /* python module code */
2594 /* some dumb utility functions */
2596 PLy_malloc(size_t bytes)
2598 void *ptr = malloc(bytes);
2602 (errcode(ERRCODE_OUT_OF_MEMORY),
2603 errmsg("out of memory")));
2608 PLy_realloc(void *optr, size_t bytes)
2610 void *nptr = realloc(optr, bytes);
2614 (errcode(ERRCODE_OUT_OF_MEMORY),
2615 errmsg("out of memory")));
2620 PLy_strdup(const char *str)
2625 len = strlen(str) + 1;
2626 result = PLy_malloc(len);
2627 memcpy(result, str, len);
2632 /* define this away */