1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * This software is copyright by Andrew Bosma
5 * but is really shameless cribbed from pltcl.c by Jan Weick, and
6 * plperl.c by Mark Hollomon.
8 * The author hereby grants permission to use, copy, modify,
9 * distribute, and license this software and its documentation for any
10 * purpose, provided that existing copyright notices are retained in
11 * all copies and that this notice is included verbatim in any
12 * distributions. No written agreement, license, or royalty fee is
13 * required for any of the authorized uses. Modifications to this
14 * software may be copyrighted by their author and need not follow the
15 * licensing terms described here, provided that the new terms are
16 * clearly indicated on the first page of each file where they apply.
18 * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY
19 * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
20 * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
21 * DERIVATIVES THEREOF, EVEN IF THE AUTHOR HAVE BEEN ADVISED OF THE
22 * POSSIBILITY OF SUCH DAMAGE.
24 * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
25 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
27 * NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
28 * AND THE AUTHOR AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
29 * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
32 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.67 2005/12/26 04:28:48 neilc Exp $
34 *********************************************************************
44 /* postgreSQL stuff */
45 #include "access/heapam.h"
46 #include "catalog/pg_proc.h"
47 #include "catalog/pg_type.h"
48 #include "commands/trigger.h"
49 #include "executor/spi.h"
51 #include "nodes/makefuncs.h"
52 #include "parser/parse_type.h"
53 #include "tcop/tcopprot.h"
54 #include "utils/lsyscache.h"
55 #include "utils/memutils.h"
56 #include "utils/syscache.h"
57 #include "utils/typcache.h"
62 /* convert Postgresql Datum or tuple into a PyObject.
63 * input to Python. Tuples are converted to dictionary
67 typedef PyObject *(*PLyDatumToObFunc) (const char *);
69 typedef struct PLyDatumToOb
71 PLyDatumToObFunc func;
77 typedef struct PLyTupleToOb
83 typedef union PLyTypeInput
89 /* convert PyObject to a Postgresql Datum or tuple.
92 typedef struct PLyObToDatum
99 typedef struct PLyObToTuple
105 typedef union PLyTypeOutput
111 /* all we need to move Postgresql data to Python objects,
114 typedef struct PLyTypeInfo
121 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
122 * 1 rowtype 2 rowtype, but I/O functions not set up yet
127 /* cached procedure data
129 typedef struct PLyProcedure
131 char *proname; /* SQL name of procedure */
132 char *pyname; /* Python name of procedure */
133 TransactionId fn_xmin;
136 PLyTypeInfo result; /* also used to store info for trigger tuple
138 PLyTypeInfo args[FUNC_MAX_ARGS];
140 PyObject *code; /* compiled procedure code */
141 PyObject *statics; /* data saved across calls, local scope */
142 PyObject *globals; /* data saved across calls, global score */
143 PyObject *me; /* PyCObject containing pointer to this
150 typedef struct PLyPlanObject
153 void *plan; /* return of an SPI_saveplan */
160 typedef struct PLyResultObject
163 /* HeapTuple *tuples; */
164 PyObject *nrows; /* number of rows returned by query */
165 PyObject *rows; /* data rows, or None if no data returned */
166 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
170 /* function declarations
173 /* Two exported functions: first is the magic telling Postgresql
174 * what function call interface it implements. Second allows
175 * preinitialization of the interpreter during postmaster startup.
177 Datum plpython_call_handler(PG_FUNCTION_ARGS);
178 void plpython_init(void);
180 PG_FUNCTION_INFO_V1(plpython_call_handler);
182 /* most of the remaining of the declarations, all static
185 /* these should only be called once at the first call
186 * of plpython_call_handler. initialize the python interpreter
189 static void PLy_init_all(void);
190 static void PLy_init_interp(void);
191 static void PLy_init_plpy(void);
193 /* call PyErr_SetString with a vprint interface
196 PLy_exception_set(PyObject *, const char *,...)
197 __attribute__((format(printf, 2, 3)));
199 /* Get the innermost python procedure called from the backend.
201 static char *PLy_procedure_name(PLyProcedure *);
203 /* some utility functions
205 static void PLy_elog(int, const char *,...);
206 static char *PLy_traceback(int *);
207 static char *PLy_vprintf(const char *fmt, va_list ap);
208 static char *PLy_printf(const char *fmt,...);
210 static void *PLy_malloc(size_t);
211 static void *PLy_realloc(void *, size_t);
212 static char *PLy_strdup(const char *);
213 static void PLy_free(void *);
215 /* sub handlers for functions and triggers
217 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
218 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
220 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
221 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
223 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
224 TriggerData *, HeapTuple);
226 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
228 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
231 static PLyProcedure *PLy_procedure_create(FunctionCallInfo fcinfo,
233 HeapTuple procTup, char *key);
235 static void PLy_procedure_compile(PLyProcedure *, const char *);
236 static char *PLy_procedure_munge_source(const char *, const char *);
237 static void PLy_procedure_delete(PLyProcedure *);
239 static void PLy_typeinfo_init(PLyTypeInfo *);
240 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
241 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
242 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
243 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
244 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
245 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
246 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
248 /* conversion functions
250 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
251 static PyObject *PLyBool_FromString(const char *);
252 static PyObject *PLyFloat_FromString(const char *);
253 static PyObject *PLyInt_FromString(const char *);
254 static PyObject *PLyLong_FromString(const char *);
255 static PyObject *PLyString_FromString(const char *);
260 static bool PLy_first_call = true;
263 * Currently active plpython function
265 static PLyProcedure *PLy_curr_procedure = NULL;
268 * When a callback from Python into PG incurs an error, we temporarily store
269 * the error information here, and return NULL to the Python interpreter.
270 * Any further callback attempts immediately fail, and when the Python
271 * interpreter returns to the calling function, we re-throw the error (even if
272 * Python thinks it trapped the error and doesn't return NULL). Eventually
273 * this ought to be improved to let Python code really truly trap the error,
274 * but that's more of a change from the pre-8.0 semantics than I have time for
275 * now --- it will only be possible if the callback query is executed inside a
278 static ErrorData *PLy_error_in_progress = NULL;
280 static PyObject *PLy_interp_globals = NULL;
281 static PyObject *PLy_interp_safe_globals = NULL;
282 static PyObject *PLy_procedure_cache = NULL;
286 static PyObject *PLy_exc_error = NULL;
287 static PyObject *PLy_exc_fatal = NULL;
288 static PyObject *PLy_exc_spi_error = NULL;
290 /* some globals for the python module
292 static char PLy_plan_doc[] = {
293 "Store a PostgreSQL plan"
296 static char PLy_result_doc[] = {
297 "Results of a PostgreSQL query"
302 * the function definitions
306 * This routine is a crock, and so is everyplace that calls it. The problem
307 * is that the cached form of plpython functions/queries is allocated permanently
308 * (mostly via malloc()) and never released until backend exit. Subsidiary
309 * data structures such as fmgr info records therefore must live forever
310 * as well. A better implementation would store all this stuff in a per-
311 * function memory context that could be reclaimed at need. In the meantime,
312 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
313 * it might allocate, and whatever the eventual function might allocate using
314 * fn_mcxt, will live forever too.
317 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
319 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
323 plpython_call_handler(PG_FUNCTION_ARGS)
326 PLyProcedure *save_curr_proc;
327 PLyProcedure *volatile proc = NULL;
331 if (SPI_connect() != SPI_OK_CONNECT)
332 elog(ERROR, "could not connect to SPI manager");
334 save_curr_proc = PLy_curr_procedure;
338 if (CALLED_AS_TRIGGER(fcinfo))
340 TriggerData *tdata = (TriggerData *) fcinfo->context;
343 proc = PLy_procedure_get(fcinfo,
344 RelationGetRelid(tdata->tg_relation));
345 PLy_curr_procedure = proc;
346 trv = PLy_trigger_handler(fcinfo, proc);
347 retval = PointerGetDatum(trv);
351 proc = PLy_procedure_get(fcinfo, InvalidOid);
352 PLy_curr_procedure = proc;
353 retval = PLy_function_handler(fcinfo, proc);
358 PLy_curr_procedure = save_curr_proc;
361 /* note: Py_DECREF needs braces around it, as of 2003/08 */
369 PLy_curr_procedure = save_curr_proc;
376 /* trigger and function sub handlers
378 * the python function is expected to return Py_None if the tuple is
379 * acceptable and unmodified. Otherwise it should return a PyString
380 * object who's value is SKIP, or MODIFY. SKIP means don't perform
381 * this action. MODIFY means the tuple has been modified, so update
382 * tuple and perform action. SKIP and MODIFY assume the trigger fires
383 * BEFORE the event and is ROW level. postgres expects the function
384 * to take no arguments and return an argument of type trigger.
387 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
390 PyObject *volatile plargs = NULL;
391 PyObject *volatile plrv = NULL;
395 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
396 plrv = PLy_procedure_call(proc, "TD", plargs);
398 Assert(plrv != NULL);
399 Assert(!PLy_error_in_progress);
402 * Disconnect from SPI manager
404 if (SPI_finish() != SPI_OK_FINISH)
405 elog(ERROR, "SPI_finish failed");
408 * return of None means we're happy with the tuple
414 if (!PyString_Check(plrv))
415 elog(ERROR, "expected trigger to return None or a String");
417 srv = PyString_AsString(plrv);
418 if (pg_strcasecmp(srv, "SKIP") == 0)
420 else if (pg_strcasecmp(srv, "MODIFY") == 0)
422 TriggerData *tdata = (TriggerData *) fcinfo->context;
424 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
425 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
426 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
428 elog(WARNING, "ignoring modified tuple in DELETE trigger");
430 else if (pg_strcasecmp(srv, "OK") != 0)
433 * hmmm, perhaps they only read the pltcl page, not a
434 * surprising thing since i've written no documentation, so
435 * accept a belated OK
437 elog(ERROR, "expected return to be \"SKIP\" or \"MODIFY\"");
457 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
460 PyObject *volatile plntup;
461 PyObject *volatile plkeys;
462 PyObject *volatile platt;
463 PyObject *volatile plval;
464 PyObject *volatile plstr;
470 int *volatile modattrs;
471 Datum *volatile modvalues;
472 char *volatile modnulls;
475 plntup = plkeys = platt = plval = plstr = NULL;
482 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
483 elog(ERROR, "TD[\"new\"] deleted, unable to modify tuple");
484 if (!PyDict_Check(plntup))
485 elog(ERROR, "TD[\"new\"] is not a dictionary object");
488 plkeys = PyDict_Keys(plntup);
489 natts = PyList_Size(plkeys);
491 modattrs = (int *) palloc(natts * sizeof(int));
492 modvalues = (Datum *) palloc(natts * sizeof(Datum));
493 modnulls = (char *) palloc(natts * sizeof(char));
495 tupdesc = tdata->tg_relation->rd_att;
497 for (i = 0; i < natts; i++)
501 platt = PyList_GetItem(plkeys, i);
502 if (!PyString_Check(platt))
503 elog(ERROR, "attribute name is not a string");
504 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
505 if (attn == SPI_ERROR_NOATTRIBUTE)
506 elog(ERROR, "invalid attribute \"%s\" in tuple",
507 PyString_AsString(platt));
510 plval = PyDict_GetItem(plntup, platt);
512 elog(FATAL, "python interpreter is probably corrupted");
518 if (plval != Py_None && !tupdesc->attrs[atti]->attisdropped)
520 plstr = PyObject_Str(plval);
522 PLy_elog(ERROR, "function \"%s\" could not modify tuple", proc->proname);
523 src = PyString_AsString(plstr);
525 modvalues[i] = FunctionCall3(&proc->result.out.r.atts[atti].typfunc,
526 CStringGetDatum(src),
527 ObjectIdGetDatum(proc->result.out.r.atts[atti].typioparam),
528 Int32GetDatum(tupdesc->attrs[atti]->atttypmod));
536 modvalues[i] = (Datum) 0;
544 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
545 modattrs, modvalues, modnulls);
547 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
579 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
581 TriggerData *tdata = (TriggerData *) fcinfo->context;
590 PyObject *volatile pltdata = NULL;
595 pltdata = PyDict_New();
597 PLy_elog(ERROR, "could not build arguments for trigger procedure");
599 pltname = PyString_FromString(tdata->tg_trigger->tgname);
600 PyDict_SetItemString(pltdata, "name", pltname);
603 stroid = DatumGetCString(DirectFunctionCall1(oidout,
604 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
605 pltrelid = PyString_FromString(stroid);
606 PyDict_SetItemString(pltdata, "relid", pltrelid);
610 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
611 pltwhen = PyString_FromString("BEFORE");
612 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
613 pltwhen = PyString_FromString("AFTER");
616 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
617 pltwhen = NULL; /* keep compiler quiet */
619 PyDict_SetItemString(pltdata, "when", pltwhen);
622 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
624 pltlevel = PyString_FromString("ROW");
625 PyDict_SetItemString(pltdata, "level", pltlevel);
628 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
630 pltevent = PyString_FromString("INSERT");
632 PyDict_SetItemString(pltdata, "old", Py_None);
633 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
634 tdata->tg_relation->rd_att);
635 PyDict_SetItemString(pltdata, "new", pytnew);
637 *rv = tdata->tg_trigtuple;
639 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
641 pltevent = PyString_FromString("DELETE");
643 PyDict_SetItemString(pltdata, "new", Py_None);
644 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
645 tdata->tg_relation->rd_att);
646 PyDict_SetItemString(pltdata, "old", pytold);
648 *rv = tdata->tg_trigtuple;
650 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
652 pltevent = PyString_FromString("UPDATE");
654 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
655 tdata->tg_relation->rd_att);
656 PyDict_SetItemString(pltdata, "new", pytnew);
658 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
659 tdata->tg_relation->rd_att);
660 PyDict_SetItemString(pltdata, "old", pytold);
662 *rv = tdata->tg_newtuple;
666 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
667 pltevent = NULL; /* keep compiler quiet */
670 PyDict_SetItemString(pltdata, "event", pltevent);
673 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
675 pltlevel = PyString_FromString("STATEMENT");
676 PyDict_SetItemString(pltdata, "level", pltlevel);
679 PyDict_SetItemString(pltdata, "old", Py_None);
680 PyDict_SetItemString(pltdata, "new", Py_None);
683 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
684 pltevent = PyString_FromString("INSERT");
685 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
686 pltevent = PyString_FromString("DELETE");
687 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
688 pltevent = PyString_FromString("UPDATE");
691 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
692 pltevent = NULL; /* keep compiler quiet */
695 PyDict_SetItemString(pltdata, "event", pltevent);
699 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
701 if (tdata->tg_trigger->tgnargs)
709 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
710 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
712 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
715 * stolen, don't Py_DECREF
717 PyList_SetItem(pltargs, i, pltarg);
725 PyDict_SetItemString(pltdata, "args", pltargs);
740 /* function handler and friends
743 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
746 PyObject *volatile plargs = NULL;
747 PyObject *volatile plrv = NULL;
748 PyObject *volatile plrv_so = NULL;
753 plargs = PLy_function_build_args(fcinfo, proc);
754 plrv = PLy_procedure_call(proc, "args", plargs);
756 Assert(plrv != NULL);
757 Assert(!PLy_error_in_progress);
760 * Disconnect from SPI manager and then create the return values datum
761 * (if the input function does a palloc for it this must not be
762 * allocated in the SPI memory context because SPI_finish would free
765 if (SPI_finish() != SPI_OK_FINISH)
766 elog(ERROR, "SPI_finish failed");
769 * convert the python PyObject to a postgresql Datum
773 fcinfo->isnull = true;
778 fcinfo->isnull = false;
779 plrv_so = PyObject_Str(plrv);
781 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
782 plrv_sc = PyString_AsString(plrv_so);
783 rv = FunctionCall3(&proc->result.out.d.typfunc,
784 PointerGetDatum(plrv_sc),
785 ObjectIdGetDatum(proc->result.out.d.typioparam),
808 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
812 PyDict_SetItemString(proc->globals, kargs, vargs);
813 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
814 proc->globals, proc->globals);
817 * If there was an error in a PG callback, propagate that no matter what
818 * Python claims about its success.
820 if (PLy_error_in_progress)
822 ErrorData *edata = PLy_error_in_progress;
824 PLy_error_in_progress = NULL;
828 if (rv == NULL || PyErr_Occurred())
831 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
838 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
840 PyObject *volatile arg = NULL;
841 PyObject *volatile args = NULL;
846 args = PyList_New(proc->nargs);
847 for (i = 0; i < proc->nargs; i++)
849 if (proc->args[i].is_rowtype > 0)
851 if (fcinfo->argnull[i])
859 HeapTupleData tmptup;
861 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
862 /* Extract rowtype info and find a tupdesc */
863 tupType = HeapTupleHeaderGetTypeId(td);
864 tupTypmod = HeapTupleHeaderGetTypMod(td);
865 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
867 /* Set up I/O funcs if not done yet */
868 if (proc->args[i].is_rowtype != 1)
869 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
871 /* Build a temporary HeapTuple control structure */
872 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
875 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
880 if (fcinfo->argnull[i])
887 dt = FunctionCall3(&(proc->args[i].in.d.typfunc),
889 ObjectIdGetDatum(proc->args[i].in.d.typioparam),
891 ct = DatumGetCString(dt);
892 arg = (proc->args[i].in.d.func) (ct);
904 * FIXME -- error check this
906 PyList_SetItem(args, i, arg);
923 * PLyProcedure functions
926 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
927 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
928 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
931 static PLyProcedure *
932 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
938 PLyProcedure *proc = NULL;
941 fn_oid = fcinfo->flinfo->fn_oid;
942 procTup = SearchSysCache(PROCOID,
943 ObjectIdGetDatum(fn_oid),
945 if (!HeapTupleIsValid(procTup))
946 elog(ERROR, "cache lookup failed for function %u", fn_oid);
948 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
949 if (rv >= sizeof(key) || rv < 0)
950 elog(ERROR, "key too long");
952 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
957 if (!PyCObject_Check(plproc))
958 elog(FATAL, "expected a PyCObject, didn't get one");
960 proc = PyCObject_AsVoidPtr(plproc);
961 if (proc->me != plproc)
962 elog(FATAL, "proc->me != plproc");
963 /* did we find an up-to-date cache entry? */
964 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
965 proc->fn_cmin != HeapTupleHeaderGetCmin(procTup->t_data))
973 proc = PLy_procedure_create(fcinfo, tgreloid, procTup, key);
975 ReleaseSysCache(procTup);
980 static PLyProcedure *
981 PLy_procedure_create(FunctionCallInfo fcinfo, Oid tgreloid,
982 HeapTuple procTup, char *key)
984 char procName[NAMEDATALEN + 256];
985 Form_pg_proc procStruct;
986 PLyProcedure *volatile proc;
987 char *volatile procSource = NULL;
993 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
995 if (OidIsValid(tgreloid))
996 rv = snprintf(procName, sizeof(procName),
997 "__plpython_procedure_%s_%u_trigger_%u",
998 NameStr(procStruct->proname),
999 fcinfo->flinfo->fn_oid,
1002 rv = snprintf(procName, sizeof(procName),
1003 "__plpython_procedure_%s_%u",
1004 NameStr(procStruct->proname),
1005 fcinfo->flinfo->fn_oid);
1006 if (rv >= sizeof(procName) || rv < 0)
1007 elog(ERROR, "procedure name would overrun buffer");
1009 proc = PLy_malloc(sizeof(PLyProcedure));
1010 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1011 proc->pyname = PLy_strdup(procName);
1012 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1013 proc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1014 /* Remember if function is STABLE/IMMUTABLE */
1016 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1017 PLy_typeinfo_init(&proc->result);
1018 for (i = 0; i < FUNC_MAX_ARGS; i++)
1019 PLy_typeinfo_init(&proc->args[i]);
1021 proc->code = proc->statics = NULL;
1022 proc->globals = proc->me = NULL;
1027 * get information required for output conversion of the return value,
1028 * but only if this isn't a trigger.
1030 if (!CALLED_AS_TRIGGER(fcinfo))
1032 HeapTuple rvTypeTup;
1033 Form_pg_type rvTypeStruct;
1035 rvTypeTup = SearchSysCache(TYPEOID,
1036 ObjectIdGetDatum(procStruct->prorettype),
1038 if (!HeapTupleIsValid(rvTypeTup))
1039 elog(ERROR, "cache lookup failed for type %u",
1040 procStruct->prorettype);
1041 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1043 /* Disallow pseudotype result */
1044 if (rvTypeStruct->typtype == 'p')
1046 if (procStruct->prorettype == TRIGGEROID)
1048 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1049 errmsg("trigger functions may only be called as triggers")));
1052 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1053 errmsg("plpython functions cannot return type %s",
1054 format_type_be(procStruct->prorettype))));
1057 if (rvTypeStruct->typtype == 'c')
1059 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1060 errmsg("plpython functions cannot return tuples yet")));
1062 PLy_output_datum_func(&proc->result, rvTypeTup);
1064 ReleaseSysCache(rvTypeTup);
1069 * input/output conversion for trigger tuples. use the result
1070 * TypeInfo variable to store the tuple conversion info.
1072 TriggerData *tdata = (TriggerData *) fcinfo->context;
1074 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1075 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1079 * now get information required for input conversion of the procedures
1082 proc->nargs = fcinfo->nargs;
1083 for (i = 0; i < fcinfo->nargs; i++)
1085 HeapTuple argTypeTup;
1086 Form_pg_type argTypeStruct;
1088 argTypeTup = SearchSysCache(TYPEOID,
1089 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1091 if (!HeapTupleIsValid(argTypeTup))
1092 elog(ERROR, "cache lookup failed for type %u",
1093 procStruct->proargtypes.values[i]);
1094 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1096 /* Disallow pseudotype argument */
1097 if (argTypeStruct->typtype == 'p')
1099 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1100 errmsg("plpython functions cannot take type %s",
1101 format_type_be(procStruct->proargtypes.values[i]))));
1103 if (argTypeStruct->typtype != 'c')
1104 PLy_input_datum_func(&(proc->args[i]),
1105 procStruct->proargtypes.values[i],
1108 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1110 ReleaseSysCache(argTypeTup);
1115 * get the text of the function.
1117 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1118 Anum_pg_proc_prosrc, &isnull);
1120 elog(ERROR, "null prosrc");
1121 procSource = DatumGetCString(DirectFunctionCall1(textout,
1124 PLy_procedure_compile(proc, procSource);
1128 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1129 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1133 PLy_procedure_delete(proc);
1145 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1147 PyObject *crv = NULL;
1150 proc->globals = PyDict_Copy(PLy_interp_globals);
1153 * SD is private preserved data between calls GD is global data shared by
1156 proc->statics = PyDict_New();
1157 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1160 * insert the function code into the interpreter
1162 msrc = PLy_procedure_munge_source(proc->pyname, src);
1163 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1166 if (crv != NULL && (!PyErr_Occurred()))
1169 char call[NAMEDATALEN + 256];
1174 * compile a call to the function
1176 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1177 if (clen < 0 || clen >= sizeof(call))
1178 elog(ERROR, "string would overflow buffer");
1179 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1180 if (proc->code != NULL && (!PyErr_Occurred()))
1186 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1190 PLy_procedure_munge_source(const char *name, const char *src)
1199 * room for function source and the def statement
1201 mlen = (strlen(src) * 2) + strlen(name) + 16;
1203 mrc = PLy_malloc(mlen);
1204 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1205 Assert(plen >= 0 && plen < mlen);
1212 if (*sp == '\r' && *(sp + 1) == '\n')
1215 if (*sp == '\n' || *sp == '\r')
1228 if (mp > (mrc + mlen))
1229 elog(FATAL, "buffer overrun in PLy_munge_source");
1235 PLy_procedure_delete(PLyProcedure * proc)
1239 Py_XDECREF(proc->code);
1240 Py_XDECREF(proc->statics);
1241 Py_XDECREF(proc->globals);
1242 Py_XDECREF(proc->me);
1244 PLy_free(proc->proname);
1246 PLy_free(proc->pyname);
1247 for (i = 0; i < proc->nargs; i++)
1248 if (proc->args[i].is_rowtype == 1)
1250 if (proc->args[i].in.r.atts)
1251 PLy_free(proc->args[i].in.r.atts);
1252 if (proc->args[i].out.r.atts)
1253 PLy_free(proc->args[i].out.r.atts);
1257 /* conversion functions. remember output from python is
1258 * input to postgresql, and vis versa.
1261 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1265 if (arg->is_rowtype == 0)
1266 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1268 arg->is_rowtype = 1;
1269 arg->in.r.natts = desc->natts;
1270 arg->in.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1272 for (i = 0; i < desc->natts; i++)
1276 if (desc->attrs[i]->attisdropped)
1279 typeTup = SearchSysCache(TYPEOID,
1280 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1282 if (!HeapTupleIsValid(typeTup))
1283 elog(ERROR, "cache lookup failed for type %u",
1284 desc->attrs[i]->atttypid);
1286 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1287 desc->attrs[i]->atttypid,
1290 ReleaseSysCache(typeTup);
1295 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1299 if (arg->is_rowtype == 0)
1300 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1302 arg->is_rowtype = 1;
1303 arg->out.r.natts = desc->natts;
1304 arg->out.r.atts = PLy_malloc(desc->natts * sizeof(PLyDatumToOb));
1306 for (i = 0; i < desc->natts; i++)
1310 if (desc->attrs[i]->attisdropped)
1313 typeTup = SearchSysCache(TYPEOID,
1314 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1316 if (!HeapTupleIsValid(typeTup))
1317 elog(ERROR, "cache lookup failed for type %u",
1318 desc->attrs[i]->atttypid);
1320 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1322 ReleaseSysCache(typeTup);
1327 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1329 if (arg->is_rowtype > 0)
1330 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1331 arg->is_rowtype = 0;
1332 PLy_output_datum_func2(&(arg->out.d), typeTup);
1336 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1338 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1340 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1341 arg->typioparam = getTypeIOParam(typeTup);
1342 arg->typbyval = typeStruct->typbyval;
1346 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1348 if (arg->is_rowtype > 0)
1349 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1350 arg->is_rowtype = 0;
1351 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1355 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1357 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1359 /* Get the type's conversion information */
1360 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1361 arg->typioparam = getTypeIOParam(typeTup);
1362 arg->typbyval = typeStruct->typbyval;
1364 /* Determine which kind of Python object we will convert to */
1368 arg->func = PLyBool_FromString;
1373 arg->func = PLyFloat_FromString;
1377 arg->func = PLyInt_FromString;
1380 arg->func = PLyLong_FromString;
1383 arg->func = PLyString_FromString;
1389 PLy_typeinfo_init(PLyTypeInfo * arg)
1391 arg->is_rowtype = -1;
1392 arg->in.r.natts = arg->out.r.natts = 0;
1393 arg->in.r.atts = NULL;
1394 arg->out.r.atts = NULL;
1398 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1400 if (arg->is_rowtype == 1)
1403 PLy_free(arg->in.r.atts);
1404 if (arg->out.r.atts)
1405 PLy_free(arg->out.r.atts);
1409 /* assumes that a bool is always returned as a 't' or 'f'
1412 PLyBool_FromString(const char *src)
1415 return PyInt_FromLong(1);
1416 return PyInt_FromLong(0);
1420 PLyFloat_FromString(const char *src)
1426 v = strtod(src, &eptr);
1427 if (*eptr != '\0' || errno)
1429 return PyFloat_FromDouble(v);
1433 PLyInt_FromString(const char *src)
1439 v = strtol(src, &eptr, 0);
1440 if (*eptr != '\0' || errno)
1442 return PyInt_FromLong(v);
1446 PLyLong_FromString(const char *src)
1448 return PyLong_FromString((char *) src, NULL, 0);
1452 PLyString_FromString(const char *src)
1454 return PyString_FromString(src);
1458 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1460 PyObject *volatile dict;
1463 if (info->is_rowtype != 1)
1464 elog(ERROR, "PLyTypeInfo structure describes a datum");
1466 dict = PyDict_New();
1468 PLy_elog(ERROR, "could not create tuple dictionary");
1472 for (i = 0; i < info->in.r.natts; i++)
1481 if (desc->attrs[i]->attisdropped)
1484 key = NameStr(desc->attrs[i]->attname);
1485 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1487 if (is_null || info->in.r.atts[i].func == NULL)
1488 PyDict_SetItemString(dict, key, Py_None);
1491 vdat = FunctionCall3(&info->in.r.atts[i].typfunc,
1493 ObjectIdGetDatum(info->in.r.atts[i].typioparam),
1494 Int32GetDatum(desc->attrs[i]->atttypmod));
1495 vsrc = DatumGetCString(vdat);
1498 * no exceptions allowed
1500 value = info->in.r.atts[i].func(vsrc);
1502 PyDict_SetItemString(dict, key, value);
1517 /* initialization, some python variables function declared here
1520 /* 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
1532 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1533 static PyObject *PLy_plan_new(void);
1534 static void PLy_plan_dealloc(PyObject *);
1535 static PyObject *PLy_plan_getattr(PyObject *, char *);
1536 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1538 static PyObject *PLy_result_new(void);
1539 static void PLy_result_dealloc(PyObject *);
1540 static PyObject *PLy_result_getattr(PyObject *, char *);
1541 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1542 static PyObject *PLy_result_status(PyObject *, PyObject *);
1543 static int PLy_result_length(PyObject *);
1544 static PyObject *PLy_result_item(PyObject *, int);
1545 static PyObject *PLy_result_slice(PyObject *, int, int);
1546 static int PLy_result_ass_item(PyObject *, int, PyObject *);
1547 static int PLy_result_ass_slice(PyObject *, int, int, PyObject *);
1550 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
1551 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
1552 static PyObject *PLy_spi_execute_query(char *query, long limit);
1553 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
1554 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
1557 static PyTypeObject PLy_PlanType = {
1558 PyObject_HEAD_INIT(NULL)
1560 "PLyPlan", /* tp_name */
1561 sizeof(PLyPlanObject), /* tp_size */
1562 0, /* tp_itemsize */
1567 (destructor) PLy_plan_dealloc, /* tp_dealloc */
1569 (getattrfunc) PLy_plan_getattr, /* tp_getattr */
1573 0, /* tp_as_number */
1574 0, /* tp_as_sequence */
1575 0, /* tp_as_mapping */
1579 0, /* tp_getattro */
1580 0, /* tp_setattro */
1581 0, /* tp_as_buffer */
1583 PLy_plan_doc, /* tp_doc */
1586 static PyMethodDef PLy_plan_methods[] = {
1587 {"status", PLy_plan_status, METH_VARARGS, NULL},
1588 {NULL, NULL, 0, NULL}
1592 static PySequenceMethods PLy_result_as_sequence = {
1593 (inquiry) PLy_result_length, /* sq_length */
1594 (binaryfunc) 0, /* sq_concat */
1595 (intargfunc) 0, /* sq_repeat */
1596 (intargfunc) PLy_result_item, /* sq_item */
1597 (intintargfunc) PLy_result_slice, /* sq_slice */
1598 (intobjargproc) PLy_result_ass_item, /* sq_ass_item */
1599 (intintobjargproc) PLy_result_ass_slice, /* sq_ass_slice */
1602 static PyTypeObject PLy_ResultType = {
1603 PyObject_HEAD_INIT(NULL)
1605 "PLyResult", /* tp_name */
1606 sizeof(PLyResultObject), /* tp_size */
1607 0, /* tp_itemsize */
1612 (destructor) PLy_result_dealloc, /* tp_dealloc */
1614 (getattrfunc) PLy_result_getattr, /* tp_getattr */
1618 0, /* tp_as_number */
1619 &PLy_result_as_sequence, /* tp_as_sequence */
1620 0, /* tp_as_mapping */
1624 0, /* tp_getattro */
1625 0, /* tp_setattro */
1626 0, /* tp_as_buffer */
1628 PLy_result_doc, /* tp_doc */
1631 static PyMethodDef PLy_result_methods[] = {
1632 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
1633 {"status", PLy_result_status, METH_VARARGS, NULL},
1634 {NULL, NULL, 0, NULL}
1637 static PyMethodDef PLy_methods[] = {
1641 {"debug", PLy_debug, METH_VARARGS, NULL},
1642 {"log", PLy_log, METH_VARARGS, NULL},
1643 {"info", PLy_info, METH_VARARGS, NULL},
1644 {"notice", PLy_notice, METH_VARARGS, NULL},
1645 {"warning", PLy_warning, METH_VARARGS, NULL},
1646 {"error", PLy_error, METH_VARARGS, NULL},
1647 {"fatal", PLy_fatal, METH_VARARGS, NULL},
1650 * create a stored plan
1652 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
1655 * execute a plan or query
1657 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
1659 {NULL, NULL, 0, NULL}
1663 /* 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
1729 PLy_result_new(void)
1731 PLyResultObject *ob;
1733 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
1736 /* ob->tuples = NULL; */
1739 ob->status = Py_None;
1740 ob->nrows = PyInt_FromLong(-1);
1741 ob->rows = PyList_New(0);
1743 return (PyObject *) ob;
1747 PLy_result_dealloc(PyObject * arg)
1749 PLyResultObject *ob = (PLyResultObject *) arg;
1751 Py_XDECREF(ob->nrows);
1752 Py_XDECREF(ob->rows);
1753 Py_XDECREF(ob->status);
1759 PLy_result_getattr(PyObject * self, char *name)
1761 return Py_FindMethod(PLy_result_methods, self, name);
1765 PLy_result_nrows(PyObject * self, PyObject * args)
1767 PLyResultObject *ob = (PLyResultObject *) self;
1769 Py_INCREF(ob->nrows);
1774 PLy_result_status(PyObject * self, PyObject * args)
1776 PLyResultObject *ob = (PLyResultObject *) self;
1778 Py_INCREF(ob->status);
1783 PLy_result_length(PyObject * arg)
1785 PLyResultObject *ob = (PLyResultObject *) arg;
1787 return PyList_Size(ob->rows);
1791 PLy_result_item(PyObject * arg, int idx)
1794 PLyResultObject *ob = (PLyResultObject *) arg;
1796 rv = PyList_GetItem(ob->rows, idx);
1803 PLy_result_ass_item(PyObject * arg, int idx, PyObject * item)
1806 PLyResultObject *ob = (PLyResultObject *) arg;
1809 rv = PyList_SetItem(ob->rows, idx, item);
1814 PLy_result_slice(PyObject * arg, int lidx, int hidx)
1817 PLyResultObject *ob = (PLyResultObject *) arg;
1819 rv = PyList_GetSlice(ob->rows, lidx, hidx);
1827 PLy_result_ass_slice(PyObject * arg, int lidx, int hidx, PyObject * slice)
1830 PLyResultObject *ob = (PLyResultObject *) arg;
1832 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
1839 PLy_spi_prepare(PyObject * self, PyObject * args)
1841 PLyPlanObject *plan;
1842 PyObject *list = NULL;
1843 PyObject *volatile optr = NULL;
1846 MemoryContext oldcontext;
1848 /* Can't execute more if we have an unhandled error */
1849 if (PLy_error_in_progress)
1851 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1855 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
1857 PyErr_SetString(PLy_exc_spi_error,
1858 "Invalid arguments for plpy.prepare()");
1862 if (list && (!PySequence_Check(list)))
1864 PyErr_SetString(PLy_exc_spi_error,
1865 "Second argument in plpy.prepare() must be a sequence");
1869 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
1872 oldcontext = CurrentMemoryContext;
1880 nargs = PySequence_Length(list);
1883 plan->nargs = nargs;
1884 plan->types = PLy_malloc(sizeof(Oid) * nargs);
1885 plan->values = PLy_malloc(sizeof(Datum) * nargs);
1886 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
1889 * the other loop might throw an exception, if PLyTypeInfo
1890 * member isn't properly initialized the Py_DECREF(plan) will
1893 for (i = 0; i < nargs; i++)
1895 PLy_typeinfo_init(&plan->args[i]);
1896 plan->values[i] = (Datum) NULL;
1899 for (i = 0; i < nargs; i++)
1903 Form_pg_type typeStruct;
1905 optr = PySequence_GetItem(list, i);
1906 if (!PyString_Check(optr))
1907 elog(ERROR, "Type names must be strings.");
1908 sptr = PyString_AsString(optr);
1911 * XXX should extend this to allow qualified type names
1913 typeTup = typenameType(makeTypeName(sptr));
1915 optr = NULL; /* this is important */
1917 plan->types[i] = HeapTupleGetOid(typeTup);
1918 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1919 if (typeStruct->typtype != 'c')
1920 PLy_output_datum_func(&plan->args[i], typeTup);
1922 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
1923 ReleaseSysCache(typeTup);
1928 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
1929 if (plan->plan == NULL)
1930 elog(ERROR, "SPI_prepare failed: %s",
1931 SPI_result_code_string(SPI_result));
1933 /* transfer plan from procCxt to topCxt */
1934 tmpplan = plan->plan;
1935 plan->plan = SPI_saveplan(tmpplan);
1936 SPI_freeplan(tmpplan);
1937 if (plan->plan == NULL)
1938 elog(ERROR, "SPI_saveplan failed: %s",
1939 SPI_result_code_string(SPI_result));
1943 MemoryContextSwitchTo(oldcontext);
1944 PLy_error_in_progress = CopyErrorData();
1948 if (!PyErr_Occurred())
1949 PyErr_SetString(PLy_exc_spi_error,
1950 "Unknown error in PLy_spi_prepare");
1951 /* XXX this oughta be replaced with errcontext mechanism */
1952 PLy_elog(WARNING, "in function %s:",
1953 PLy_procedure_name(PLy_curr_procedure));
1958 return (PyObject *) plan;
1961 /* execute(query="select * from foo", limit=5)
1962 * execute(plan=plan, values=(foo, bar), limit=5)
1965 PLy_spi_execute(PyObject * self, PyObject * args)
1969 PyObject *list = NULL;
1972 /* Can't execute more if we have an unhandled error */
1973 if (PLy_error_in_progress)
1975 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
1979 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
1980 return PLy_spi_execute_query(query, limit);
1984 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
1985 is_PLyPlanObject(plan))
1986 return PLy_spi_execute_plan(plan, list, limit);
1988 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
1993 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
1998 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)
2022 PyObject *so = PyObject_Str(list);
2025 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2026 PLy_procedure_name(PLy_curr_procedure));
2027 sv = PyString_AsString(so);
2028 PLy_exception_set(PLy_exc_spi_error,
2029 "Expected sequence of %d arguments, got %d. %s",
2030 plan->nargs, nargs, sv);
2036 oldcontext = CurrentMemoryContext;
2039 nulls = palloc(nargs * sizeof(char));
2041 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));
2054 sv = PyString_AsString(so);
2057 * FIXME -- if this elogs, we have Python reference leak
2060 FunctionCall3(&(plan->args[i].out.d.typfunc),
2061 CStringGetDatum(sv),
2062 ObjectIdGetDatum(plan->args[i].out.d.typioparam),
2073 plan->values[i] = (Datum) 0;
2078 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2079 PLy_curr_procedure->fn_readonly, limit);
2085 MemoryContextSwitchTo(oldcontext);
2086 PLy_error_in_progress = CopyErrorData();
2090 * cleanup plan->values array
2092 for (i = 0; i < nargs; i++)
2094 if (!plan->args[i].out.d.typbyval &&
2095 (plan->values[i] != (Datum) NULL))
2097 pfree(DatumGetPointer(plan->values[i]));
2098 plan->values[i] = (Datum) NULL;
2102 if (!PyErr_Occurred())
2103 PyErr_SetString(PLy_exc_error,
2104 "Unknown error in PLy_spi_execute_plan");
2105 /* XXX this oughta be replaced with errcontext mechanism */
2106 PLy_elog(WARNING, "in function %s:",
2107 PLy_procedure_name(PLy_curr_procedure));
2112 for (i = 0; i < nargs; i++)
2114 if (!plan->args[i].out.d.typbyval &&
2115 (plan->values[i] != (Datum) NULL))
2117 pfree(DatumGetPointer(plan->values[i]));
2118 plan->values[i] = (Datum) NULL;
2124 PLy_exception_set(PLy_exc_spi_error,
2125 "SPI_execute_plan failed: %s",
2126 SPI_result_code_string(rv));
2130 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2134 PLy_spi_execute_query(char *query, long limit)
2137 MemoryContext oldcontext;
2139 oldcontext = CurrentMemoryContext;
2142 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2146 MemoryContextSwitchTo(oldcontext);
2147 PLy_error_in_progress = CopyErrorData();
2149 if (!PyErr_Occurred())
2150 PyErr_SetString(PLy_exc_spi_error,
2151 "Unknown error in PLy_spi_execute_query");
2152 /* XXX this oughta be replaced with errcontext mechanism */
2153 PLy_elog(WARNING, "in function %s:",
2154 PLy_procedure_name(PLy_curr_procedure));
2161 PLy_exception_set(PLy_exc_spi_error,
2162 "SPI_execute failed: %s",
2163 SPI_result_code_string(rv));
2167 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2171 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2173 PLyResultObject *result;
2174 MemoryContext oldcontext;
2176 result = (PLyResultObject *) PLy_result_new();
2177 Py_DECREF(result->status);
2178 result->status = PyInt_FromLong(status);
2180 if (status == SPI_OK_UTILITY)
2182 Py_DECREF(result->nrows);
2183 result->nrows = PyInt_FromLong(0);
2185 else if (status != SPI_OK_SELECT)
2187 Py_DECREF(result->nrows);
2188 result->nrows = PyInt_FromLong(rows);
2195 PLy_typeinfo_init(&args);
2196 Py_DECREF(result->nrows);
2197 result->nrows = PyInt_FromLong(rows);
2199 oldcontext = CurrentMemoryContext;
2204 Py_DECREF(result->rows);
2205 result->rows = PyList_New(rows);
2207 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2208 for (i = 0; i < rows; i++)
2210 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2213 PyList_SetItem(result->rows, i, row);
2215 PLy_typeinfo_dealloc(&args);
2217 SPI_freetuptable(tuptable);
2222 MemoryContextSwitchTo(oldcontext);
2223 PLy_error_in_progress = CopyErrorData();
2225 if (!PyErr_Occurred())
2226 PyErr_SetString(PLy_exc_error,
2227 "Unknown error in PLy_spi_execute_fetch_result");
2229 PLy_typeinfo_dealloc(&args);
2235 return (PyObject *) result;
2240 * language handler and interpreter initialization
2244 * plpython_init() - Initialize everything that can be
2245 * safely initialized during postmaster
2248 * DO NOT make this static --- it has to be callable by preload
2253 static volatile bool init_active = false;
2255 /* Do initialization only once */
2256 if (!PLy_first_call)
2260 elog(FATAL, "initialization of language module failed");
2266 if (PyErr_Occurred())
2267 PLy_elog(FATAL, "untrapped error in initialization");
2268 PLy_procedure_cache = PyDict_New();
2269 if (PLy_procedure_cache == NULL)
2270 PLy_elog(ERROR, "could not create procedure cache");
2272 PLy_first_call = false;
2278 /* Execute postmaster-startup safe initialization */
2283 * Any other initialization that must be done each time a new backend
2284 * starts -- currently none
2289 PLy_init_interp(void)
2293 mainmod = PyImport_AddModule("__main__");
2294 if (mainmod == NULL || PyErr_Occurred())
2295 PLy_elog(ERROR, "could not import \"__main__\" module.");
2297 PLy_interp_globals = PyModule_GetDict(mainmod);
2298 PLy_interp_safe_globals = PyDict_New();
2299 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2301 if (PLy_interp_globals == NULL || PyErr_Occurred())
2302 PLy_elog(ERROR, "could not initialize globals");
2315 * initialize plpy module
2317 PLy_PlanType.ob_type = PLy_ResultType.ob_type = &PyType_Type;
2318 plpy = Py_InitModule("plpy", PLy_methods);
2319 plpy_dict = PyModule_GetDict(plpy);
2321 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2323 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2324 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2325 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2326 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2327 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2328 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2331 * initialize main module, and add plpy
2333 main_mod = PyImport_AddModule("__main__");
2334 main_dict = PyModule_GetDict(main_mod);
2335 plpy_mod = PyImport_AddModule("plpy");
2336 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2337 if (PyErr_Occurred())
2338 elog(ERROR, "could not init plpy");
2341 /* the python interface to the elog function
2342 * don't confuse these with PLy_elog
2344 static PyObject *PLy_output(int, PyObject *, PyObject *);
2347 PLy_debug(PyObject * self, PyObject * args)
2349 return PLy_output(DEBUG2, self, args);
2353 PLy_log(PyObject * self, PyObject * args)
2355 return PLy_output(LOG, self, args);
2359 PLy_info(PyObject * self, PyObject * args)
2361 return PLy_output(INFO, self, args);
2365 PLy_notice(PyObject * self, PyObject * args)
2367 return PLy_output(NOTICE, self, args);
2371 PLy_warning(PyObject * self, PyObject * args)
2373 return PLy_output(WARNING, self, args);
2377 PLy_error(PyObject * self, PyObject * args)
2379 return PLy_output(ERROR, self, args);
2383 PLy_fatal(PyObject * self, PyObject * args)
2385 return PLy_output(FATAL, self, args);
2390 PLy_output(volatile int level, PyObject * self, PyObject * args)
2394 MemoryContext oldcontext;
2396 so = PyObject_Str(args);
2397 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2400 sv = "Unable to parse error message in `plpy.elog'";
2403 oldcontext = CurrentMemoryContext;
2406 elog(level, "%s", sv);
2410 MemoryContextSwitchTo(oldcontext);
2411 PLy_error_in_progress = CopyErrorData();
2416 * returning NULL here causes the python interpreter to bail. when
2417 * control passes back to PLy_procedure_call, we check for PG
2418 * exceptions and re-throw the error.
2420 PyErr_SetString(PLy_exc_error, sv);
2428 * return a legal object so the interpreter will continue on its merry way
2436 * Get the last procedure name called by the backend ( the innermost,
2437 * If a plpython procedure call calls the backend and the backend calls
2438 * another plpython procedure )
2440 * NB: this returns the SQL name, not the internal Python procedure name
2444 PLy_procedure_name(PLyProcedure * proc)
2447 return "<unknown procedure>";
2448 return proc->proname;
2451 /* output a python traceback/exception via the postgresql elog
2452 * function. not pretty.
2455 PLy_exception_set(PyObject * exc, const char *fmt,...)
2461 vsnprintf(buf, sizeof(buf), fmt, ap);
2464 PyErr_SetString(exc, buf);
2467 /* Emit a PG error or notice, together with any available info about the
2468 * current Python error. This should be used to propagate Python errors
2472 PLy_elog(int elevel, const char *fmt,...)
2479 xmsg = PLy_traceback(&xlevel);
2482 emsg = PLy_vprintf(fmt, ap);
2488 (errmsg("plpython: %s", emsg),
2489 (xmsg) ? errdetail("%s", xmsg) : 0));
2506 PLy_traceback(int *xlevel)
2518 * get the current exception
2520 PyErr_Fetch(&e, &v, &tb);
2523 * oops, no exception, return
2531 PyErr_NormalizeException(&e, &v, &tb);
2533 eob = PyObject_Str(e);
2534 if (v && ((vob = PyObject_Str(v)) != NULL))
2535 vstr = PyString_AsString(vob);
2540 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
2541 * because that function calls us, so we could end up with infinite
2542 * recursion. I'm not even sure if eob could be NULL here -- would an
2543 * Assert() be more appropriate?
2545 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
2546 xstr = PLy_printf("%s: %s", estr, vstr);
2552 * intuit an appropriate error level for based on the exception type
2554 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
2556 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
2565 PLy_printf(const char *fmt,...)
2571 emsg = PLy_vprintf(fmt, ap);
2577 PLy_vprintf(const char *fmt, va_list ap)
2584 blen = strlen(fmt) * 2;
2587 buf = PLy_malloc(blen * sizeof(char));
2591 bchar = vsnprintf(buf, blen, fmt, ap);
2592 if (bchar > 0 && bchar < blen)
2600 buf = PLy_realloc(buf, blen);
2606 /* python module code
2610 /* some dumb utility functions
2614 PLy_malloc(size_t bytes)
2616 void *ptr = malloc(bytes);
2620 (errcode(ERRCODE_OUT_OF_MEMORY),
2621 errmsg("out of memory")));
2626 PLy_realloc(void *optr, size_t bytes)
2628 void *nptr = realloc(optr, bytes);
2632 (errcode(ERRCODE_OUT_OF_MEMORY),
2633 errmsg("out of memory")));
2638 PLy_strdup(const char *str)
2643 len = strlen(str) + 1;
2644 result = PLy_malloc(len);
2645 memcpy(result, str, len);