1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.80 2006/05/26 19:23:09 adunstan Exp $
6 *********************************************************************
16 /* postgreSQL stuff */
17 #include "access/heapam.h"
18 #include "catalog/pg_proc.h"
19 #include "catalog/pg_type.h"
20 #include "commands/trigger.h"
21 #include "executor/spi.h"
23 #include "nodes/makefuncs.h"
24 #include "parser/parse_type.h"
25 #include "tcop/tcopprot.h"
26 #include "utils/builtins.h"
27 #include "utils/lsyscache.h"
28 #include "utils/memutils.h"
29 #include "utils/syscache.h"
30 #include "utils/typcache.h"
35 /* convert Postgresql Datum or tuple into a PyObject.
36 * input to Python. Tuples are converted to dictionary
40 typedef PyObject *(*PLyDatumToObFunc) (const char *);
42 typedef struct PLyDatumToOb
44 PLyDatumToObFunc func;
50 typedef struct PLyTupleToOb
56 typedef union PLyTypeInput
62 /* convert PyObject to a Postgresql Datum or tuple.
65 typedef struct PLyObToDatum
67 FmgrInfo typfunc; /* The type's input function */
68 Oid typoid; /* The OID of the type */
73 typedef struct PLyObToTuple
79 typedef union PLyTypeOutput
85 /* all we need to move Postgresql data to Python objects,
88 typedef struct PLyTypeInfo
95 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
96 * 1 rowtype 2 rowtype, but I/O functions not set up yet
101 /* cached procedure data */
102 typedef struct PLyProcedure
104 char *proname; /* SQL name of procedure */
105 char *pyname; /* Python name of procedure */
106 TransactionId fn_xmin;
109 PLyTypeInfo result; /* also used to store info for trigger tuple
111 PLyTypeInfo args[FUNC_MAX_ARGS];
113 PyObject *code; /* compiled procedure code */
114 PyObject *statics; /* data saved across calls, local scope */
115 PyObject *globals; /* data saved across calls, global scope */
116 PyObject *me; /* PyCObject containing pointer to this
122 typedef struct PLyPlanObject
125 void *plan; /* return of an SPI_saveplan */
132 typedef struct PLyResultObject
135 /* HeapTuple *tuples; */
136 PyObject *nrows; /* number of rows returned by query */
137 PyObject *rows; /* data rows, or None if no data returned */
138 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
142 /* function declarations */
144 /* Two exported functions: first is the magic telling Postgresql
145 * what function call interface it implements. Second allows
146 * preinitialization of the interpreter during postmaster startup.
148 Datum plpython_call_handler(PG_FUNCTION_ARGS);
149 void plpython_init(void);
151 PG_FUNCTION_INFO_V1(plpython_call_handler);
153 /* most of the remaining of the declarations, all static */
155 /* these should only be called once at the first call
156 * of plpython_call_handler. initialize the python interpreter
159 static void PLy_init_all(void);
160 static void PLy_init_interp(void);
161 static void PLy_init_plpy(void);
163 /* call PyErr_SetString with a vprint interface */
165 PLy_exception_set(PyObject *, const char *,...)
166 __attribute__((format(printf, 2, 3)));
168 /* Get the innermost python procedure called from the backend */
169 static char *PLy_procedure_name(PLyProcedure *);
171 /* some utility functions */
172 static void PLy_elog(int, const char *,...);
173 static char *PLy_traceback(int *);
174 static char *PLy_vprintf(const char *fmt, va_list ap);
175 static char *PLy_printf(const char *fmt,...);
177 static void *PLy_malloc(size_t);
178 static void *PLy_realloc(void *, size_t);
179 static char *PLy_strdup(const char *);
180 static void PLy_free(void *);
182 /* sub handlers for functions and triggers */
183 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
184 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
186 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
187 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
189 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
190 TriggerData *, HeapTuple);
192 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
194 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
197 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
199 HeapTuple procTup, char *key);
201 static void PLy_procedure_compile(PLyProcedure *, const char *);
202 static char *PLy_procedure_munge_source(const char *, const char *);
203 static void PLy_procedure_delete(PLyProcedure *);
205 static void PLy_typeinfo_init(PLyTypeInfo *);
206 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
207 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
208 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
209 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
210 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
211 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
212 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
214 /* conversion functions */
215 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
216 static PyObject *PLyBool_FromString(const char *);
217 static PyObject *PLyFloat_FromString(const char *);
218 static PyObject *PLyInt_FromString(const char *);
219 static PyObject *PLyLong_FromString(const char *);
220 static PyObject *PLyString_FromString(const char *);
224 static bool PLy_first_call = true;
227 * Currently active plpython function
229 static PLyProcedure *PLy_curr_procedure = NULL;
232 * When a callback from Python into PG incurs an error, we temporarily store
233 * the error information here, and return NULL to the Python interpreter.
234 * Any further callback attempts immediately fail, and when the Python
235 * interpreter returns to the calling function, we re-throw the error (even if
236 * Python thinks it trapped the error and doesn't return NULL). Eventually
237 * this ought to be improved to let Python code really truly trap the error,
238 * but that's more of a change from the pre-8.0 semantics than I have time for
239 * now --- it will only be possible if the callback query is executed inside a
242 static ErrorData *PLy_error_in_progress = NULL;
244 static PyObject *PLy_interp_globals = NULL;
245 static PyObject *PLy_interp_safe_globals = NULL;
246 static PyObject *PLy_procedure_cache = NULL;
248 /* Python exceptions */
249 static PyObject *PLy_exc_error = NULL;
250 static PyObject *PLy_exc_fatal = NULL;
251 static PyObject *PLy_exc_spi_error = NULL;
253 /* some globals for the python module */
254 static char PLy_plan_doc[] = {
255 "Store a PostgreSQL plan"
258 static char PLy_result_doc[] = {
259 "Results of a PostgreSQL query"
264 * the function definitions
268 * This routine is a crock, and so is everyplace that calls it. The problem
269 * is that the cached form of plpython functions/queries is allocated permanently
270 * (mostly via malloc()) and never released until backend exit. Subsidiary
271 * data structures such as fmgr info records therefore must live forever
272 * as well. A better implementation would store all this stuff in a per-
273 * function memory context that could be reclaimed at need. In the meantime,
274 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
275 * it might allocate, and whatever the eventual function might allocate using
276 * fn_mcxt, will live forever too.
279 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
281 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
285 plpython_call_handler(PG_FUNCTION_ARGS)
288 PLyProcedure *save_curr_proc;
289 PLyProcedure *volatile proc = NULL;
293 if (SPI_connect() != SPI_OK_CONNECT)
294 elog(ERROR, "could not connect to SPI manager");
296 save_curr_proc = PLy_curr_procedure;
300 if (CALLED_AS_TRIGGER(fcinfo))
302 TriggerData *tdata = (TriggerData *) fcinfo->context;
305 proc = PLy_procedure_get(fcinfo,
306 RelationGetRelid(tdata->tg_relation));
307 PLy_curr_procedure = proc;
308 trv = PLy_trigger_handler(fcinfo, proc);
309 retval = PointerGetDatum(trv);
313 proc = PLy_procedure_get(fcinfo, InvalidOid);
314 PLy_curr_procedure = proc;
315 retval = PLy_function_handler(fcinfo, proc);
320 PLy_curr_procedure = save_curr_proc;
323 /* note: Py_DECREF needs braces around it, as of 2003/08 */
331 PLy_curr_procedure = save_curr_proc;
338 /* trigger and function sub handlers
340 * the python function is expected to return Py_None if the tuple is
341 * acceptable and unmodified. Otherwise it should return a PyString
342 * object who's value is SKIP, or MODIFY. SKIP means don't perform
343 * this action. MODIFY means the tuple has been modified, so update
344 * tuple and perform action. SKIP and MODIFY assume the trigger fires
345 * BEFORE the event and is ROW level. postgres expects the function
346 * to take no arguments and return an argument of type trigger.
349 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
352 PyObject *volatile plargs = NULL;
353 PyObject *volatile plrv = NULL;
357 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
358 plrv = PLy_procedure_call(proc, "TD", plargs);
360 Assert(plrv != NULL);
361 Assert(!PLy_error_in_progress);
364 * Disconnect from SPI manager
366 if (SPI_finish() != SPI_OK_FINISH)
367 elog(ERROR, "SPI_finish failed");
370 * return of None means we're happy with the tuple
376 if (!PyString_Check(plrv))
378 (errcode(ERRCODE_DATA_EXCEPTION),
379 errmsg("unexpected return value from trigger procedure"),
380 errdetail("Expected None or a String.")));
382 srv = PyString_AsString(plrv);
383 if (pg_strcasecmp(srv, "SKIP") == 0)
385 else if (pg_strcasecmp(srv, "MODIFY") == 0)
387 TriggerData *tdata = (TriggerData *) fcinfo->context;
389 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
390 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
391 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
393 elog(WARNING, "ignoring modified tuple in DELETE trigger");
395 else if (pg_strcasecmp(srv, "OK") != 0)
398 * accept "OK" as an alternative to None; otherwise,
402 (errcode(ERRCODE_DATA_EXCEPTION),
403 errmsg("unexpected return value from trigger procedure"),
404 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
424 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
427 PyObject *volatile plntup;
428 PyObject *volatile plkeys;
429 PyObject *volatile platt;
430 PyObject *volatile plval;
431 PyObject *volatile plstr;
437 int *volatile modattrs;
438 Datum *volatile modvalues;
439 char *volatile modnulls;
442 plntup = plkeys = platt = plval = plstr = NULL;
449 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
450 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
451 if (!PyDict_Check(plntup))
452 elog(ERROR, "TD[\"new\"] is not a dictionary object");
455 plkeys = PyDict_Keys(plntup);
456 natts = PyList_Size(plkeys);
458 modattrs = (int *) palloc(natts * sizeof(int));
459 modvalues = (Datum *) palloc(natts * sizeof(Datum));
460 modnulls = (char *) palloc(natts * sizeof(char));
462 tupdesc = tdata->tg_relation->rd_att;
464 for (i = 0; i < natts; i++)
468 platt = PyList_GetItem(plkeys, i);
469 if (!PyString_Check(platt))
470 elog(ERROR, "attribute name is not a string");
471 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
472 if (attn == SPI_ERROR_NOATTRIBUTE)
473 elog(ERROR, "invalid attribute \"%s\" in tuple",
474 PyString_AsString(platt));
477 plval = PyDict_GetItem(plntup, platt);
479 elog(FATAL, "python interpreter is probably corrupted");
485 if (tupdesc->attrs[atti]->attisdropped)
487 modvalues[i] = (Datum) 0;
490 else if (plval != Py_None)
492 plstr = PyObject_Str(plval);
494 PLy_elog(ERROR, "function \"%s\" could not modify tuple",
496 src = PyString_AsString(plstr);
499 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
501 proc->result.out.r.atts[atti].typioparam,
502 tupdesc->attrs[atti]->atttypmod);
511 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
513 proc->result.out.r.atts[atti].typioparam,
514 tupdesc->attrs[atti]->atttypmod);
522 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
523 modattrs, modvalues, modnulls);
525 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
556 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
558 TriggerData *tdata = (TriggerData *) fcinfo->context;
569 PyObject *volatile pltdata = NULL;
574 pltdata = PyDict_New();
576 PLy_elog(ERROR, "could not build arguments for trigger procedure");
578 pltname = PyString_FromString(tdata->tg_trigger->tgname);
579 PyDict_SetItemString(pltdata, "name", pltname);
582 stroid = DatumGetCString(DirectFunctionCall1(oidout,
583 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
584 pltrelid = PyString_FromString(stroid);
585 PyDict_SetItemString(pltdata, "relid", pltrelid);
589 stroid = SPI_getrelname(tdata->tg_relation);
590 plttablename = PyString_FromString(stroid);
591 PyDict_SetItemString(pltdata, "table_name", plttablename);
592 Py_DECREF(plttablename);
595 stroid = SPI_getnspname(tdata->tg_relation);
596 plttableschema = PyString_FromString(stroid);
597 PyDict_SetItemString(pltdata, "table_schema", plttableschema);
598 Py_DECREF(plttableschema);
602 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
603 pltwhen = PyString_FromString("BEFORE");
604 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
605 pltwhen = PyString_FromString("AFTER");
608 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
609 pltwhen = NULL; /* keep compiler quiet */
611 PyDict_SetItemString(pltdata, "when", pltwhen);
614 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
616 pltlevel = PyString_FromString("ROW");
617 PyDict_SetItemString(pltdata, "level", pltlevel);
620 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
622 pltevent = PyString_FromString("INSERT");
624 PyDict_SetItemString(pltdata, "old", Py_None);
625 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
626 tdata->tg_relation->rd_att);
627 PyDict_SetItemString(pltdata, "new", pytnew);
629 *rv = tdata->tg_trigtuple;
631 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
633 pltevent = PyString_FromString("DELETE");
635 PyDict_SetItemString(pltdata, "new", Py_None);
636 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
637 tdata->tg_relation->rd_att);
638 PyDict_SetItemString(pltdata, "old", pytold);
640 *rv = tdata->tg_trigtuple;
642 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
644 pltevent = PyString_FromString("UPDATE");
646 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
647 tdata->tg_relation->rd_att);
648 PyDict_SetItemString(pltdata, "new", pytnew);
650 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
651 tdata->tg_relation->rd_att);
652 PyDict_SetItemString(pltdata, "old", pytold);
654 *rv = tdata->tg_newtuple;
658 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
659 pltevent = NULL; /* keep compiler quiet */
662 PyDict_SetItemString(pltdata, "event", pltevent);
665 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
667 pltlevel = PyString_FromString("STATEMENT");
668 PyDict_SetItemString(pltdata, "level", pltlevel);
671 PyDict_SetItemString(pltdata, "old", Py_None);
672 PyDict_SetItemString(pltdata, "new", Py_None);
675 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
676 pltevent = PyString_FromString("INSERT");
677 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
678 pltevent = PyString_FromString("DELETE");
679 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
680 pltevent = PyString_FromString("UPDATE");
683 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
684 pltevent = NULL; /* keep compiler quiet */
687 PyDict_SetItemString(pltdata, "event", pltevent);
691 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
693 if (tdata->tg_trigger->tgnargs)
701 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
702 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
704 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
707 * stolen, don't Py_DECREF
709 PyList_SetItem(pltargs, i, pltarg);
717 PyDict_SetItemString(pltdata, "args", pltargs);
732 /* function handler and friends */
734 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
737 PyObject *volatile plargs = NULL;
738 PyObject *volatile plrv = NULL;
739 PyObject *volatile plrv_so = NULL;
744 plargs = PLy_function_build_args(fcinfo, proc);
745 plrv = PLy_procedure_call(proc, "args", plargs);
747 Assert(plrv != NULL);
748 Assert(!PLy_error_in_progress);
751 * Disconnect from SPI manager and then create the return values datum
752 * (if the input function does a palloc for it this must not be
753 * allocated in the SPI memory context because SPI_finish would free
756 if (SPI_finish() != SPI_OK_FINISH)
757 elog(ERROR, "SPI_finish failed");
760 * If the function is declared to return void, the Python
761 * return value must be None. For void-returning functions, we
762 * also treat a None return value as a special "void datum"
763 * rather than NULL (as is the case for non-void-returning
766 if (proc->result.out.d.typoid == VOIDOID)
770 (errcode(ERRCODE_DATATYPE_MISMATCH),
771 errmsg("invalid return value from plpython function"),
772 errdetail("Functions returning type \"void\" must return None.")));
774 fcinfo->isnull = false;
777 else if (plrv == Py_None)
779 fcinfo->isnull = true;
780 rv = InputFunctionCall(&proc->result.out.d.typfunc,
782 proc->result.out.d.typioparam,
787 fcinfo->isnull = false;
788 plrv_so = PyObject_Str(plrv);
790 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
791 plrv_sc = PyString_AsString(plrv_so);
792 rv = InputFunctionCall(&proc->result.out.d.typfunc,
794 proc->result.out.d.typioparam,
816 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
820 PyDict_SetItemString(proc->globals, kargs, vargs);
821 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
822 proc->globals, proc->globals);
825 * If there was an error in a PG callback, propagate that no matter what
826 * Python claims about its success.
828 if (PLy_error_in_progress)
830 ErrorData *edata = PLy_error_in_progress;
832 PLy_error_in_progress = NULL;
836 if (rv == NULL || PyErr_Occurred())
839 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
846 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
848 PyObject *volatile arg = NULL;
849 PyObject *volatile args = NULL;
854 args = PyList_New(proc->nargs);
855 for (i = 0; i < proc->nargs; i++)
857 if (proc->args[i].is_rowtype > 0)
859 if (fcinfo->argnull[i])
867 HeapTupleData tmptup;
869 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
870 /* Extract rowtype info and find a tupdesc */
871 tupType = HeapTupleHeaderGetTypeId(td);
872 tupTypmod = HeapTupleHeaderGetTypMod(td);
873 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
875 /* Set up I/O funcs if not done yet */
876 if (proc->args[i].is_rowtype != 1)
877 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
879 /* Build a temporary HeapTuple control structure */
880 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
883 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
888 if (fcinfo->argnull[i])
894 ct = OutputFunctionCall(&(proc->args[i].in.d.typfunc),
896 arg = (proc->args[i].in.d.func) (ct);
908 * FIXME -- error check this
910 PyList_SetItem(args, i, arg);
928 * PLyProcedure functions
931 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
932 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
933 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
936 static PLyProcedure *
937 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
943 PLyProcedure *proc = NULL;
946 fn_oid = fcinfo->flinfo->fn_oid;
947 procTup = SearchSysCache(PROCOID,
948 ObjectIdGetDatum(fn_oid),
950 if (!HeapTupleIsValid(procTup))
951 elog(ERROR, "cache lookup failed for function %u", fn_oid);
953 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
954 if (rv >= sizeof(key) || rv < 0)
955 elog(ERROR, "key too long");
957 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
962 if (!PyCObject_Check(plproc))
963 elog(FATAL, "expected a PyCObject, didn't get one");
965 proc = PyCObject_AsVoidPtr(plproc);
966 if (proc->me != plproc)
967 elog(FATAL, "proc->me != plproc");
968 /* did we find an up-to-date cache entry? */
969 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
970 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
978 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
980 ReleaseSysCache(procTup);
985 static PLyProcedure *
986 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
987 HeapTuple procTup, char *key)
989 char procName[NAMEDATALEN + 256];
990 Form_pg_proc procStruct;
991 PLyProcedure *volatile proc;
992 char *volatile procSource = NULL;
998 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1000 if (OidIsValid(tgreloid))
1001 rv = snprintf(procName, sizeof(procName),
1002 "__plpython_procedure_%s_%u_trigger_%u",
1003 NameStr(procStruct->proname),
1004 fcinfo->flinfo->fn_oid,
1007 rv = snprintf(procName, sizeof(procName),
1008 "__plpython_procedure_%s_%u",
1009 NameStr(procStruct->proname),
1010 fcinfo->flinfo->fn_oid);
1011 if (rv >= sizeof(procName) || rv < 0)
1012 elog(ERROR, "procedure name would overrun buffer");
1014 proc = PLy_malloc(sizeof(PLyProcedure));
1015 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1016 proc->pyname = PLy_strdup(procName);
1017 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1018 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1019 /* Remember if function is STABLE/IMMUTABLE */
1021 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1022 PLy_typeinfo_init(&proc->result);
1023 for (i = 0; i < FUNC_MAX_ARGS; i++)
1024 PLy_typeinfo_init(&proc->args[i]);
1026 proc->code = proc->statics = NULL;
1027 proc->globals = proc->me = NULL;
1032 * get information required for output conversion of the return value,
1033 * but only if this isn't a trigger.
1035 if (!CALLED_AS_TRIGGER(fcinfo))
1037 HeapTuple rvTypeTup;
1038 Form_pg_type rvTypeStruct;
1040 rvTypeTup = SearchSysCache(TYPEOID,
1041 ObjectIdGetDatum(procStruct->prorettype),
1043 if (!HeapTupleIsValid(rvTypeTup))
1044 elog(ERROR, "cache lookup failed for type %u",
1045 procStruct->prorettype);
1046 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1048 /* Disallow pseudotype result, except for void */
1049 if (rvTypeStruct->typtype == 'p' &&
1050 procStruct->prorettype != VOIDOID)
1052 if (procStruct->prorettype == TRIGGEROID)
1054 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1055 errmsg("trigger functions may only be called as triggers")));
1058 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1059 errmsg("plpython functions cannot return type %s",
1060 format_type_be(procStruct->prorettype))));
1063 if (rvTypeStruct->typtype == 'c')
1065 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1066 errmsg("plpython functions cannot return tuples yet")));
1068 PLy_output_datum_func(&proc->result, rvTypeTup);
1070 ReleaseSysCache(rvTypeTup);
1075 * input/output conversion for trigger tuples. use the result
1076 * TypeInfo variable to store the tuple conversion info.
1078 TriggerData *tdata = (TriggerData *) fcinfo->context;
1080 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1081 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1085 * now get information required for input conversion of the procedure's
1088 proc->nargs = fcinfo->nargs;
1089 for (i = 0; i < fcinfo->nargs; i++)
1091 HeapTuple argTypeTup;
1092 Form_pg_type argTypeStruct;
1094 argTypeTup = SearchSysCache(TYPEOID,
1095 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1097 if (!HeapTupleIsValid(argTypeTup))
1098 elog(ERROR, "cache lookup failed for type %u",
1099 procStruct->proargtypes.values[i]);
1100 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1102 /* Disallow pseudotype argument */
1103 if (argTypeStruct->typtype == 'p')
1105 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1106 errmsg("plpython functions cannot take type %s",
1107 format_type_be(procStruct->proargtypes.values[i]))));
1109 if (argTypeStruct->typtype != 'c')
1110 PLy_input_datum_func(&(proc->args[i]),
1111 procStruct->proargtypes.values[i],
1114 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1116 ReleaseSysCache(argTypeTup);
1121 * get the text of the function.
1123 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1124 Anum_pg_proc_prosrc, &isnull);
1126 elog(ERROR, "null prosrc");
1127 procSource = DatumGetCString(DirectFunctionCall1(textout,
1130 PLy_procedure_compile(proc, procSource);
1134 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1135 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1139 PLy_procedure_delete(proc);
1151 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1153 PyObject *crv = NULL;
1156 proc->globals = PyDict_Copy(PLy_interp_globals);
1159 * SD is private preserved data between calls. GD is global data
1160 * shared by all functions
1162 proc->statics = PyDict_New();
1163 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1166 * insert the function code into the interpreter
1168 msrc = PLy_procedure_munge_source(proc->pyname, src);
1169 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1172 if (crv != NULL && (!PyErr_Occurred()))
1175 char call[NAMEDATALEN + 256];
1180 * compile a call to the function
1182 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1183 if (clen < 0 || clen >= sizeof(call))
1184 elog(ERROR, "string would overflow buffer");
1185 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1186 if (proc->code != NULL && (!PyErr_Occurred()))
1192 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1196 PLy_procedure_munge_source(const char *name, const char *src)
1205 * room for function source and the def statement
1207 mlen = (strlen(src) * 2) + strlen(name) + 16;
1209 mrc = PLy_malloc(mlen);
1210 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1211 Assert(plen >= 0 && plen < mlen);
1218 if (*sp == '\r' && *(sp + 1) == '\n')
1221 if (*sp == '\n' || *sp == '\r')
1234 if (mp > (mrc + mlen))
1235 elog(FATAL, "buffer overrun in PLy_munge_source");
1241 PLy_procedure_delete(PLyProcedure * proc)
1245 Py_XDECREF(proc->code);
1246 Py_XDECREF(proc->statics);
1247 Py_XDECREF(proc->globals);
1248 Py_XDECREF(proc->me);
1250 PLy_free(proc->proname);
1252 PLy_free(proc->pyname);
1253 for (i = 0; i < proc->nargs; i++)
1254 if (proc->args[i].is_rowtype == 1)
1256 if (proc->args[i].in.r.atts)
1257 PLy_free(proc->args[i].in.r.atts);
1258 if (proc->args[i].out.r.atts)
1259 PLy_free(proc->args[i].out.r.atts);
1263 /* conversion functions. remember output from python is
1264 * input to postgresql, and vis versa.
1267 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1271 if (arg->is_rowtype == 0)
1272 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1274 arg->is_rowtype = 1;
1275 arg->in.r.natts = desc->natts;
1276 arg->in.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1278 for (i = 0; i < desc->natts; i++)
1282 if (desc->attrs[i]->attisdropped)
1285 typeTup = SearchSysCache(TYPEOID,
1286 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1288 if (!HeapTupleIsValid(typeTup))
1289 elog(ERROR, "cache lookup failed for type %u",
1290 desc->attrs[i]->atttypid);
1292 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1293 desc->attrs[i]->atttypid,
1296 ReleaseSysCache(typeTup);
1301 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1305 if (arg->is_rowtype == 0)
1306 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1308 arg->is_rowtype = 1;
1309 arg->out.r.natts = desc->natts;
1310 arg->out.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1312 for (i = 0; i < desc->natts; i++)
1316 if (desc->attrs[i]->attisdropped)
1319 typeTup = SearchSysCache(TYPEOID,
1320 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1322 if (!HeapTupleIsValid(typeTup))
1323 elog(ERROR, "cache lookup failed for type %u",
1324 desc->attrs[i]->atttypid);
1326 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1328 ReleaseSysCache(typeTup);
1333 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1335 if (arg->is_rowtype > 0)
1336 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1337 arg->is_rowtype = 0;
1338 PLy_output_datum_func2(&(arg->out.d), typeTup);
1342 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1344 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1346 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1347 arg->typoid = HeapTupleGetOid(typeTup);
1348 arg->typioparam = getTypeIOParam(typeTup);
1349 arg->typbyval = typeStruct->typbyval;
1353 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1355 if (arg->is_rowtype > 0)
1356 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1357 arg->is_rowtype = 0;
1358 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1362 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1364 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1366 /* Get the type's conversion information */
1367 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1368 arg->typioparam = getTypeIOParam(typeTup);
1369 arg->typbyval = typeStruct->typbyval;
1371 /* Determine which kind of Python object we will convert to */
1375 arg->func = PLyBool_FromString;
1380 arg->func = PLyFloat_FromString;
1384 arg->func = PLyInt_FromString;
1387 arg->func = PLyLong_FromString;
1390 arg->func = PLyString_FromString;
1396 PLy_typeinfo_init(PLyTypeInfo * arg)
1398 arg->is_rowtype = -1;
1399 arg->in.r.natts = arg->out.r.natts = 0;
1400 arg->in.r.atts = NULL;
1401 arg->out.r.atts = NULL;
1405 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1407 if (arg->is_rowtype == 1)
1410 PLy_free(arg->in.r.atts);
1411 if (arg->out.r.atts)
1412 PLy_free(arg->out.r.atts);
1416 /* assumes that a bool is always returned as a 't' or 'f' */
1418 PLyBool_FromString(const char *src)
1421 return PyInt_FromLong(1);
1422 return PyInt_FromLong(0);
1426 PLyFloat_FromString(const char *src)
1432 v = strtod(src, &eptr);
1433 if (*eptr != '\0' || errno)
1435 return PyFloat_FromDouble(v);
1439 PLyInt_FromString(const char *src)
1445 v = strtol(src, &eptr, 0);
1446 if (*eptr != '\0' || errno)
1448 return PyInt_FromLong(v);
1452 PLyLong_FromString(const char *src)
1454 return PyLong_FromString((char *) src, NULL, 0);
1458 PLyString_FromString(const char *src)
1460 return PyString_FromString(src);
1464 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1466 PyObject *volatile dict;
1469 if (info->is_rowtype != 1)
1470 elog(ERROR, "PLyTypeInfo structure describes a datum");
1472 dict = PyDict_New();
1474 PLy_elog(ERROR, "could not create tuple dictionary");
1478 for (i = 0; i < info->in.r.natts; i++)
1486 if (desc->attrs[i]->attisdropped)
1489 key = NameStr(desc->attrs[i]->attname);
1490 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1492 if (is_null || info->in.r.atts[i].func == NULL)
1493 PyDict_SetItemString(dict, key, Py_None);
1496 vsrc = OutputFunctionCall(&info->in.r.atts[i].typfunc,
1500 * no exceptions allowed
1502 value = info->in.r.atts[i].func(vsrc);
1504 PyDict_SetItemString(dict, key, value);
1519 /* initialization, some python variables function declared here */
1521 /* interface to postgresql elog */
1522 static PyObject *PLy_debug(PyObject *, PyObject *);
1523 static PyObject *PLy_log(PyObject *, PyObject *);
1524 static PyObject *PLy_info(PyObject *, PyObject *);
1525 static PyObject *PLy_notice(PyObject *, PyObject *);
1526 static PyObject *PLy_warning(PyObject *, PyObject *);
1527 static PyObject *PLy_error(PyObject *, PyObject *);
1528 static PyObject *PLy_fatal(PyObject *, PyObject *);
1530 /* PLyPlanObject, PLyResultObject and SPI interface */
1531 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1532 static PyObject *PLy_plan_new(void);
1533 static void PLy_plan_dealloc(PyObject *);
1534 static PyObject *PLy_plan_getattr(PyObject *, char *);
1535 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1537 static PyObject *PLy_result_new(void);
1538 static void PLy_result_dealloc(PyObject *);
1539 static PyObject *PLy_result_getattr(PyObject *, char *);
1540 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1541 static PyObject *PLy_result_status(PyObject *, PyObject *);
1542 static int PLy_result_length(PyObject *);
1543 static PyObject *PLy_result_item(PyObject *, int);
1544 static PyObject *PLy_result_slice(PyObject *, int, int);
1545 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1546 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1549 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1550 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1551 static PyObject *PLy_spi_execute_query(char *query, long limit);
1552 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1553 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1556 static PyTypeObject PLy_PlanType = {
1557 PyObject_HEAD_INIT(NULL)
1559 "PLyPlan", /* tp_name */
1560 sizeof(PLyPlanObject), /* tp_size */
1561 0, /* tp_itemsize */
1566 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1568 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1572 0, /* tp_as_number */
1573 0, /* tp_as_sequence */
1574 0, /* tp_as_mapping */
1578 0, /* tp_getattro */
1579 0, /* tp_setattro */
1580 0, /* tp_as_buffer */
1582 PLy_plan_doc, /* tp_doc */
1585 static PyMethodDef PLy_plan_methods[] = {
1586 {"status", PLy_plan_status, METH_VARARGS, NULL},
1587 {NULL, NULL, 0, NULL}
1591 static PySequenceMethods PLy_result_as_sequence = {
1592 (inquiry) PLy_result_length, /* sq_length */
1593 (binaryfunc) 0, /* sq_concat */
1594 (intargfunc) 0, /* sq_repeat */
1595 (intargfunc) PLy_result_item, /* sq_item */
1596 (intintargfunc) PLy_result_slice, /* sq_slice */
1597 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1598 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1601 static PyTypeObject PLy_ResultType = {
1602 PyObject_HEAD_INIT(NULL)
1604 "PLyResult", /* tp_name */
1605 sizeof(PLyResultObject), /* tp_size */
1606 0, /* tp_itemsize */
1611 (destructor) PLy_result_dealloc, /* tp_dealloc */
1613 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1617 0, /* tp_as_number */
1618 &PLy_result_as_sequence, /* tp_as_sequence */
1619 0, /* tp_as_mapping */
1623 0, /* tp_getattro */
1624 0, /* tp_setattro */
1625 0, /* tp_as_buffer */
1627 PLy_result_doc, /* tp_doc */
1630 static PyMethodDef PLy_result_methods[] = {
1631 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
1632 {"status", PLy_result_status, METH_VARARGS, NULL},
1633 {NULL, NULL, 0, NULL}
1636 static PyMethodDef PLy_methods[] = {
1640 {"debug", PLy_debug, METH_VARARGS, NULL},
1641 {"log", PLy_log, METH_VARARGS, NULL},
1642 {"info", PLy_info, METH_VARARGS, NULL},
1643 {"notice", PLy_notice, METH_VARARGS, NULL},
1644 {"warning", PLy_warning, METH_VARARGS, NULL},
1645 {"error", PLy_error, METH_VARARGS, NULL},
1646 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1649 * create a stored plan
1651 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1654 * execute a plan or query
1656 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1658 {NULL, NULL, 0, NULL}
1662 /* plan object methods */
1668 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1676 return (PyObject *) ob;
1681 PLy_plan_dealloc(PyObject * arg)
1683 PLyPlanObject *ob = (PLyPlanObject *) arg;
1686 SPI_freeplan(ob->plan);
1688 PLy_free(ob->types);
1693 for (i = 0; i < ob->nargs; i++)
1694 PLy_typeinfo_dealloc(&ob->args[i]);
1703 PLy_plan_getattr(PyObject * self, char *name)
1705 return Py_FindMethod(PLy_plan_methods, self, name);
1709 PLy_plan_status(PyObject * self, PyObject * args)
1711 if (PyArg_ParseTuple(args, ""))
1715 /* return PyInt_FromLong(self->status); */
1717 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1723 /* result object methods */
1726 PLy_result_new(void)
1728 PLyResultObject *ob;
1730 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1733 /* ob->tuples = NULL; */
1736 ob->status = Py_None;
1737 ob->nrows = PyInt_FromLong(-1);
1738 ob->rows = PyList_New(0);
1740 return (PyObject *) ob;
1744 PLy_result_dealloc(PyObject * arg)
1746 PLyResultObject *ob = (PLyResultObject *) arg;
1748 Py_XDECREF(ob->nrows);
1749 Py_XDECREF(ob->rows);
1750 Py_XDECREF(ob->status);
1756 PLy_result_getattr(PyObject * self, char *name)
1758 return Py_FindMethod(PLy_result_methods, self, name);
1762 PLy_result_nrows(PyObject * self, PyObject * args)
1764 PLyResultObject *ob = (PLyResultObject *) self;
1766 Py_INCREF(ob->nrows);
1771 PLy_result_status(PyObject * self, PyObject * args)
1773 PLyResultObject *ob = (PLyResultObject *) self;
1775 Py_INCREF(ob->status);
1780 PLy_result_length(PyObject * arg)
1782 PLyResultObject *ob = (PLyResultObject *) arg;
1784 return PyList_Size(ob->rows);
1788 PLy_result_item(PyObject * arg, int idx)
1791 PLyResultObject *ob = (PLyResultObject *) arg;
1793 rv = PyList_GetItem(ob->rows, idx);
1800 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1803 PLyResultObject *ob = (PLyResultObject *) arg;
1806 rv = PyList_SetItem(ob->rows, idx, item);
1811 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1814 PLyResultObject *ob = (PLyResultObject *) arg;
1816 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1824 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1827 PLyResultObject *ob = (PLyResultObject *) arg;
1829 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1835 PLy_spi_prepare(PyObject * self, PyObject * args)
1837 PLyPlanObject *plan;
1838 PyObject *list = NULL;
1839 PyObject *volatile optr = NULL;
1842 MemoryContext oldcontext;
1844 /* Can't execute more if we have an unhandled error */
1845 if (PLy_error_in_progress)
1847 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1851 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1853 PyErr_SetString(PLy_exc_spi_error,
1854 "Invalid arguments for plpy.prepare()");
1858 if (list && (!PySequence_Check(list)))
1860 PyErr_SetString(PLy_exc_spi_error,
1861 "Second argument in plpy.prepare() must be a sequence");
1865 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1868 oldcontext = CurrentMemoryContext;
1876 nargs = PySequence_Length(list);
1879 plan->nargs = nargs;
1880 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1881 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1882 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1885 * the other loop might throw an exception, if PLyTypeInfo
1886 * member isn't properly initialized the Py_DECREF(plan) will
1889 for (i = 0; i < nargs; i++)
1891 PLy_typeinfo_init(&plan->args[i]);
1892 plan->values[i] = PointerGetDatum(NULL);
1895 for (i = 0; i < nargs; i++)
1900 Form_pg_type typeStruct;
1902 optr = PySequence_GetItem(list, i);
1903 if (!PyString_Check(optr))
1904 elog(ERROR, "Type names must be strings.");
1905 sptr = PyString_AsString(optr);
1908 * Parse possibly-qualified type name and look it up in
1911 names = stringToQualifiedNameList(sptr,
1913 typeTup = typenameType(NULL,
1914 makeTypeNameFromNameList(names));
1916 optr = NULL; /* this is important */
1918 plan->types[i] = HeapTupleGetOid(typeTup);
1919 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1920 if (typeStruct->typtype != 'c')
1921 PLy_output_datum_func(&plan->args[i], typeTup);
1923 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
1924 ReleaseSysCache(typeTup);
1929 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1930 if (plan->plan == NULL)
1931 elog(ERROR, "SPI_prepare failed: %s",
1932 SPI_result_code_string(SPI_result));
1934 /* transfer plan from procCxt to topCxt */
1935 tmpplan = plan->plan;
1936 plan->plan = SPI_saveplan(tmpplan);
1937 SPI_freeplan(tmpplan);
1938 if (plan->plan == NULL)
1939 elog(ERROR, "SPI_saveplan failed: %s",
1940 SPI_result_code_string(SPI_result));
1944 MemoryContextSwitchTo(oldcontext);
1945 PLy_error_in_progress = CopyErrorData();
1949 if (!PyErr_Occurred())
1950 PyErr_SetString(PLy_exc_spi_error,
1951 "Unknown error in PLy_spi_prepare");
1952 /* XXX this oughta be replaced with errcontext mechanism */
1953 PLy_elog(WARNING, "in function %s:",
1954 PLy_procedure_name(PLy_curr_procedure));
1959 return (PyObject *) plan;
1962 /* execute(query="select * from foo", limit=5)
1963 * execute(plan=plan, values=(foo, bar), limit=5)
1966 PLy_spi_execute(PyObject * self, PyObject * args)
1970 PyObject *list = NULL;
1973 /* Can't execute more if we have an unhandled error */
1974 if (PLy_error_in_progress)
1976 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1980 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
1981 return PLy_spi_execute_query(query, limit);
1985 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
1986 is_PLyPlanObject(plan))
1987 return PLy_spi_execute_plan(plan, list, limit);
1989 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
1994 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
1999 PLyPlanObject *plan;
2000 MemoryContext oldcontext;
2004 if (!PySequence_Check(list) || PyString_Check(list))
2006 char *msg = "plpy.execute() takes a sequence as its second argument";
2008 PyErr_SetString(PLy_exc_spi_error, msg);
2011 nargs = PySequence_Length(list);
2016 plan = (PLyPlanObject *) ob;
2018 if (nargs != plan->nargs)
2021 PyObject *so = PyObject_Str(list);
2024 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2025 PLy_procedure_name(PLy_curr_procedure));
2026 sv = PyString_AsString(so);
2027 PLy_exception_set(PLy_exc_spi_error,
2028 "Expected sequence of %d arguments, got %d. %s",
2029 plan->nargs, nargs, sv);
2035 oldcontext = CurrentMemoryContext;
2038 char *nulls = palloc(nargs * sizeof(char));
2040 for (i = 0; i < nargs; i++)
2045 elem = PySequence_GetItem(list, i);
2046 if (elem != Py_None)
2048 so = PyObject_Str(elem);
2050 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2051 PLy_procedure_name(PLy_curr_procedure));
2056 char *sv = PyString_AsString(so);
2059 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2061 plan->args[i].out.d.typioparam,
2078 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2080 plan->args[i].out.d.typioparam,
2086 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2087 PLy_curr_procedure->fn_readonly, limit);
2093 MemoryContextSwitchTo(oldcontext);
2094 PLy_error_in_progress = CopyErrorData();
2098 * cleanup plan->values array
2100 for (i = 0; i < nargs; i++)
2102 if (!plan->args[i].out.d.typbyval &&
2103 (plan->values[i] != PointerGetDatum(NULL)))
2105 pfree(DatumGetPointer(plan->values[i]));
2106 plan->values[i] = PointerGetDatum(NULL);
2110 if (!PyErr_Occurred())
2111 PyErr_SetString(PLy_exc_error,
2112 "Unknown error in PLy_spi_execute_plan");
2113 /* XXX this oughta be replaced with errcontext mechanism */
2114 PLy_elog(WARNING, "in function %s:",
2115 PLy_procedure_name(PLy_curr_procedure));
2120 for (i = 0; i < nargs; i++)
2122 if (!plan->args[i].out.d.typbyval &&
2123 (plan->values[i] != PointerGetDatum(NULL)))
2125 pfree(DatumGetPointer(plan->values[i]));
2126 plan->values[i] = PointerGetDatum(NULL);
2132 PLy_exception_set(PLy_exc_spi_error,
2133 "SPI_execute_plan failed: %s",
2134 SPI_result_code_string(rv));
2138 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2142 PLy_spi_execute_query(char *query, long limit)
2145 MemoryContext oldcontext;
2147 oldcontext = CurrentMemoryContext;
2150 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2154 MemoryContextSwitchTo(oldcontext);
2155 PLy_error_in_progress = CopyErrorData();
2157 if (!PyErr_Occurred())
2158 PyErr_SetString(PLy_exc_spi_error,
2159 "Unknown error in PLy_spi_execute_query");
2160 /* XXX this oughta be replaced with errcontext mechanism */
2161 PLy_elog(WARNING, "in function %s:",
2162 PLy_procedure_name(PLy_curr_procedure));
2169 PLy_exception_set(PLy_exc_spi_error,
2170 "SPI_execute failed: %s",
2171 SPI_result_code_string(rv));
2175 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2179 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2181 PLyResultObject *result;
2182 MemoryContext oldcontext;
2184 result = (PLyResultObject *) PLy_result_new();
2185 Py_DECREF(result->status);
2186 result->status = PyInt_FromLong(status);
2188 if (status == SPI_OK_UTILITY)
2190 Py_DECREF(result->nrows);
2191 result->nrows = PyInt_FromLong(0);
2193 else if (status != SPI_OK_SELECT)
2195 Py_DECREF(result->nrows);
2196 result->nrows = PyInt_FromLong(rows);
2203 PLy_typeinfo_init(&args);
2204 Py_DECREF(result->nrows);
2205 result->nrows = PyInt_FromLong(rows);
2207 oldcontext = CurrentMemoryContext;
2212 Py_DECREF(result->rows);
2213 result->rows = PyList_New(rows);
2215 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2216 for (i = 0; i < rows; i++)
2218 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2221 PyList_SetItem(result->rows, i, row);
2223 PLy_typeinfo_dealloc(&args);
2225 SPI_freetuptable(tuptable);
2230 MemoryContextSwitchTo(oldcontext);
2231 PLy_error_in_progress = CopyErrorData();
2233 if (!PyErr_Occurred())
2234 PyErr_SetString(PLy_exc_error,
2235 "Unknown error in PLy_spi_execute_fetch_result");
2237 PLy_typeinfo_dealloc(&args);
2243 return (PyObject *) result;
2248 * language handler and interpreter initialization
2252 * plpython_init() - Initialize everything that can be
2253 * safely initialized during postmaster
2256 * DO NOT make this static --- it has to be callable by preload
2261 static volatile bool init_active = false;
2263 /* Do initialization only once */
2264 if (!PLy_first_call)
2268 elog(FATAL, "initialization of language module failed");
2274 if (PyErr_Occurred())
2275 PLy_elog(FATAL, "untrapped error in initialization");
2276 PLy_procedure_cache = PyDict_New();
2277 if (PLy_procedure_cache == NULL)
2278 PLy_elog(ERROR, "could not create procedure cache");
2280 PLy_first_call = false;
2286 /* Execute postmaster-startup safe initialization */
2291 * Any other initialization that must be done each time a new backend
2292 * starts -- currently none
2297 PLy_init_interp(void)
2301 mainmod = PyImport_AddModule("__main__");
2302 if (mainmod == NULL || PyErr_Occurred())
2303 PLy_elog(ERROR, "could not import \"__main__\" module.");
2305 PLy_interp_globals = PyModule_GetDict(mainmod);
2306 PLy_interp_safe_globals = PyDict_New();
2307 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2309 if (PLy_interp_globals == NULL || PyErr_Occurred())
2310 PLy_elog(ERROR, "could not initialize globals");
2323 * initialize plpy module
2325 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2326 plpy = Py_InitModule("plpy", PLy_methods);
2327 plpy_dict = PyModule_GetDict(plpy);
2329 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2331 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2332 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2333 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2334 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2335 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2336 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2339 * initialize main module, and add plpy
2341 main_mod = PyImport_AddModule("__main__");
2342 main_dict = PyModule_GetDict(main_mod);
2343 plpy_mod = PyImport_AddModule("plpy");
2344 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2345 if (PyErr_Occurred())
2346 elog(ERROR, "could not init plpy");
2349 /* the python interface to the elog function
2350 * don't confuse these with PLy_elog
2352 static PyObject *PLy_output(int, PyObject *, PyObject *);
2355 PLy_debug(PyObject * self, PyObject * args)
2357 return PLy_output(DEBUG2, self, args);
2361 PLy_log(PyObject * self, PyObject * args)
2363 return PLy_output(LOG, self, args);
2367 PLy_info(PyObject * self, PyObject * args)
2369 return PLy_output(INFO, self, args);
2373 PLy_notice(PyObject * self, PyObject * args)
2375 return PLy_output(NOTICE, self, args);
2379 PLy_warning(PyObject * self, PyObject * args)
2381 return PLy_output(WARNING, self, args);
2385 PLy_error(PyObject * self, PyObject * args)
2387 return PLy_output(ERROR, self, args);
2391 PLy_fatal(PyObject * self, PyObject * args)
2393 return PLy_output(FATAL, self, args);
2398 PLy_output(volatile int level, PyObject * self, PyObject * args)
2402 MemoryContext oldcontext;
2404 so = PyObject_Str(args);
2405 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2408 sv = "Unable to parse error message in `plpy.elog'";
2411 oldcontext = CurrentMemoryContext;
2414 elog(level, "%s", sv);
2418 MemoryContextSwitchTo(oldcontext);
2419 PLy_error_in_progress = CopyErrorData();
2424 * returning NULL here causes the python interpreter to bail. when
2425 * control passes back to PLy_procedure_call, we check for PG
2426 * exceptions and re-throw the error.
2428 PyErr_SetString(PLy_exc_error, sv);
2436 * return a legal object so the interpreter will continue on its merry way
2444 * Get the name of the last procedure called by the backend (the
2445 * innermost, if a plpython procedure call calls the backend and the
2446 * backend calls another plpython procedure).
2448 * NB: this returns the SQL name, not the internal Python procedure name
2451 PLy_procedure_name(PLyProcedure * proc)
2454 return "<unknown procedure>";
2455 return proc->proname;
2458 /* output a python traceback/exception via the postgresql elog
2459 * function. not pretty.
2462 PLy_exception_set(PyObject * exc, const char *fmt,...)
2468 vsnprintf(buf, sizeof(buf), fmt, ap);
2471 PyErr_SetString(exc, buf);
2474 /* Emit a PG error or notice, together with any available info about the
2475 * current Python error. This should be used to propagate Python errors
2479 PLy_elog(int elevel, const char *fmt,...)
2486 xmsg = PLy_traceback(&xlevel);
2489 emsg = PLy_vprintf(fmt, ap);
2495 (errmsg("plpython: %s", emsg),
2496 (xmsg) ? errdetail("%s", xmsg) : 0));
2513 PLy_traceback(int *xlevel)
2525 * get the current exception
2527 PyErr_Fetch(&e, &v, &tb);
2530 * oops, no exception, return
2538 PyErr_NormalizeException(&e, &v, &tb);
2541 eob = PyObject_Str(e);
2542 if (v && ((vob = PyObject_Str(v)) != NULL))
2543 vstr = PyString_AsString(vob);
2548 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
2549 * because that function calls us, so we could end up with infinite
2550 * recursion. I'm not even sure if eob could be NULL here -- would an
2551 * Assert() be more appropriate?
2553 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
2554 xstr = PLy_printf("%s: %s", estr, vstr);
2561 * intuit an appropriate error level based on the exception type
2563 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
2565 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
2575 PLy_printf(const char *fmt,...)
2581 emsg = PLy_vprintf(fmt, ap);
2587 PLy_vprintf(const char *fmt, va_list ap)
2594 blen = strlen(fmt) * 2;
2597 buf = PLy_malloc(blen * sizeof(char));
2601 bchar = vsnprintf(buf, blen, fmt, ap);
2602 if (bchar > 0 && bchar < blen)
2610 buf = PLy_realloc(buf, blen);
2616 /* python module code */
2618 /* some dumb utility functions */
2620 PLy_malloc(size_t bytes)
2622 void *ptr = malloc(bytes);
2626 (errcode(ERRCODE_OUT_OF_MEMORY),
2627 errmsg("out of memory")));
2632 PLy_realloc(void *optr, size_t bytes)
2634 void *nptr = realloc(optr, bytes);
2638 (errcode(ERRCODE_OUT_OF_MEMORY),
2639 errmsg("out of memory")));
2644 PLy_strdup(const char *str)
2649 len = strlen(str) + 1;
2650 result = PLy_malloc(len);
2651 memcpy(result, str, len);
2656 /* define this away */