1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.81 2006/05/30 22:12:16 tgl 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"
37 /* convert Postgresql Datum or tuple into a PyObject.
38 * input to Python. Tuples are converted to dictionary
42 typedef PyObject *(*PLyDatumToObFunc) (const char *);
44 typedef struct PLyDatumToOb
46 PLyDatumToObFunc func;
52 typedef struct PLyTupleToOb
58 typedef union PLyTypeInput
64 /* convert PyObject to a Postgresql Datum or tuple.
67 typedef struct PLyObToDatum
69 FmgrInfo typfunc; /* The type's input function */
70 Oid typoid; /* The OID of the type */
75 typedef struct PLyObToTuple
81 typedef union PLyTypeOutput
87 /* all we need to move Postgresql data to Python objects,
90 typedef struct PLyTypeInfo
97 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
98 * 1 rowtype 2 rowtype, but I/O functions not set up yet
103 /* cached procedure data */
104 typedef struct PLyProcedure
106 char *proname; /* SQL name of procedure */
107 char *pyname; /* Python name of procedure */
108 TransactionId fn_xmin;
111 PLyTypeInfo result; /* also used to store info for trigger tuple
113 PLyTypeInfo args[FUNC_MAX_ARGS];
115 PyObject *code; /* compiled procedure code */
116 PyObject *statics; /* data saved across calls, local scope */
117 PyObject *globals; /* data saved across calls, global scope */
118 PyObject *me; /* PyCObject containing pointer to this
124 typedef struct PLyPlanObject
127 void *plan; /* return of an SPI_saveplan */
134 typedef struct PLyResultObject
137 /* HeapTuple *tuples; */
138 PyObject *nrows; /* number of rows returned by query */
139 PyObject *rows; /* data rows, or None if no data returned */
140 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
144 /* function declarations */
146 /* Two exported functions: first is the magic telling Postgresql
147 * what function call interface it implements. Second allows
148 * preinitialization of the interpreter during postmaster startup.
150 Datum plpython_call_handler(PG_FUNCTION_ARGS);
151 void plpython_init(void);
153 PG_FUNCTION_INFO_V1(plpython_call_handler);
155 /* most of the remaining of the declarations, all static */
157 /* these should only be called once at the first call
158 * of plpython_call_handler. initialize the python interpreter
161 static void PLy_init_all(void);
162 static void PLy_init_interp(void);
163 static void PLy_init_plpy(void);
165 /* call PyErr_SetString with a vprint interface */
167 PLy_exception_set(PyObject *, const char *,...)
168 __attribute__((format(printf, 2, 3)));
170 /* Get the innermost python procedure called from the backend */
171 static char *PLy_procedure_name(PLyProcedure *);
173 /* some utility functions */
174 static void PLy_elog(int, const char *,...);
175 static char *PLy_traceback(int *);
176 static char *PLy_vprintf(const char *fmt, va_list ap);
177 static char *PLy_printf(const char *fmt,...);
179 static void *PLy_malloc(size_t);
180 static void *PLy_realloc(void *, size_t);
181 static char *PLy_strdup(const char *);
182 static void PLy_free(void *);
184 /* sub handlers for functions and triggers */
185 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
186 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
188 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
189 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
191 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
192 TriggerData *, HeapTuple);
194 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
196 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
199 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
201 HeapTuple procTup, char *key);
203 static void PLy_procedure_compile(PLyProcedure *, const char *);
204 static char *PLy_procedure_munge_source(const char *, const char *);
205 static void PLy_procedure_delete(PLyProcedure *);
207 static void PLy_typeinfo_init(PLyTypeInfo *);
208 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
209 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
210 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
211 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
212 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
213 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
214 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
216 /* conversion functions */
217 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
218 static PyObject *PLyBool_FromString(const char *);
219 static PyObject *PLyFloat_FromString(const char *);
220 static PyObject *PLyInt_FromString(const char *);
221 static PyObject *PLyLong_FromString(const char *);
222 static PyObject *PLyString_FromString(const char *);
226 static bool PLy_first_call = true;
229 * Currently active plpython function
231 static PLyProcedure *PLy_curr_procedure = NULL;
234 * When a callback from Python into PG incurs an error, we temporarily store
235 * the error information here, and return NULL to the Python interpreter.
236 * Any further callback attempts immediately fail, and when the Python
237 * interpreter returns to the calling function, we re-throw the error (even if
238 * Python thinks it trapped the error and doesn't return NULL). Eventually
239 * this ought to be improved to let Python code really truly trap the error,
240 * but that's more of a change from the pre-8.0 semantics than I have time for
241 * now --- it will only be possible if the callback query is executed inside a
244 static ErrorData *PLy_error_in_progress = NULL;
246 static PyObject *PLy_interp_globals = NULL;
247 static PyObject *PLy_interp_safe_globals = NULL;
248 static PyObject *PLy_procedure_cache = NULL;
250 /* Python exceptions */
251 static PyObject *PLy_exc_error = NULL;
252 static PyObject *PLy_exc_fatal = NULL;
253 static PyObject *PLy_exc_spi_error = NULL;
255 /* some globals for the python module */
256 static char PLy_plan_doc[] = {
257 "Store a PostgreSQL plan"
260 static char PLy_result_doc[] = {
261 "Results of a PostgreSQL query"
266 * the function definitions
270 * This routine is a crock, and so is everyplace that calls it. The problem
271 * is that the cached form of plpython functions/queries is allocated permanently
272 * (mostly via malloc()) and never released until backend exit. Subsidiary
273 * data structures such as fmgr info records therefore must live forever
274 * as well. A better implementation would store all this stuff in a per-
275 * function memory context that could be reclaimed at need. In the meantime,
276 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
277 * it might allocate, and whatever the eventual function might allocate using
278 * fn_mcxt, will live forever too.
281 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
283 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
287 plpython_call_handler(PG_FUNCTION_ARGS)
290 PLyProcedure *save_curr_proc;
291 PLyProcedure *volatile proc = NULL;
295 if (SPI_connect() != SPI_OK_CONNECT)
296 elog(ERROR, "could not connect to SPI manager");
298 save_curr_proc = PLy_curr_procedure;
302 if (CALLED_AS_TRIGGER(fcinfo))
304 TriggerData *tdata = (TriggerData *) fcinfo->context;
307 proc = PLy_procedure_get(fcinfo,
308 RelationGetRelid(tdata->tg_relation));
309 PLy_curr_procedure = proc;
310 trv = PLy_trigger_handler(fcinfo, proc);
311 retval = PointerGetDatum(trv);
315 proc = PLy_procedure_get(fcinfo, InvalidOid);
316 PLy_curr_procedure = proc;
317 retval = PLy_function_handler(fcinfo, proc);
322 PLy_curr_procedure = save_curr_proc;
325 /* note: Py_DECREF needs braces around it, as of 2003/08 */
333 PLy_curr_procedure = save_curr_proc;
340 /* trigger and function sub handlers
342 * the python function is expected to return Py_None if the tuple is
343 * acceptable and unmodified. Otherwise it should return a PyString
344 * object who's value is SKIP, or MODIFY. SKIP means don't perform
345 * this action. MODIFY means the tuple has been modified, so update
346 * tuple and perform action. SKIP and MODIFY assume the trigger fires
347 * BEFORE the event and is ROW level. postgres expects the function
348 * to take no arguments and return an argument of type trigger.
351 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
354 PyObject *volatile plargs = NULL;
355 PyObject *volatile plrv = NULL;
359 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
360 plrv = PLy_procedure_call(proc, "TD", plargs);
362 Assert(plrv != NULL);
363 Assert(!PLy_error_in_progress);
366 * Disconnect from SPI manager
368 if (SPI_finish() != SPI_OK_FINISH)
369 elog(ERROR, "SPI_finish failed");
372 * return of None means we're happy with the tuple
378 if (!PyString_Check(plrv))
380 (errcode(ERRCODE_DATA_EXCEPTION),
381 errmsg("unexpected return value from trigger procedure"),
382 errdetail("Expected None or a String.")));
384 srv = PyString_AsString(plrv);
385 if (pg_strcasecmp(srv, "SKIP") == 0)
387 else if (pg_strcasecmp(srv, "MODIFY") == 0)
389 TriggerData *tdata = (TriggerData *) fcinfo->context;
391 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
392 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
393 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
395 elog(WARNING, "ignoring modified tuple in DELETE trigger");
397 else if (pg_strcasecmp(srv, "OK") != 0)
400 * accept "OK" as an alternative to None; otherwise,
404 (errcode(ERRCODE_DATA_EXCEPTION),
405 errmsg("unexpected return value from trigger procedure"),
406 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
426 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
429 PyObject *volatile plntup;
430 PyObject *volatile plkeys;
431 PyObject *volatile platt;
432 PyObject *volatile plval;
433 PyObject *volatile plstr;
439 int *volatile modattrs;
440 Datum *volatile modvalues;
441 char *volatile modnulls;
444 plntup = plkeys = platt = plval = plstr = NULL;
451 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
452 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
453 if (!PyDict_Check(plntup))
454 elog(ERROR, "TD[\"new\"] is not a dictionary object");
457 plkeys = PyDict_Keys(plntup);
458 natts = PyList_Size(plkeys);
460 modattrs = (int *) palloc(natts * sizeof(int));
461 modvalues = (Datum *) palloc(natts * sizeof(Datum));
462 modnulls = (char *) palloc(natts * sizeof(char));
464 tupdesc = tdata->tg_relation->rd_att;
466 for (i = 0; i < natts; i++)
470 platt = PyList_GetItem(plkeys, i);
471 if (!PyString_Check(platt))
472 elog(ERROR, "attribute name is not a string");
473 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
474 if (attn == SPI_ERROR_NOATTRIBUTE)
475 elog(ERROR, "invalid attribute \"%s\" in tuple",
476 PyString_AsString(platt));
479 plval = PyDict_GetItem(plntup, platt);
481 elog(FATAL, "python interpreter is probably corrupted");
487 if (tupdesc->attrs[atti]->attisdropped)
489 modvalues[i] = (Datum) 0;
492 else if (plval != Py_None)
494 plstr = PyObject_Str(plval);
496 PLy_elog(ERROR, "function \"%s\" could not modify tuple",
498 src = PyString_AsString(plstr);
501 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
503 proc->result.out.r.atts[atti].typioparam,
504 tupdesc->attrs[atti]->atttypmod);
513 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
515 proc->result.out.r.atts[atti].typioparam,
516 tupdesc->attrs[atti]->atttypmod);
524 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
525 modattrs, modvalues, modnulls);
527 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
558 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
560 TriggerData *tdata = (TriggerData *) fcinfo->context;
571 PyObject *volatile pltdata = NULL;
576 pltdata = PyDict_New();
578 PLy_elog(ERROR, "could not build arguments for trigger procedure");
580 pltname = PyString_FromString(tdata->tg_trigger->tgname);
581 PyDict_SetItemString(pltdata, "name", pltname);
584 stroid = DatumGetCString(DirectFunctionCall1(oidout,
585 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
586 pltrelid = PyString_FromString(stroid);
587 PyDict_SetItemString(pltdata, "relid", pltrelid);
591 stroid = SPI_getrelname(tdata->tg_relation);
592 plttablename = PyString_FromString(stroid);
593 PyDict_SetItemString(pltdata, "table_name", plttablename);
594 Py_DECREF(plttablename);
597 stroid = SPI_getnspname(tdata->tg_relation);
598 plttableschema = PyString_FromString(stroid);
599 PyDict_SetItemString(pltdata, "table_schema", plttableschema);
600 Py_DECREF(plttableschema);
604 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
605 pltwhen = PyString_FromString("BEFORE");
606 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
607 pltwhen = PyString_FromString("AFTER");
610 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
611 pltwhen = NULL; /* keep compiler quiet */
613 PyDict_SetItemString(pltdata, "when", pltwhen);
616 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
618 pltlevel = PyString_FromString("ROW");
619 PyDict_SetItemString(pltdata, "level", pltlevel);
622 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
624 pltevent = PyString_FromString("INSERT");
626 PyDict_SetItemString(pltdata, "old", Py_None);
627 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
628 tdata->tg_relation->rd_att);
629 PyDict_SetItemString(pltdata, "new", pytnew);
631 *rv = tdata->tg_trigtuple;
633 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
635 pltevent = PyString_FromString("DELETE");
637 PyDict_SetItemString(pltdata, "new", Py_None);
638 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
639 tdata->tg_relation->rd_att);
640 PyDict_SetItemString(pltdata, "old", pytold);
642 *rv = tdata->tg_trigtuple;
644 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
646 pltevent = PyString_FromString("UPDATE");
648 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
649 tdata->tg_relation->rd_att);
650 PyDict_SetItemString(pltdata, "new", pytnew);
652 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
653 tdata->tg_relation->rd_att);
654 PyDict_SetItemString(pltdata, "old", pytold);
656 *rv = tdata->tg_newtuple;
660 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
661 pltevent = NULL; /* keep compiler quiet */
664 PyDict_SetItemString(pltdata, "event", pltevent);
667 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
669 pltlevel = PyString_FromString("STATEMENT");
670 PyDict_SetItemString(pltdata, "level", pltlevel);
673 PyDict_SetItemString(pltdata, "old", Py_None);
674 PyDict_SetItemString(pltdata, "new", Py_None);
677 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
678 pltevent = PyString_FromString("INSERT");
679 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
680 pltevent = PyString_FromString("DELETE");
681 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
682 pltevent = PyString_FromString("UPDATE");
685 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
686 pltevent = NULL; /* keep compiler quiet */
689 PyDict_SetItemString(pltdata, "event", pltevent);
693 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
695 if (tdata->tg_trigger->tgnargs)
703 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
704 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
706 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
709 * stolen, don't Py_DECREF
711 PyList_SetItem(pltargs, i, pltarg);
719 PyDict_SetItemString(pltdata, "args", pltargs);
734 /* function handler and friends */
736 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
739 PyObject *volatile plargs = NULL;
740 PyObject *volatile plrv = NULL;
741 PyObject *volatile plrv_so = NULL;
746 plargs = PLy_function_build_args(fcinfo, proc);
747 plrv = PLy_procedure_call(proc, "args", plargs);
749 Assert(plrv != NULL);
750 Assert(!PLy_error_in_progress);
753 * Disconnect from SPI manager and then create the return values datum
754 * (if the input function does a palloc for it this must not be
755 * allocated in the SPI memory context because SPI_finish would free
758 if (SPI_finish() != SPI_OK_FINISH)
759 elog(ERROR, "SPI_finish failed");
762 * If the function is declared to return void, the Python
763 * return value must be None. For void-returning functions, we
764 * also treat a None return value as a special "void datum"
765 * rather than NULL (as is the case for non-void-returning
768 if (proc->result.out.d.typoid == VOIDOID)
772 (errcode(ERRCODE_DATATYPE_MISMATCH),
773 errmsg("invalid return value from plpython function"),
774 errdetail("Functions returning type \"void\" must return None.")));
776 fcinfo->isnull = false;
779 else if (plrv == Py_None)
781 fcinfo->isnull = true;
782 rv = InputFunctionCall(&proc->result.out.d.typfunc,
784 proc->result.out.d.typioparam,
789 fcinfo->isnull = false;
790 plrv_so = PyObject_Str(plrv);
792 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
793 plrv_sc = PyString_AsString(plrv_so);
794 rv = InputFunctionCall(&proc->result.out.d.typfunc,
796 proc->result.out.d.typioparam,
818 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
822 PyDict_SetItemString(proc->globals, kargs, vargs);
823 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
824 proc->globals, proc->globals);
827 * If there was an error in a PG callback, propagate that no matter what
828 * Python claims about its success.
830 if (PLy_error_in_progress)
832 ErrorData *edata = PLy_error_in_progress;
834 PLy_error_in_progress = NULL;
838 if (rv == NULL || PyErr_Occurred())
841 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
848 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
850 PyObject *volatile arg = NULL;
851 PyObject *volatile args = NULL;
856 args = PyList_New(proc->nargs);
857 for (i = 0; i < proc->nargs; i++)
859 if (proc->args[i].is_rowtype > 0)
861 if (fcinfo->argnull[i])
869 HeapTupleData tmptup;
871 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
872 /* Extract rowtype info and find a tupdesc */
873 tupType = HeapTupleHeaderGetTypeId(td);
874 tupTypmod = HeapTupleHeaderGetTypMod(td);
875 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
877 /* Set up I/O funcs if not done yet */
878 if (proc->args[i].is_rowtype != 1)
879 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
881 /* Build a temporary HeapTuple control structure */
882 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
885 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
890 if (fcinfo->argnull[i])
896 ct = OutputFunctionCall(&(proc->args[i].in.d.typfunc),
898 arg = (proc->args[i].in.d.func) (ct);
910 * FIXME -- error check this
912 PyList_SetItem(args, i, arg);
930 * PLyProcedure functions
933 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
934 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
935 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
938 static PLyProcedure *
939 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
945 PLyProcedure *proc = NULL;
948 fn_oid = fcinfo->flinfo->fn_oid;
949 procTup = SearchSysCache(PROCOID,
950 ObjectIdGetDatum(fn_oid),
952 if (!HeapTupleIsValid(procTup))
953 elog(ERROR, "cache lookup failed for function %u", fn_oid);
955 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
956 if (rv >= sizeof(key) || rv < 0)
957 elog(ERROR, "key too long");
959 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
964 if (!PyCObject_Check(plproc))
965 elog(FATAL, "expected a PyCObject, didn't get one");
967 proc = PyCObject_AsVoidPtr(plproc);
968 if (proc->me != plproc)
969 elog(FATAL, "proc->me != plproc");
970 /* did we find an up-to-date cache entry? */
971 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
972 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
980 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
982 ReleaseSysCache(procTup);
987 static PLyProcedure *
988 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
989 HeapTuple procTup, char *key)
991 char procName[NAMEDATALEN + 256];
992 Form_pg_proc procStruct;
993 PLyProcedure *volatile proc;
994 char *volatile procSource = NULL;
1000 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1002 if (OidIsValid(tgreloid))
1003 rv = snprintf(procName, sizeof(procName),
1004 "__plpython_procedure_%s_%u_trigger_%u",
1005 NameStr(procStruct->proname),
1006 fcinfo->flinfo->fn_oid,
1009 rv = snprintf(procName, sizeof(procName),
1010 "__plpython_procedure_%s_%u",
1011 NameStr(procStruct->proname),
1012 fcinfo->flinfo->fn_oid);
1013 if (rv >= sizeof(procName) || rv < 0)
1014 elog(ERROR, "procedure name would overrun buffer");
1016 proc = PLy_malloc(sizeof(PLyProcedure));
1017 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1018 proc->pyname = PLy_strdup(procName);
1019 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1020 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1021 /* Remember if function is STABLE/IMMUTABLE */
1023 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1024 PLy_typeinfo_init(&proc->result);
1025 for (i = 0; i < FUNC_MAX_ARGS; i++)
1026 PLy_typeinfo_init(&proc->args[i]);
1028 proc->code = proc->statics = NULL;
1029 proc->globals = proc->me = NULL;
1034 * get information required for output conversion of the return value,
1035 * but only if this isn't a trigger.
1037 if (!CALLED_AS_TRIGGER(fcinfo))
1039 HeapTuple rvTypeTup;
1040 Form_pg_type rvTypeStruct;
1042 rvTypeTup = SearchSysCache(TYPEOID,
1043 ObjectIdGetDatum(procStruct->prorettype),
1045 if (!HeapTupleIsValid(rvTypeTup))
1046 elog(ERROR, "cache lookup failed for type %u",
1047 procStruct->prorettype);
1048 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1050 /* Disallow pseudotype result, except for void */
1051 if (rvTypeStruct->typtype == 'p' &&
1052 procStruct->prorettype != VOIDOID)
1054 if (procStruct->prorettype == TRIGGEROID)
1056 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1057 errmsg("trigger functions may only be called as triggers")));
1060 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1061 errmsg("plpython functions cannot return type %s",
1062 format_type_be(procStruct->prorettype))));
1065 if (rvTypeStruct->typtype == 'c')
1067 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1068 errmsg("plpython functions cannot return tuples yet")));
1070 PLy_output_datum_func(&proc->result, rvTypeTup);
1072 ReleaseSysCache(rvTypeTup);
1077 * input/output conversion for trigger tuples. use the result
1078 * TypeInfo variable to store the tuple conversion info.
1080 TriggerData *tdata = (TriggerData *) fcinfo->context;
1082 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1083 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1087 * now get information required for input conversion of the procedure's
1090 proc->nargs = fcinfo->nargs;
1091 for (i = 0; i < fcinfo->nargs; i++)
1093 HeapTuple argTypeTup;
1094 Form_pg_type argTypeStruct;
1096 argTypeTup = SearchSysCache(TYPEOID,
1097 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1099 if (!HeapTupleIsValid(argTypeTup))
1100 elog(ERROR, "cache lookup failed for type %u",
1101 procStruct->proargtypes.values[i]);
1102 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1104 /* Disallow pseudotype argument */
1105 if (argTypeStruct->typtype == 'p')
1107 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1108 errmsg("plpython functions cannot take type %s",
1109 format_type_be(procStruct->proargtypes.values[i]))));
1111 if (argTypeStruct->typtype != 'c')
1112 PLy_input_datum_func(&(proc->args[i]),
1113 procStruct->proargtypes.values[i],
1116 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1118 ReleaseSysCache(argTypeTup);
1123 * get the text of the function.
1125 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1126 Anum_pg_proc_prosrc, &isnull);
1128 elog(ERROR, "null prosrc");
1129 procSource = DatumGetCString(DirectFunctionCall1(textout,
1132 PLy_procedure_compile(proc, procSource);
1136 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1137 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1141 PLy_procedure_delete(proc);
1153 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1155 PyObject *crv = NULL;
1158 proc->globals = PyDict_Copy(PLy_interp_globals);
1161 * SD is private preserved data between calls. GD is global data
1162 * shared by all functions
1164 proc->statics = PyDict_New();
1165 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1168 * insert the function code into the interpreter
1170 msrc = PLy_procedure_munge_source(proc->pyname, src);
1171 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1174 if (crv != NULL && (!PyErr_Occurred()))
1177 char call[NAMEDATALEN + 256];
1182 * compile a call to the function
1184 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1185 if (clen < 0 || clen >= sizeof(call))
1186 elog(ERROR, "string would overflow buffer");
1187 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1188 if (proc->code != NULL && (!PyErr_Occurred()))
1194 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1198 PLy_procedure_munge_source(const char *name, const char *src)
1207 * room for function source and the def statement
1209 mlen = (strlen(src) * 2) + strlen(name) + 16;
1211 mrc = PLy_malloc(mlen);
1212 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1213 Assert(plen >= 0 && plen < mlen);
1220 if (*sp == '\r' && *(sp + 1) == '\n')
1223 if (*sp == '\n' || *sp == '\r')
1236 if (mp > (mrc + mlen))
1237 elog(FATAL, "buffer overrun in PLy_munge_source");
1243 PLy_procedure_delete(PLyProcedure * proc)
1247 Py_XDECREF(proc->code);
1248 Py_XDECREF(proc->statics);
1249 Py_XDECREF(proc->globals);
1250 Py_XDECREF(proc->me);
1252 PLy_free(proc->proname);
1254 PLy_free(proc->pyname);
1255 for (i = 0; i < proc->nargs; i++)
1256 if (proc->args[i].is_rowtype == 1)
1258 if (proc->args[i].in.r.atts)
1259 PLy_free(proc->args[i].in.r.atts);
1260 if (proc->args[i].out.r.atts)
1261 PLy_free(proc->args[i].out.r.atts);
1265 /* conversion functions. remember output from python is
1266 * input to postgresql, and vis versa.
1269 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1273 if (arg->is_rowtype == 0)
1274 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1276 arg->is_rowtype = 1;
1277 arg->in.r.natts = desc->natts;
1278 arg->in.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1280 for (i = 0; i < desc->natts; i++)
1284 if (desc->attrs[i]->attisdropped)
1287 typeTup = SearchSysCache(TYPEOID,
1288 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1290 if (!HeapTupleIsValid(typeTup))
1291 elog(ERROR, "cache lookup failed for type %u",
1292 desc->attrs[i]->atttypid);
1294 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1295 desc->attrs[i]->atttypid,
1298 ReleaseSysCache(typeTup);
1303 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1307 if (arg->is_rowtype == 0)
1308 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1310 arg->is_rowtype = 1;
1311 arg->out.r.natts = desc->natts;
1312 arg->out.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1314 for (i = 0; i < desc->natts; i++)
1318 if (desc->attrs[i]->attisdropped)
1321 typeTup = SearchSysCache(TYPEOID,
1322 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1324 if (!HeapTupleIsValid(typeTup))
1325 elog(ERROR, "cache lookup failed for type %u",
1326 desc->attrs[i]->atttypid);
1328 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1330 ReleaseSysCache(typeTup);
1335 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1337 if (arg->is_rowtype > 0)
1338 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1339 arg->is_rowtype = 0;
1340 PLy_output_datum_func2(&(arg->out.d), typeTup);
1344 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1346 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1348 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1349 arg->typoid = HeapTupleGetOid(typeTup);
1350 arg->typioparam = getTypeIOParam(typeTup);
1351 arg->typbyval = typeStruct->typbyval;
1355 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1357 if (arg->is_rowtype > 0)
1358 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1359 arg->is_rowtype = 0;
1360 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1364 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1366 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1368 /* Get the type's conversion information */
1369 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1370 arg->typioparam = getTypeIOParam(typeTup);
1371 arg->typbyval = typeStruct->typbyval;
1373 /* Determine which kind of Python object we will convert to */
1377 arg->func = PLyBool_FromString;
1382 arg->func = PLyFloat_FromString;
1386 arg->func = PLyInt_FromString;
1389 arg->func = PLyLong_FromString;
1392 arg->func = PLyString_FromString;
1398 PLy_typeinfo_init(PLyTypeInfo * arg)
1400 arg->is_rowtype = -1;
1401 arg->in.r.natts = arg->out.r.natts = 0;
1402 arg->in.r.atts = NULL;
1403 arg->out.r.atts = NULL;
1407 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1409 if (arg->is_rowtype == 1)
1412 PLy_free(arg->in.r.atts);
1413 if (arg->out.r.atts)
1414 PLy_free(arg->out.r.atts);
1418 /* assumes that a bool is always returned as a 't' or 'f' */
1420 PLyBool_FromString(const char *src)
1423 return PyInt_FromLong(1);
1424 return PyInt_FromLong(0);
1428 PLyFloat_FromString(const char *src)
1434 v = strtod(src, &eptr);
1435 if (*eptr != '\0' || errno)
1437 return PyFloat_FromDouble(v);
1441 PLyInt_FromString(const char *src)
1447 v = strtol(src, &eptr, 0);
1448 if (*eptr != '\0' || errno)
1450 return PyInt_FromLong(v);
1454 PLyLong_FromString(const char *src)
1456 return PyLong_FromString((char *) src, NULL, 0);
1460 PLyString_FromString(const char *src)
1462 return PyString_FromString(src);
1466 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1468 PyObject *volatile dict;
1471 if (info->is_rowtype != 1)
1472 elog(ERROR, "PLyTypeInfo structure describes a datum");
1474 dict = PyDict_New();
1476 PLy_elog(ERROR, "could not create tuple dictionary");
1480 for (i = 0; i < info->in.r.natts; i++)
1488 if (desc->attrs[i]->attisdropped)
1491 key = NameStr(desc->attrs[i]->attname);
1492 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1494 if (is_null || info->in.r.atts[i].func == NULL)
1495 PyDict_SetItemString(dict, key, Py_None);
1498 vsrc = OutputFunctionCall(&info->in.r.atts[i].typfunc,
1502 * no exceptions allowed
1504 value = info->in.r.atts[i].func(vsrc);
1506 PyDict_SetItemString(dict, key, value);
1521 /* initialization, some python variables function declared here */
1523 /* interface to postgresql elog */
1524 static PyObject *PLy_debug(PyObject *, PyObject *);
1525 static PyObject *PLy_log(PyObject *, PyObject *);
1526 static PyObject *PLy_info(PyObject *, PyObject *);
1527 static PyObject *PLy_notice(PyObject *, PyObject *);
1528 static PyObject *PLy_warning(PyObject *, PyObject *);
1529 static PyObject *PLy_error(PyObject *, PyObject *);
1530 static PyObject *PLy_fatal(PyObject *, PyObject *);
1532 /* PLyPlanObject, PLyResultObject and SPI interface */
1533 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1534 static PyObject *PLy_plan_new(void);
1535 static void PLy_plan_dealloc(PyObject *);
1536 static PyObject *PLy_plan_getattr(PyObject *, char *);
1537 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1539 static PyObject *PLy_result_new(void);
1540 static void PLy_result_dealloc(PyObject *);
1541 static PyObject *PLy_result_getattr(PyObject *, char *);
1542 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1543 static PyObject *PLy_result_status(PyObject *, PyObject *);
1544 static int PLy_result_length(PyObject *);
1545 static PyObject *PLy_result_item(PyObject *, int);
1546 static PyObject *PLy_result_slice(PyObject *, int, int);
1547 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1548 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1551 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1552 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1553 static PyObject *PLy_spi_execute_query(char *query, long limit);
1554 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1555 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1558 static PyTypeObject PLy_PlanType = {
1559 PyObject_HEAD_INIT(NULL)
1561 "PLyPlan", /* tp_name */
1562 sizeof(PLyPlanObject), /* tp_size */
1563 0, /* tp_itemsize */
1568 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1570 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1574 0, /* tp_as_number */
1575 0, /* tp_as_sequence */
1576 0, /* tp_as_mapping */
1580 0, /* tp_getattro */
1581 0, /* tp_setattro */
1582 0, /* tp_as_buffer */
1584 PLy_plan_doc, /* tp_doc */
1587 static PyMethodDef PLy_plan_methods[] = {
1588 {"status", PLy_plan_status, METH_VARARGS, NULL},
1589 {NULL, NULL, 0, NULL}
1593 static PySequenceMethods PLy_result_as_sequence = {
1594 (inquiry) PLy_result_length, /* sq_length */
1595 (binaryfunc) 0, /* sq_concat */
1596 (intargfunc) 0, /* sq_repeat */
1597 (intargfunc) PLy_result_item, /* sq_item */
1598 (intintargfunc) PLy_result_slice, /* sq_slice */
1599 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1600 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1603 static PyTypeObject PLy_ResultType = {
1604 PyObject_HEAD_INIT(NULL)
1606 "PLyResult", /* tp_name */
1607 sizeof(PLyResultObject), /* tp_size */
1608 0, /* tp_itemsize */
1613 (destructor) PLy_result_dealloc, /* tp_dealloc */
1615 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1619 0, /* tp_as_number */
1620 &PLy_result_as_sequence, /* tp_as_sequence */
1621 0, /* tp_as_mapping */
1625 0, /* tp_getattro */
1626 0, /* tp_setattro */
1627 0, /* tp_as_buffer */
1629 PLy_result_doc, /* tp_doc */
1632 static PyMethodDef PLy_result_methods[] = {
1633 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
1634 {"status", PLy_result_status, METH_VARARGS, NULL},
1635 {NULL, NULL, 0, NULL}
1638 static PyMethodDef PLy_methods[] = {
1642 {"debug", PLy_debug, METH_VARARGS, NULL},
1643 {"log", PLy_log, METH_VARARGS, NULL},
1644 {"info", PLy_info, METH_VARARGS, NULL},
1645 {"notice", PLy_notice, METH_VARARGS, NULL},
1646 {"warning", PLy_warning, METH_VARARGS, NULL},
1647 {"error", PLy_error, METH_VARARGS, NULL},
1648 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1651 * create a stored plan
1653 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1656 * execute a plan or query
1658 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1660 {NULL, NULL, 0, NULL}
1664 /* plan object methods */
1670 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
1678 return (PyObject *) ob;
1683 PLy_plan_dealloc(PyObject * arg)
1685 PLyPlanObject *ob = (PLyPlanObject *) arg;
1688 SPI_freeplan(ob->plan);
1690 PLy_free(ob->types);
1695 for (i = 0; i < ob->nargs; i++)
1696 PLy_typeinfo_dealloc(&ob->args[i]);
1705 PLy_plan_getattr(PyObject * self, char *name)
1707 return Py_FindMethod(PLy_plan_methods, self, name);
1711 PLy_plan_status(PyObject * self, PyObject * args)
1713 if (PyArg_ParseTuple(args, ""))
1717 /* return PyInt_FromLong(self->status); */
1719 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
1725 /* result object methods */
1728 PLy_result_new(void)
1730 PLyResultObject *ob;
1732 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1735 /* ob->tuples = NULL; */
1738 ob->status = Py_None;
1739 ob->nrows = PyInt_FromLong(-1);
1740 ob->rows = PyList_New(0);
1742 return (PyObject *) ob;
1746 PLy_result_dealloc(PyObject * arg)
1748 PLyResultObject *ob = (PLyResultObject *) arg;
1750 Py_XDECREF(ob->nrows);
1751 Py_XDECREF(ob->rows);
1752 Py_XDECREF(ob->status);
1758 PLy_result_getattr(PyObject * self, char *name)
1760 return Py_FindMethod(PLy_result_methods, self, name);
1764 PLy_result_nrows(PyObject * self, PyObject * args)
1766 PLyResultObject *ob = (PLyResultObject *) self;
1768 Py_INCREF(ob->nrows);
1773 PLy_result_status(PyObject * self, PyObject * args)
1775 PLyResultObject *ob = (PLyResultObject *) self;
1777 Py_INCREF(ob->status);
1782 PLy_result_length(PyObject * arg)
1784 PLyResultObject *ob = (PLyResultObject *) arg;
1786 return PyList_Size(ob->rows);
1790 PLy_result_item(PyObject * arg, int idx)
1793 PLyResultObject *ob = (PLyResultObject *) arg;
1795 rv = PyList_GetItem(ob->rows, idx);
1802 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1805 PLyResultObject *ob = (PLyResultObject *) arg;
1808 rv = PyList_SetItem(ob->rows, idx, item);
1813 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1816 PLyResultObject *ob = (PLyResultObject *) arg;
1818 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1826 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1829 PLyResultObject *ob = (PLyResultObject *) arg;
1831 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1837 PLy_spi_prepare(PyObject * self, PyObject * args)
1839 PLyPlanObject *plan;
1840 PyObject *list = NULL;
1841 PyObject *volatile optr = NULL;
1844 MemoryContext oldcontext;
1846 /* Can't execute more if we have an unhandled error */
1847 if (PLy_error_in_progress)
1849 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1853 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1855 PyErr_SetString(PLy_exc_spi_error,
1856 "Invalid arguments for plpy.prepare()");
1860 if (list && (!PySequence_Check(list)))
1862 PyErr_SetString(PLy_exc_spi_error,
1863 "Second argument in plpy.prepare() must be a sequence");
1867 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1870 oldcontext = CurrentMemoryContext;
1878 nargs = PySequence_Length(list);
1881 plan->nargs = nargs;
1882 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1883 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1884 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1887 * the other loop might throw an exception, if PLyTypeInfo
1888 * member isn't properly initialized the Py_DECREF(plan) will
1891 for (i = 0; i < nargs; i++)
1893 PLy_typeinfo_init(&plan->args[i]);
1894 plan->values[i] = PointerGetDatum(NULL);
1897 for (i = 0; i < nargs; i++)
1902 Form_pg_type typeStruct;
1904 optr = PySequence_GetItem(list, i);
1905 if (!PyString_Check(optr))
1906 elog(ERROR, "Type names must be strings.");
1907 sptr = PyString_AsString(optr);
1910 * Parse possibly-qualified type name and look it up in
1913 names = stringToQualifiedNameList(sptr,
1915 typeTup = typenameType(NULL,
1916 makeTypeNameFromNameList(names));
1918 optr = NULL; /* this is important */
1920 plan->types[i] = HeapTupleGetOid(typeTup);
1921 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1922 if (typeStruct->typtype != 'c')
1923 PLy_output_datum_func(&plan->args[i], typeTup);
1925 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
1926 ReleaseSysCache(typeTup);
1931 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1932 if (plan->plan == NULL)
1933 elog(ERROR, "SPI_prepare failed: %s",
1934 SPI_result_code_string(SPI_result));
1936 /* transfer plan from procCxt to topCxt */
1937 tmpplan = plan->plan;
1938 plan->plan = SPI_saveplan(tmpplan);
1939 SPI_freeplan(tmpplan);
1940 if (plan->plan == NULL)
1941 elog(ERROR, "SPI_saveplan failed: %s",
1942 SPI_result_code_string(SPI_result));
1946 MemoryContextSwitchTo(oldcontext);
1947 PLy_error_in_progress = CopyErrorData();
1951 if (!PyErr_Occurred())
1952 PyErr_SetString(PLy_exc_spi_error,
1953 "Unknown error in PLy_spi_prepare");
1954 /* XXX this oughta be replaced with errcontext mechanism */
1955 PLy_elog(WARNING, "in function %s:",
1956 PLy_procedure_name(PLy_curr_procedure));
1961 return (PyObject *) plan;
1964 /* execute(query="select * from foo", limit=5)
1965 * execute(plan=plan, values=(foo, bar), limit=5)
1968 PLy_spi_execute(PyObject * self, PyObject * args)
1972 PyObject *list = NULL;
1975 /* Can't execute more if we have an unhandled error */
1976 if (PLy_error_in_progress)
1978 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1982 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
1983 return PLy_spi_execute_query(query, limit);
1987 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
1988 is_PLyPlanObject(plan))
1989 return PLy_spi_execute_plan(plan, list, limit);
1991 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
1996 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
2001 PLyPlanObject *plan;
2002 MemoryContext oldcontext;
2006 if (!PySequence_Check(list) || PyString_Check(list))
2008 char *msg = "plpy.execute() takes a sequence as its second argument";
2010 PyErr_SetString(PLy_exc_spi_error, msg);
2013 nargs = PySequence_Length(list);
2018 plan = (PLyPlanObject *) ob;
2020 if (nargs != plan->nargs)
2023 PyObject *so = PyObject_Str(list);
2026 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2027 PLy_procedure_name(PLy_curr_procedure));
2028 sv = PyString_AsString(so);
2029 PLy_exception_set(PLy_exc_spi_error,
2030 "Expected sequence of %d arguments, got %d. %s",
2031 plan->nargs, nargs, sv);
2037 oldcontext = CurrentMemoryContext;
2040 char *nulls = palloc(nargs * sizeof(char));
2042 for (i = 0; i < nargs; i++)
2047 elem = PySequence_GetItem(list, i);
2048 if (elem != Py_None)
2050 so = PyObject_Str(elem);
2052 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2053 PLy_procedure_name(PLy_curr_procedure));
2058 char *sv = PyString_AsString(so);
2061 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2063 plan->args[i].out.d.typioparam,
2080 InputFunctionCall(&(plan->args[i].out.d.typfunc),
2082 plan->args[i].out.d.typioparam,
2088 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2089 PLy_curr_procedure->fn_readonly, limit);
2095 MemoryContextSwitchTo(oldcontext);
2096 PLy_error_in_progress = CopyErrorData();
2100 * cleanup plan->values array
2102 for (i = 0; i < nargs; i++)
2104 if (!plan->args[i].out.d.typbyval &&
2105 (plan->values[i] != PointerGetDatum(NULL)))
2107 pfree(DatumGetPointer(plan->values[i]));
2108 plan->values[i] = PointerGetDatum(NULL);
2112 if (!PyErr_Occurred())
2113 PyErr_SetString(PLy_exc_error,
2114 "Unknown error in PLy_spi_execute_plan");
2115 /* XXX this oughta be replaced with errcontext mechanism */
2116 PLy_elog(WARNING, "in function %s:",
2117 PLy_procedure_name(PLy_curr_procedure));
2122 for (i = 0; i < nargs; i++)
2124 if (!plan->args[i].out.d.typbyval &&
2125 (plan->values[i] != PointerGetDatum(NULL)))
2127 pfree(DatumGetPointer(plan->values[i]));
2128 plan->values[i] = PointerGetDatum(NULL);
2134 PLy_exception_set(PLy_exc_spi_error,
2135 "SPI_execute_plan failed: %s",
2136 SPI_result_code_string(rv));
2140 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2144 PLy_spi_execute_query(char *query, long limit)
2147 MemoryContext oldcontext;
2149 oldcontext = CurrentMemoryContext;
2152 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2156 MemoryContextSwitchTo(oldcontext);
2157 PLy_error_in_progress = CopyErrorData();
2159 if (!PyErr_Occurred())
2160 PyErr_SetString(PLy_exc_spi_error,
2161 "Unknown error in PLy_spi_execute_query");
2162 /* XXX this oughta be replaced with errcontext mechanism */
2163 PLy_elog(WARNING, "in function %s:",
2164 PLy_procedure_name(PLy_curr_procedure));
2171 PLy_exception_set(PLy_exc_spi_error,
2172 "SPI_execute failed: %s",
2173 SPI_result_code_string(rv));
2177 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2181 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2183 PLyResultObject *result;
2184 MemoryContext oldcontext;
2186 result = (PLyResultObject *) PLy_result_new();
2187 Py_DECREF(result->status);
2188 result->status = PyInt_FromLong(status);
2190 if (status == SPI_OK_UTILITY)
2192 Py_DECREF(result->nrows);
2193 result->nrows = PyInt_FromLong(0);
2195 else if (status != SPI_OK_SELECT)
2197 Py_DECREF(result->nrows);
2198 result->nrows = PyInt_FromLong(rows);
2205 PLy_typeinfo_init(&args);
2206 Py_DECREF(result->nrows);
2207 result->nrows = PyInt_FromLong(rows);
2209 oldcontext = CurrentMemoryContext;
2214 Py_DECREF(result->rows);
2215 result->rows = PyList_New(rows);
2217 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2218 for (i = 0; i < rows; i++)
2220 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2223 PyList_SetItem(result->rows, i, row);
2225 PLy_typeinfo_dealloc(&args);
2227 SPI_freetuptable(tuptable);
2232 MemoryContextSwitchTo(oldcontext);
2233 PLy_error_in_progress = CopyErrorData();
2235 if (!PyErr_Occurred())
2236 PyErr_SetString(PLy_exc_error,
2237 "Unknown error in PLy_spi_execute_fetch_result");
2239 PLy_typeinfo_dealloc(&args);
2245 return (PyObject *) result;
2250 * language handler and interpreter initialization
2254 * plpython_init() - Initialize everything that can be
2255 * safely initialized during postmaster
2258 * DO NOT make this static --- it has to be callable by preload
2263 static volatile bool init_active = false;
2265 /* Do initialization only once */
2266 if (!PLy_first_call)
2270 elog(FATAL, "initialization of language module failed");
2276 if (PyErr_Occurred())
2277 PLy_elog(FATAL, "untrapped error in initialization");
2278 PLy_procedure_cache = PyDict_New();
2279 if (PLy_procedure_cache == NULL)
2280 PLy_elog(ERROR, "could not create procedure cache");
2282 PLy_first_call = false;
2288 /* Execute postmaster-startup safe initialization */
2293 * Any other initialization that must be done each time a new backend
2294 * starts -- currently none
2299 PLy_init_interp(void)
2303 mainmod = PyImport_AddModule("__main__");
2304 if (mainmod == NULL || PyErr_Occurred())
2305 PLy_elog(ERROR, "could not import \"__main__\" module.");
2307 PLy_interp_globals = PyModule_GetDict(mainmod);
2308 PLy_interp_safe_globals = PyDict_New();
2309 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2311 if (PLy_interp_globals == NULL || PyErr_Occurred())
2312 PLy_elog(ERROR, "could not initialize globals");
2325 * initialize plpy module
2327 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2328 plpy = Py_InitModule("plpy", PLy_methods);
2329 plpy_dict = PyModule_GetDict(plpy);
2331 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2333 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2334 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2335 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2336 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2337 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2338 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2341 * initialize main module, and add plpy
2343 main_mod = PyImport_AddModule("__main__");
2344 main_dict = PyModule_GetDict(main_mod);
2345 plpy_mod = PyImport_AddModule("plpy");
2346 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2347 if (PyErr_Occurred())
2348 elog(ERROR, "could not init plpy");
2351 /* the python interface to the elog function
2352 * don't confuse these with PLy_elog
2354 static PyObject *PLy_output(int, PyObject *, PyObject *);
2357 PLy_debug(PyObject * self, PyObject * args)
2359 return PLy_output(DEBUG2, self, args);
2363 PLy_log(PyObject * self, PyObject * args)
2365 return PLy_output(LOG, self, args);
2369 PLy_info(PyObject * self, PyObject * args)
2371 return PLy_output(INFO, self, args);
2375 PLy_notice(PyObject * self, PyObject * args)
2377 return PLy_output(NOTICE, self, args);
2381 PLy_warning(PyObject * self, PyObject * args)
2383 return PLy_output(WARNING, self, args);
2387 PLy_error(PyObject * self, PyObject * args)
2389 return PLy_output(ERROR, self, args);
2393 PLy_fatal(PyObject * self, PyObject * args)
2395 return PLy_output(FATAL, self, args);
2400 PLy_output(volatile int level, PyObject * self, PyObject * args)
2404 MemoryContext oldcontext;
2406 so = PyObject_Str(args);
2407 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2410 sv = "Unable to parse error message in `plpy.elog'";
2413 oldcontext = CurrentMemoryContext;
2416 elog(level, "%s", sv);
2420 MemoryContextSwitchTo(oldcontext);
2421 PLy_error_in_progress = CopyErrorData();
2426 * returning NULL here causes the python interpreter to bail. when
2427 * control passes back to PLy_procedure_call, we check for PG
2428 * exceptions and re-throw the error.
2430 PyErr_SetString(PLy_exc_error, sv);
2438 * return a legal object so the interpreter will continue on its merry way
2446 * Get the name of the last procedure called by the backend (the
2447 * innermost, if a plpython procedure call calls the backend and the
2448 * backend calls another plpython procedure).
2450 * NB: this returns the SQL name, not the internal Python procedure name
2453 PLy_procedure_name(PLyProcedure * proc)
2456 return "<unknown procedure>";
2457 return proc->proname;
2460 /* output a python traceback/exception via the postgresql elog
2461 * function. not pretty.
2464 PLy_exception_set(PyObject * exc, const char *fmt,...)
2470 vsnprintf(buf, sizeof(buf), fmt, ap);
2473 PyErr_SetString(exc, buf);
2476 /* Emit a PG error or notice, together with any available info about the
2477 * current Python error. This should be used to propagate Python errors
2481 PLy_elog(int elevel, const char *fmt,...)
2488 xmsg = PLy_traceback(&xlevel);
2491 emsg = PLy_vprintf(fmt, ap);
2497 (errmsg("plpython: %s", emsg),
2498 (xmsg) ? errdetail("%s", xmsg) : 0));
2515 PLy_traceback(int *xlevel)
2527 * get the current exception
2529 PyErr_Fetch(&e, &v, &tb);
2532 * oops, no exception, return
2540 PyErr_NormalizeException(&e, &v, &tb);
2543 eob = PyObject_Str(e);
2544 if (v && ((vob = PyObject_Str(v)) != NULL))
2545 vstr = PyString_AsString(vob);
2550 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
2551 * because that function calls us, so we could end up with infinite
2552 * recursion. I'm not even sure if eob could be NULL here -- would an
2553 * Assert() be more appropriate?
2555 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
2556 xstr = PLy_printf("%s: %s", estr, vstr);
2563 * intuit an appropriate error level based on the exception type
2565 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
2567 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
2577 PLy_printf(const char *fmt,...)
2583 emsg = PLy_vprintf(fmt, ap);
2589 PLy_vprintf(const char *fmt, va_list ap)
2596 blen = strlen(fmt) * 2;
2599 buf = PLy_malloc(blen * sizeof(char));
2603 bchar = vsnprintf(buf, blen, fmt, ap);
2604 if (bchar > 0 && bchar < blen)
2612 buf = PLy_realloc(buf, blen);
2618 /* python module code */
2620 /* some dumb utility functions */
2622 PLy_malloc(size_t bytes)
2624 void *ptr = malloc(bytes);
2628 (errcode(ERRCODE_OUT_OF_MEMORY),
2629 errmsg("out of memory")));
2634 PLy_realloc(void *optr, size_t bytes)
2636 void *nptr = realloc(optr, bytes);
2640 (errcode(ERRCODE_OUT_OF_MEMORY),
2641 errmsg("out of memory")));
2646 PLy_strdup(const char *str)
2651 len = strlen(str) + 1;
2652 result = PLy_malloc(len);
2653 memcpy(result, str, len);
2658 /* define this away */