1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.106 2008/01/02 03:10:27 tgl Exp $
6 *********************************************************************
9 #if defined(_MSC_VER) && defined(_DEBUG)
10 /* Python uses #pragma to bring in a non-default libpython on VC++ if
11 * _DEBUG is defined */
13 /* Also hide away errcode, since we load Python.h before postgres.h */
14 #define errcode __msvc_errcode
18 #elif defined (_MSC_VER)
19 #define errcode __msvc_errcode
27 * Py_ssize_t compat for Python <= 2.4
29 #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
30 typedef int Py_ssize_t;
32 #define PY_SSIZE_T_MAX INT_MAX
33 #define PY_SSIZE_T_MIN INT_MIN
37 * PyBool_FromLong is supported from 2.3.
39 #if PY_VERSION_HEX < 0x02030000
40 #define PyBool_FromLong(x) PyInt_FromLong(x)
50 /* postgreSQL stuff */
51 #include "access/heapam.h"
52 #include "catalog/pg_proc.h"
53 #include "catalog/pg_type.h"
54 #include "commands/trigger.h"
55 #include "executor/spi.h"
58 #include "nodes/makefuncs.h"
59 #include "parser/parse_type.h"
60 #include "tcop/tcopprot.h"
61 #include "utils/builtins.h"
62 #include "utils/lsyscache.h"
63 #include "utils/memutils.h"
64 #include "utils/syscache.h"
65 #include "utils/typcache.h"
72 /* convert Postgresql Datum or tuple into a PyObject.
73 * input to Python. Tuples are converted to dictionary
77 typedef PyObject *(*PLyDatumToObFunc) (const char *);
79 typedef struct PLyDatumToOb
81 PLyDatumToObFunc func;
82 FmgrInfo typfunc; /* The type's output function */
83 Oid typoid; /* The OID of the type */
88 typedef struct PLyTupleToOb
94 typedef union PLyTypeInput
100 /* convert PyObject to a Postgresql Datum or tuple.
103 typedef struct PLyObToDatum
105 FmgrInfo typfunc; /* The type's input function */
106 Oid typoid; /* The OID of the type */
111 typedef struct PLyObToTuple
117 typedef union PLyTypeOutput
123 /* all we need to move Postgresql data to Python objects,
126 typedef struct PLyTypeInfo
133 * is_rowtype can be: -1 not known yet (initial state) 0 scalar datatype
134 * 1 rowtype 2 rowtype, but I/O functions not set up yet
139 /* cached procedure data */
140 typedef struct PLyProcedure
142 char *proname; /* SQL name of procedure */
143 char *pyname; /* Python name of procedure */
144 TransactionId fn_xmin;
145 ItemPointerData fn_tid;
147 PLyTypeInfo result; /* also used to store info for trigger tuple
149 bool is_setof; /* true, if procedure returns result set */
150 PyObject *setof; /* contents of result set. */
151 char **argnames; /* Argument names */
152 PLyTypeInfo args[FUNC_MAX_ARGS];
154 PyObject *code; /* compiled procedure code */
155 PyObject *statics; /* data saved across calls, local scope */
156 PyObject *globals; /* data saved across calls, global scope */
157 PyObject *me; /* PyCObject containing pointer to this
163 typedef struct PLyPlanObject
166 void *plan; /* return of an SPI_saveplan */
173 typedef struct PLyResultObject
176 /* HeapTuple *tuples; */
177 PyObject * nrows; /* number of rows returned by query */
178 PyObject *rows; /* data rows, or None if no data returned */
179 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
183 /* function declarations */
185 /* Two exported functions: first is the magic telling Postgresql
186 * what function call interface it implements. Second is for
187 * initialization of the interpreter during library load.
189 Datum plpython_call_handler(PG_FUNCTION_ARGS);
192 PG_FUNCTION_INFO_V1(plpython_call_handler);
194 /* most of the remaining of the declarations, all static */
196 /* these should only be called once at the first call
197 * of plpython_call_handler. initialize the python interpreter
200 static void PLy_init_interp(void);
201 static void PLy_init_plpy(void);
203 /* call PyErr_SetString with a vprint interface */
205 PLy_exception_set(PyObject *, const char *,...)
206 __attribute__((format(printf, 2, 3)));
208 /* Get the innermost python procedure called from the backend */
209 static char *PLy_procedure_name(PLyProcedure *);
211 /* some utility functions */
212 static void PLy_elog(int, const char *,...);
213 static char *PLy_traceback(int *);
215 static void *PLy_malloc(size_t);
216 static void *PLy_malloc0(size_t);
217 static char *PLy_strdup(const char *);
218 static void PLy_free(void *);
220 /* sub handlers for functions and triggers */
221 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
222 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
224 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
225 static void PLy_function_delete_args(PLyProcedure *);
226 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
228 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
229 TriggerData *, HeapTuple);
231 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
233 static PLyProcedure *PLy_procedure_get(FunctionCallInfo fcinfo,
236 static PLyProcedure *PLy_procedure_create(HeapTuple procTup, Oid tgreloid,
239 static void PLy_procedure_compile(PLyProcedure *, const char *);
240 static char *PLy_procedure_munge_source(const char *, const char *);
241 static void PLy_procedure_delete(PLyProcedure *);
243 static void PLy_typeinfo_init(PLyTypeInfo *);
244 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
245 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
246 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
247 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
248 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
249 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
250 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
252 /* conversion functions */
253 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
254 static PyObject *PLyBool_FromString(const char *);
255 static PyObject *PLyFloat_FromString(const char *);
256 static PyObject *PLyInt_FromString(const char *);
257 static PyObject *PLyLong_FromString(const char *);
258 static PyObject *PLyString_FromString(const char *);
260 static HeapTuple PLyMapping_ToTuple(PLyTypeInfo *, PyObject *);
261 static HeapTuple PLySequence_ToTuple(PLyTypeInfo *, PyObject *);
262 static HeapTuple PLyObject_ToTuple(PLyTypeInfo *, PyObject *);
265 * Currently active plpython function
267 static PLyProcedure *PLy_curr_procedure = NULL;
270 * When a callback from Python into PG incurs an error, we temporarily store
271 * the error information here, and return NULL to the Python interpreter.
272 * Any further callback attempts immediately fail, and when the Python
273 * interpreter returns to the calling function, we re-throw the error (even if
274 * Python thinks it trapped the error and doesn't return NULL). Eventually
275 * this ought to be improved to let Python code really truly trap the error,
276 * but that's more of a change from the pre-8.0 semantics than I have time for
277 * now --- it will only be possible if the callback query is executed inside a
280 static ErrorData *PLy_error_in_progress = NULL;
282 static PyObject *PLy_interp_globals = NULL;
283 static PyObject *PLy_interp_safe_globals = NULL;
284 static PyObject *PLy_procedure_cache = NULL;
286 /* Python exceptions */
287 static PyObject *PLy_exc_error = NULL;
288 static PyObject *PLy_exc_fatal = NULL;
289 static PyObject *PLy_exc_spi_error = NULL;
291 /* 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;
329 if (SPI_connect() != SPI_OK_CONNECT)
330 elog(ERROR, "could not connect to SPI manager");
332 save_curr_proc = PLy_curr_procedure;
336 if (CALLED_AS_TRIGGER(fcinfo))
338 TriggerData *tdata = (TriggerData *) fcinfo->context;
341 proc = PLy_procedure_get(fcinfo,
342 RelationGetRelid(tdata->tg_relation));
343 PLy_curr_procedure = proc;
344 trv = PLy_trigger_handler(fcinfo, proc);
345 retval = PointerGetDatum(trv);
349 proc = PLy_procedure_get(fcinfo, InvalidOid);
350 PLy_curr_procedure = proc;
351 retval = PLy_function_handler(fcinfo, proc);
356 PLy_curr_procedure = save_curr_proc;
359 /* note: Py_DECREF needs braces around it, as of 2003/08 */
367 PLy_curr_procedure = save_curr_proc;
374 /* trigger and function sub handlers
376 * the python function is expected to return Py_None if the tuple is
377 * acceptable and unmodified. Otherwise it should return a PyString
378 * object who's value is SKIP, or MODIFY. SKIP means don't perform
379 * this action. MODIFY means the tuple has been modified, so update
380 * tuple and perform action. SKIP and MODIFY assume the trigger fires
381 * BEFORE the event and is ROW level. postgres expects the function
382 * to take no arguments and return an argument of type trigger.
385 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
388 PyObject *volatile plargs = NULL;
389 PyObject *volatile plrv = NULL;
393 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
394 plrv = PLy_procedure_call(proc, "TD", plargs);
396 Assert(plrv != NULL);
397 Assert(!PLy_error_in_progress);
400 * Disconnect from SPI manager
402 if (SPI_finish() != SPI_OK_FINISH)
403 elog(ERROR, "SPI_finish failed");
406 * return of None means we're happy with the tuple
412 if (!PyString_Check(plrv))
414 (errcode(ERRCODE_DATA_EXCEPTION),
415 errmsg("unexpected return value from trigger procedure"),
416 errdetail("Expected None or a String.")));
418 srv = PyString_AsString(plrv);
419 if (pg_strcasecmp(srv, "SKIP") == 0)
421 else if (pg_strcasecmp(srv, "MODIFY") == 0)
423 TriggerData *tdata = (TriggerData *) fcinfo->context;
425 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
426 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
427 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
429 elog(WARNING, "ignoring modified tuple in DELETE trigger");
431 else if (pg_strcasecmp(srv, "OK") != 0)
434 * accept "OK" as an alternative to None; otherwise, raise an
438 (errcode(ERRCODE_DATA_EXCEPTION),
439 errmsg("unexpected return value from trigger procedure"),
440 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
460 PLy_modify_tuple(PLyProcedure * proc, PyObject * pltd, TriggerData *tdata,
463 PyObject *volatile plntup;
464 PyObject *volatile plkeys;
465 PyObject *volatile platt;
466 PyObject *volatile plval;
467 PyObject *volatile plstr;
473 int *volatile modattrs;
474 Datum *volatile modvalues;
475 char *volatile modnulls;
478 plntup = plkeys = platt = plval = plstr = NULL;
485 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
486 elog(ERROR, "TD[\"new\"] deleted, cannot modify tuple");
487 if (!PyDict_Check(plntup))
488 elog(ERROR, "TD[\"new\"] is not a dictionary object");
491 plkeys = PyDict_Keys(plntup);
492 natts = PyList_Size(plkeys);
494 modattrs = (int *) palloc(natts * sizeof(int));
495 modvalues = (Datum *) palloc(natts * sizeof(Datum));
496 modnulls = (char *) palloc(natts * sizeof(char));
498 tupdesc = tdata->tg_relation->rd_att;
500 for (i = 0; i < natts; i++)
504 platt = PyList_GetItem(plkeys, i);
505 if (!PyString_Check(platt))
506 elog(ERROR, "attribute name is not a string");
507 attn = SPI_fnumber(tupdesc, PyString_AsString(platt));
508 if (attn == SPI_ERROR_NOATTRIBUTE)
509 elog(ERROR, "invalid attribute \"%s\" in tuple",
510 PyString_AsString(platt));
513 plval = PyDict_GetItem(plntup, platt);
515 elog(FATAL, "python interpreter is probably corrupted");
521 if (tupdesc->attrs[atti]->attisdropped)
523 modvalues[i] = (Datum) 0;
526 else if (plval != Py_None)
528 plstr = PyObject_Str(plval);
530 PLy_elog(ERROR, "function \"%s\" could not modify tuple",
532 src = PyString_AsString(plstr);
535 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
537 proc->result.out.r.atts[atti].typioparam,
538 tupdesc->attrs[atti]->atttypmod);
547 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
549 proc->result.out.r.atts[atti].typioparam,
550 tupdesc->attrs[atti]->atttypmod);
558 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
559 modattrs, modvalues, modnulls);
561 elog(ERROR, "SPI_modifytuple failed -- error %d", SPI_result);
592 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc, HeapTuple *rv)
594 TriggerData *tdata = (TriggerData *) fcinfo->context;
605 PyObject *volatile pltdata = NULL;
610 pltdata = PyDict_New();
612 PLy_elog(ERROR, "could not build arguments for trigger procedure");
614 pltname = PyString_FromString(tdata->tg_trigger->tgname);
615 PyDict_SetItemString(pltdata, "name", pltname);
618 stroid = DatumGetCString(DirectFunctionCall1(oidout,
619 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
620 pltrelid = PyString_FromString(stroid);
621 PyDict_SetItemString(pltdata, "relid", pltrelid);
625 stroid = SPI_getrelname(tdata->tg_relation);
626 plttablename = PyString_FromString(stroid);
627 PyDict_SetItemString(pltdata, "table_name", plttablename);
628 Py_DECREF(plttablename);
631 stroid = SPI_getnspname(tdata->tg_relation);
632 plttableschema = PyString_FromString(stroid);
633 PyDict_SetItemString(pltdata, "table_schema", plttableschema);
634 Py_DECREF(plttableschema);
638 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
639 pltwhen = PyString_FromString("BEFORE");
640 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
641 pltwhen = PyString_FromString("AFTER");
644 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
645 pltwhen = NULL; /* keep compiler quiet */
647 PyDict_SetItemString(pltdata, "when", pltwhen);
650 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
652 pltlevel = PyString_FromString("ROW");
653 PyDict_SetItemString(pltdata, "level", pltlevel);
656 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
658 pltevent = PyString_FromString("INSERT");
660 PyDict_SetItemString(pltdata, "old", Py_None);
661 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
662 tdata->tg_relation->rd_att);
663 PyDict_SetItemString(pltdata, "new", pytnew);
665 *rv = tdata->tg_trigtuple;
667 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
669 pltevent = PyString_FromString("DELETE");
671 PyDict_SetItemString(pltdata, "new", Py_None);
672 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
673 tdata->tg_relation->rd_att);
674 PyDict_SetItemString(pltdata, "old", pytold);
676 *rv = tdata->tg_trigtuple;
678 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
680 pltevent = PyString_FromString("UPDATE");
682 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
683 tdata->tg_relation->rd_att);
684 PyDict_SetItemString(pltdata, "new", pytnew);
686 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
687 tdata->tg_relation->rd_att);
688 PyDict_SetItemString(pltdata, "old", pytold);
690 *rv = tdata->tg_newtuple;
694 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
695 pltevent = NULL; /* keep compiler quiet */
698 PyDict_SetItemString(pltdata, "event", pltevent);
701 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
703 pltlevel = PyString_FromString("STATEMENT");
704 PyDict_SetItemString(pltdata, "level", pltlevel);
707 PyDict_SetItemString(pltdata, "old", Py_None);
708 PyDict_SetItemString(pltdata, "new", Py_None);
711 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
712 pltevent = PyString_FromString("INSERT");
713 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
714 pltevent = PyString_FromString("DELETE");
715 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
716 pltevent = PyString_FromString("UPDATE");
719 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
720 pltevent = NULL; /* keep compiler quiet */
723 PyDict_SetItemString(pltdata, "event", pltevent);
727 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
729 if (tdata->tg_trigger->tgnargs)
737 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
738 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
740 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
743 * stolen, don't Py_DECREF
745 PyList_SetItem(pltargs, i, pltarg);
753 PyDict_SetItemString(pltdata, "args", pltargs);
768 /* function handler and friends */
770 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure * proc)
773 PyObject *volatile plargs = NULL;
774 PyObject *volatile plrv = NULL;
775 PyObject *volatile plrv_so = NULL;
780 if (!proc->is_setof || proc->setof == NULL)
782 /* Simple type returning function or first time for SETOF function */
783 plargs = PLy_function_build_args(fcinfo, proc);
784 plrv = PLy_procedure_call(proc, "args", plargs);
788 * SETOF function parameters will be deleted when last row is
791 PLy_function_delete_args(proc);
792 Assert(plrv != NULL);
793 Assert(!PLy_error_in_progress);
797 * Disconnect from SPI manager and then create the return values datum
798 * (if the input function does a palloc for it this must not be
799 * allocated in the SPI memory context because SPI_finish would free
802 if (SPI_finish() != SPI_OK_FINISH)
803 elog(ERROR, "SPI_finish failed");
807 bool has_error = false;
808 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
810 if (proc->setof == NULL)
812 /* first time -- do checks and setup */
813 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
814 (rsi->allowedModes & SFRM_ValuePerCall) == 0)
817 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
818 errmsg("only value per call is allowed")));
820 rsi->returnMode = SFRM_ValuePerCall;
822 /* Make iterator out of returned object */
823 proc->setof = PyObject_GetIter(plrv);
827 if (proc->setof == NULL)
829 (errcode(ERRCODE_DATATYPE_MISMATCH),
830 errmsg("returned object cannot be iterated"),
831 errdetail("SETOF must be returned as iterable object")));
834 /* Fetch next from iterator */
835 plrv = PyIter_Next(proc->setof);
837 rsi->isDone = ExprMultipleResult;
840 rsi->isDone = ExprEndResult;
841 has_error = PyErr_Occurred() != NULL;
844 if (rsi->isDone == ExprEndResult)
846 /* Iterator is exhausted or error happened */
847 Py_DECREF(proc->setof);
854 PLy_function_delete_args(proc);
858 (errcode(ERRCODE_DATA_EXCEPTION),
859 errmsg("error fetching next item from iterator")));
861 fcinfo->isnull = true;
867 * If the function is declared to return void, the Python return value
868 * must be None. For void-returning functions, we also treat a None
869 * return value as a special "void datum" rather than NULL (as is the
870 * case for non-void-returning functions).
872 if (proc->result.out.d.typoid == VOIDOID)
876 (errcode(ERRCODE_DATATYPE_MISMATCH),
877 errmsg("invalid return value from plpython function"),
878 errdetail("Functions returning type \"void\" must return None.")));
880 fcinfo->isnull = false;
883 else if (plrv == Py_None)
885 fcinfo->isnull = true;
886 if (proc->result.is_rowtype < 1)
887 rv = InputFunctionCall(&proc->result.out.d.typfunc,
889 proc->result.out.d.typioparam,
895 else if (proc->result.is_rowtype >= 1)
897 HeapTuple tuple = NULL;
899 if (PySequence_Check(plrv))
900 /* composite type as sequence (tuple, list etc) */
901 tuple = PLySequence_ToTuple(&proc->result, plrv);
902 else if (PyMapping_Check(plrv))
903 /* composite type as mapping (currently only dict) */
904 tuple = PLyMapping_ToTuple(&proc->result, plrv);
906 /* returned as smth, must provide method __getattr__(name) */
907 tuple = PLyObject_ToTuple(&proc->result, plrv);
911 fcinfo->isnull = false;
912 rv = HeapTupleGetDatum(tuple);
916 fcinfo->isnull = true;
922 fcinfo->isnull = false;
923 plrv_so = PyObject_Str(plrv);
925 PLy_elog(ERROR, "function \"%s\" could not create return value", proc->proname);
926 plrv_sc = PyString_AsString(plrv_so);
927 rv = InputFunctionCall(&proc->result.out.d.typfunc,
929 proc->result.out.d.typioparam,
951 PLy_procedure_call(PLyProcedure * proc, char *kargs, PyObject * vargs)
955 PyDict_SetItemString(proc->globals, kargs, vargs);
956 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
957 proc->globals, proc->globals);
960 * If there was an error in a PG callback, propagate that no matter what
961 * Python claims about its success.
963 if (PLy_error_in_progress)
965 ErrorData *edata = PLy_error_in_progress;
967 PLy_error_in_progress = NULL;
971 if (rv == NULL || PyErr_Occurred())
974 PLy_elog(ERROR, "function \"%s\" failed", proc->proname);
981 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure * proc)
983 PyObject *volatile arg = NULL;
984 PyObject *volatile args = NULL;
989 args = PyList_New(proc->nargs);
990 for (i = 0; i < proc->nargs; i++)
992 if (proc->args[i].is_rowtype > 0)
994 if (fcinfo->argnull[i])
1002 HeapTupleData tmptup;
1004 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
1005 /* Extract rowtype info and find a tupdesc */
1006 tupType = HeapTupleHeaderGetTypeId(td);
1007 tupTypmod = HeapTupleHeaderGetTypMod(td);
1008 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1010 /* Set up I/O funcs if not done yet */
1011 if (proc->args[i].is_rowtype != 1)
1012 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
1014 /* Build a temporary HeapTuple control structure */
1015 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1018 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
1019 ReleaseTupleDesc(tupdesc);
1024 if (fcinfo->argnull[i])
1030 ct = OutputFunctionCall(&(proc->args[i].in.d.typfunc),
1032 arg = (proc->args[i].in.d.func) (ct);
1043 if (PyList_SetItem(args, i, arg) == -1 ||
1045 PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1))
1046 PLy_elog(ERROR, "problem setting up arguments for \"%s\"", proc->proname);
1064 PLy_function_delete_args(PLyProcedure * proc)
1068 if (!proc->argnames)
1071 for (i = 0; i < proc->nargs; i++)
1072 PyDict_DelItemString(proc->globals, proc->argnames[i]);
1077 * PLyProcedure functions
1080 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
1081 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
1082 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
1085 static PLyProcedure *
1086 PLy_procedure_get(FunctionCallInfo fcinfo, Oid tgreloid)
1092 PLyProcedure *proc = NULL;
1095 fn_oid = fcinfo->flinfo->fn_oid;
1096 procTup = SearchSysCache(PROCOID,
1097 ObjectIdGetDatum(fn_oid),
1099 if (!HeapTupleIsValid(procTup))
1100 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1102 rv = snprintf(key, sizeof(key), "%u_%u", fn_oid, tgreloid);
1103 if (rv >= sizeof(key) || rv < 0)
1104 elog(ERROR, "key too long");
1106 plproc = PyDict_GetItemString(PLy_procedure_cache, key);
1111 if (!PyCObject_Check(plproc))
1112 elog(FATAL, "expected a PyCObject, didn't get one");
1114 proc = PyCObject_AsVoidPtr(plproc);
1115 if (proc->me != plproc)
1116 elog(FATAL, "proc->me != plproc");
1117 /* did we find an up-to-date cache entry? */
1118 if (proc->fn_xmin != HeapTupleHeaderGetXmin(procTup->t_data) ||
1119 !ItemPointerEquals(&proc->fn_tid, &procTup->t_self))
1127 proc = PLy_procedure_create(procTup, tgreloid, key);
1129 if (OidIsValid(tgreloid))
1132 * Input/output conversion for trigger tuples. Use the result
1133 * TypeInfo variable to store the tuple conversion info. We
1134 * do this over again on each call to cover the possibility that
1135 * the relation's tupdesc changed since the trigger was last called.
1136 * PLy_input_tuple_funcs and PLy_output_tuple_funcs are responsible
1137 * for not doing repetitive work.
1139 TriggerData *tdata = (TriggerData *) fcinfo->context;
1141 Assert(CALLED_AS_TRIGGER(fcinfo));
1142 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1143 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
1146 ReleaseSysCache(procTup);
1151 static PLyProcedure *
1152 PLy_procedure_create(HeapTuple procTup, Oid tgreloid, char *key)
1154 char procName[NAMEDATALEN + 256];
1155 Form_pg_proc procStruct;
1156 PLyProcedure *volatile proc;
1157 char *volatile procSource = NULL;
1166 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1168 if (OidIsValid(tgreloid))
1169 rv = snprintf(procName, sizeof(procName),
1170 "__plpython_procedure_%s_%u_trigger_%u",
1171 NameStr(procStruct->proname),
1172 HeapTupleGetOid(procTup),
1175 rv = snprintf(procName, sizeof(procName),
1176 "__plpython_procedure_%s_%u",
1177 NameStr(procStruct->proname),
1178 HeapTupleGetOid(procTup));
1179 if (rv >= sizeof(procName) || rv < 0)
1180 elog(ERROR, "procedure name would overrun buffer");
1182 proc = PLy_malloc(sizeof(PLyProcedure));
1183 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1184 proc->pyname = PLy_strdup(procName);
1185 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1186 proc->fn_tid = procTup->t_self;
1187 /* Remember if function is STABLE/IMMUTABLE */
1189 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1190 PLy_typeinfo_init(&proc->result);
1191 for (i = 0; i < FUNC_MAX_ARGS; i++)
1192 PLy_typeinfo_init(&proc->args[i]);
1194 proc->code = proc->statics = NULL;
1195 proc->globals = proc->me = NULL;
1196 proc->is_setof = procStruct->proretset;
1198 proc->argnames = NULL;
1203 * get information required for output conversion of the return value,
1204 * but only if this isn't a trigger.
1206 if (!OidIsValid(tgreloid))
1208 HeapTuple rvTypeTup;
1209 Form_pg_type rvTypeStruct;
1211 rvTypeTup = SearchSysCache(TYPEOID,
1212 ObjectIdGetDatum(procStruct->prorettype),
1214 if (!HeapTupleIsValid(rvTypeTup))
1215 elog(ERROR, "cache lookup failed for type %u",
1216 procStruct->prorettype);
1217 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1219 /* Disallow pseudotype result, except for void */
1220 if (rvTypeStruct->typtype == TYPTYPE_PSEUDO &&
1221 procStruct->prorettype != VOIDOID)
1223 if (procStruct->prorettype == TRIGGEROID)
1225 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1226 errmsg("trigger functions can only be called as triggers")));
1229 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1230 errmsg("plpython functions cannot return type %s",
1231 format_type_be(procStruct->prorettype))));
1234 if (rvTypeStruct->typtype == TYPTYPE_COMPOSITE)
1237 * Tuple: set up later, during first call to
1238 * PLy_function_handler
1240 proc->result.out.d.typoid = procStruct->prorettype;
1241 proc->result.is_rowtype = 2;
1244 PLy_output_datum_func(&proc->result, rvTypeTup);
1246 ReleaseSysCache(rvTypeTup);
1250 * now get information required for input conversion of the
1251 * procedure's arguments.
1253 proc->nargs = procStruct->pronargs;
1256 argnames = SysCacheGetAttr(PROCOID, procTup, Anum_pg_proc_proargnames, &isnull);
1259 /* XXX this code is WRONG if there are any output arguments */
1260 deconstruct_array(DatumGetArrayTypeP(argnames), TEXTOID, -1, false, 'i',
1261 &elems, NULL, &nelems);
1262 if (nelems != proc->nargs)
1264 "proargnames must have the same number of elements "
1265 "as the function has arguments");
1266 proc->argnames = (char **) PLy_malloc(sizeof(char *) * proc->nargs);
1267 memset(proc->argnames, 0, sizeof(char *) * proc->nargs);
1270 for (i = 0; i < proc->nargs; i++)
1272 HeapTuple argTypeTup;
1273 Form_pg_type argTypeStruct;
1275 argTypeTup = SearchSysCache(TYPEOID,
1276 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1278 if (!HeapTupleIsValid(argTypeTup))
1279 elog(ERROR, "cache lookup failed for type %u",
1280 procStruct->proargtypes.values[i]);
1281 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1283 /* Disallow pseudotype argument */
1284 if (argTypeStruct->typtype == TYPTYPE_PSEUDO)
1286 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1287 errmsg("plpython functions cannot take type %s",
1288 format_type_be(procStruct->proargtypes.values[i]))));
1290 if (argTypeStruct->typtype != TYPTYPE_COMPOSITE)
1291 PLy_input_datum_func(&(proc->args[i]),
1292 procStruct->proargtypes.values[i],
1295 proc->args[i].is_rowtype = 2; /* still need to set I/O funcs */
1297 ReleaseSysCache(argTypeTup);
1299 /* Fetch argument name */
1301 proc->argnames[i] = PLy_strdup(DatumGetCString(DirectFunctionCall1(textout, elems[i])));
1305 * get the text of the function.
1307 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1308 Anum_pg_proc_prosrc, &isnull);
1310 elog(ERROR, "null prosrc");
1311 procSource = DatumGetCString(DirectFunctionCall1(textout,
1314 PLy_procedure_compile(proc, procSource);
1318 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1319 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1323 PLy_procedure_delete(proc);
1335 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1337 PyObject *crv = NULL;
1340 proc->globals = PyDict_Copy(PLy_interp_globals);
1343 * SD is private preserved data between calls. GD is global data shared by
1346 proc->statics = PyDict_New();
1347 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1350 * insert the function code into the interpreter
1352 msrc = PLy_procedure_munge_source(proc->pyname, src);
1353 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1356 if (crv != NULL && (!PyErr_Occurred()))
1359 char call[NAMEDATALEN + 256];
1364 * compile a call to the function
1366 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1367 if (clen < 0 || clen >= sizeof(call))
1368 elog(ERROR, "string would overflow buffer");
1369 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1370 if (proc->code != NULL && (!PyErr_Occurred()))
1376 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1380 PLy_procedure_munge_source(const char *name, const char *src)
1389 * room for function source and the def statement
1391 mlen = (strlen(src) * 2) + strlen(name) + 16;
1393 mrc = PLy_malloc(mlen);
1394 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1395 Assert(plen >= 0 && plen < mlen);
1402 if (*sp == '\r' && *(sp + 1) == '\n')
1405 if (*sp == '\n' || *sp == '\r')
1418 if (mp > (mrc + mlen))
1419 elog(FATAL, "buffer overrun in PLy_munge_source");
1425 PLy_procedure_delete(PLyProcedure * proc)
1429 Py_XDECREF(proc->code);
1430 Py_XDECREF(proc->statics);
1431 Py_XDECREF(proc->globals);
1432 Py_XDECREF(proc->me);
1434 PLy_free(proc->proname);
1436 PLy_free(proc->pyname);
1437 for (i = 0; i < proc->nargs; i++)
1439 if (proc->args[i].is_rowtype == 1)
1441 if (proc->args[i].in.r.atts)
1442 PLy_free(proc->args[i].in.r.atts);
1443 if (proc->args[i].out.r.atts)
1444 PLy_free(proc->args[i].out.r.atts);
1446 if (proc->argnames && proc->argnames[i])
1447 PLy_free(proc->argnames[i]);
1450 PLy_free(proc->argnames);
1453 /* conversion functions. remember output from python is
1454 * input to postgresql, and vis versa.
1457 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1461 if (arg->is_rowtype == 0)
1462 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1463 arg->is_rowtype = 1;
1465 if (arg->in.r.natts != desc->natts)
1468 PLy_free(arg->in.r.atts);
1469 arg->in.r.natts = desc->natts;
1470 arg->in.r.atts = PLy_malloc0(desc->natts * sizeof(PLyDatumToOb));
1473 for (i = 0; i < desc->natts; i++)
1477 if (desc->attrs[i]->attisdropped)
1480 if (arg->in.r.atts[i].typoid == desc->attrs[i]->atttypid)
1481 continue; /* already set up this entry */
1483 typeTup = SearchSysCache(TYPEOID,
1484 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1486 if (!HeapTupleIsValid(typeTup))
1487 elog(ERROR, "cache lookup failed for type %u",
1488 desc->attrs[i]->atttypid);
1490 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1491 desc->attrs[i]->atttypid,
1494 ReleaseSysCache(typeTup);
1499 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1503 if (arg->is_rowtype == 0)
1504 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1505 arg->is_rowtype = 1;
1507 if (arg->out.r.natts != desc->natts)
1509 if (arg->out.r.atts)
1510 PLy_free(arg->out.r.atts);
1511 arg->out.r.natts = desc->natts;
1512 arg->out.r.atts = PLy_malloc0(desc->natts * sizeof(PLyDatumToOb));
1515 for (i = 0; i < desc->natts; i++)
1519 if (desc->attrs[i]->attisdropped)
1522 if (arg->out.r.atts[i].typoid == desc->attrs[i]->atttypid)
1523 continue; /* already set up this entry */
1525 typeTup = SearchSysCache(TYPEOID,
1526 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1528 if (!HeapTupleIsValid(typeTup))
1529 elog(ERROR, "cache lookup failed for type %u",
1530 desc->attrs[i]->atttypid);
1532 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1534 ReleaseSysCache(typeTup);
1539 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1541 if (arg->is_rowtype > 0)
1542 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1543 arg->is_rowtype = 0;
1544 PLy_output_datum_func2(&(arg->out.d), typeTup);
1548 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1550 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1552 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1553 arg->typoid = HeapTupleGetOid(typeTup);
1554 arg->typioparam = getTypeIOParam(typeTup);
1555 arg->typbyval = typeStruct->typbyval;
1559 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1561 if (arg->is_rowtype > 0)
1562 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1563 arg->is_rowtype = 0;
1564 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1568 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1570 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1572 /* Get the type's conversion information */
1573 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1574 arg->typoid = HeapTupleGetOid(typeTup);
1575 arg->typioparam = getTypeIOParam(typeTup);
1576 arg->typbyval = typeStruct->typbyval;
1578 /* Determine which kind of Python object we will convert to */
1582 arg->func = PLyBool_FromString;
1587 arg->func = PLyFloat_FromString;
1591 arg->func = PLyInt_FromString;
1594 arg->func = PLyLong_FromString;
1597 arg->func = PLyString_FromString;
1603 PLy_typeinfo_init(PLyTypeInfo * arg)
1605 arg->is_rowtype = -1;
1606 arg->in.r.natts = arg->out.r.natts = 0;
1607 arg->in.r.atts = NULL;
1608 arg->out.r.atts = NULL;
1612 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1614 if (arg->is_rowtype == 1)
1617 PLy_free(arg->in.r.atts);
1618 if (arg->out.r.atts)
1619 PLy_free(arg->out.r.atts);
1623 /* assumes that a bool is always returned as a 't' or 'f' */
1625 PLyBool_FromString(const char *src)
1628 * We would like to use Py_RETURN_TRUE and Py_RETURN_FALSE here for
1629 * generating SQL from trigger functions, but those are only supported in
1630 * Python >= 2.3, and we support older versions.
1631 * http://docs.python.org/api/boolObjects.html
1634 return PyBool_FromLong(1);
1635 return PyBool_FromLong(0);
1639 PLyFloat_FromString(const char *src)
1645 v = strtod(src, &eptr);
1646 if (*eptr != '\0' || errno)
1648 return PyFloat_FromDouble(v);
1652 PLyInt_FromString(const char *src)
1658 v = strtol(src, &eptr, 0);
1659 if (*eptr != '\0' || errno)
1661 return PyInt_FromLong(v);
1665 PLyLong_FromString(const char *src)
1667 return PyLong_FromString((char *) src, NULL, 0);
1671 PLyString_FromString(const char *src)
1673 return PyString_FromString(src);
1677 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1679 PyObject *volatile dict;
1682 if (info->is_rowtype != 1)
1683 elog(ERROR, "PLyTypeInfo structure describes a datum");
1685 dict = PyDict_New();
1687 PLy_elog(ERROR, "could not create tuple dictionary");
1691 for (i = 0; i < info->in.r.natts; i++)
1699 if (desc->attrs[i]->attisdropped)
1702 key = NameStr(desc->attrs[i]->attname);
1703 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1705 if (is_null || info->in.r.atts[i].func == NULL)
1706 PyDict_SetItemString(dict, key, Py_None);
1709 vsrc = OutputFunctionCall(&info->in.r.atts[i].typfunc,
1713 * no exceptions allowed
1715 value = info->in.r.atts[i].func(vsrc);
1717 PyDict_SetItemString(dict, key, value);
1734 PLyMapping_ToTuple(PLyTypeInfo * info, PyObject * mapping)
1742 Assert(PyMapping_Check(mapping));
1744 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1745 if (info->is_rowtype == 2)
1746 PLy_output_tuple_funcs(info, desc);
1747 Assert(info->is_rowtype == 1);
1750 values = palloc(sizeof(Datum) * desc->natts);
1751 nulls = palloc(sizeof(char) * desc->natts);
1752 for (i = 0; i < desc->natts; ++i)
1755 PyObject *volatile value,
1758 key = NameStr(desc->attrs[i]->attname);
1762 value = PyMapping_GetItemString(mapping, key);
1763 if (value == Py_None)
1765 values[i] = (Datum) NULL;
1772 so = PyObject_Str(value);
1774 PLy_elog(ERROR, "cannot convert mapping type");
1775 valuestr = PyString_AsString(so);
1777 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1779 ,info->out.r.atts[i].typioparam
1787 (errcode(ERRCODE_UNDEFINED_COLUMN),
1788 errmsg("no mapping found with key \"%s\"", key),
1789 errhint("to return null in specific column, "
1790 "add value None to map with key named after column")));
1804 tuple = heap_formtuple(desc, values, nulls);
1805 ReleaseTupleDesc(desc);
1814 PLySequence_ToTuple(PLyTypeInfo * info, PyObject * sequence)
1822 Assert(PySequence_Check(sequence));
1825 * Check that sequence length is exactly same as PG tuple's. We actually
1826 * can ignore exceeding items or assume missing ones as null but to avoid
1827 * plpython developer's errors we are strict here
1829 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1830 if (PySequence_Length(sequence) != desc->natts)
1832 (errcode(ERRCODE_DATATYPE_MISMATCH),
1833 errmsg("returned sequence's length must be same as tuple's length")));
1835 if (info->is_rowtype == 2)
1836 PLy_output_tuple_funcs(info, desc);
1837 Assert(info->is_rowtype == 1);
1840 values = palloc(sizeof(Datum) * desc->natts);
1841 nulls = palloc(sizeof(char) * desc->natts);
1842 for (i = 0; i < desc->natts; ++i)
1844 PyObject *volatile value,
1850 value = PySequence_GetItem(sequence, i);
1852 if (value == Py_None)
1854 values[i] = (Datum) NULL;
1861 so = PyObject_Str(value);
1863 PLy_elog(ERROR, "cannot convert sequence type");
1864 valuestr = PyString_AsString(so);
1865 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1867 ,info->out.r.atts[i].typioparam
1886 tuple = heap_formtuple(desc, values, nulls);
1887 ReleaseTupleDesc(desc);
1896 PLyObject_ToTuple(PLyTypeInfo * info, PyObject * object)
1904 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1905 if (info->is_rowtype == 2)
1906 PLy_output_tuple_funcs(info, desc);
1907 Assert(info->is_rowtype == 1);
1910 values = palloc(sizeof(Datum) * desc->natts);
1911 nulls = palloc(sizeof(char) * desc->natts);
1912 for (i = 0; i < desc->natts; ++i)
1915 PyObject *volatile value,
1918 key = NameStr(desc->attrs[i]->attname);
1922 value = PyObject_GetAttrString(object, key);
1923 if (value == Py_None)
1925 values[i] = (Datum) NULL;
1932 so = PyObject_Str(value);
1934 PLy_elog(ERROR, "cannot convert object type");
1935 valuestr = PyString_AsString(so);
1936 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1938 ,info->out.r.atts[i].typioparam
1946 (errcode(ERRCODE_UNDEFINED_COLUMN),
1947 errmsg("no attribute named \"%s\"", key),
1948 errhint("to return null in specific column, "
1949 "let returned object to have attribute named "
1950 "after column with value None")));
1964 tuple = heap_formtuple(desc, values, nulls);
1965 ReleaseTupleDesc(desc);
1973 /* initialization, some python variables function declared here */
1975 /* interface to postgresql elog */
1976 static PyObject *PLy_debug(PyObject *, PyObject *);
1977 static PyObject *PLy_log(PyObject *, PyObject *);
1978 static PyObject *PLy_info(PyObject *, PyObject *);
1979 static PyObject *PLy_notice(PyObject *, PyObject *);
1980 static PyObject *PLy_warning(PyObject *, PyObject *);
1981 static PyObject *PLy_error(PyObject *, PyObject *);
1982 static PyObject *PLy_fatal(PyObject *, PyObject *);
1984 /* PLyPlanObject, PLyResultObject and SPI interface */
1985 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1986 static PyObject *PLy_plan_new(void);
1987 static void PLy_plan_dealloc(PyObject *);
1988 static PyObject *PLy_plan_getattr(PyObject *, char *);
1989 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1991 static PyObject *PLy_result_new(void);
1992 static void PLy_result_dealloc(PyObject *);
1993 static PyObject *PLy_result_getattr(PyObject *, char *);
1994 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1995 static PyObject *PLy_result_status(PyObject *, PyObject *);
1996 static Py_ssize_t PLy_result_length(PyObject *);
1997 static PyObject *PLy_result_item(PyObject *, Py_ssize_t);
1998 static PyObject *PLy_result_slice(PyObject *, Py_ssize_t, Py_ssize_t);
1999 static int PLy_result_ass_item(PyObject *, Py_ssize_t, PyObject *);
2000 static int PLy_result_ass_slice(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
2003 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
2004 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
2005 static PyObject *PLy_spi_execute_query(char *query, long limit);
2006 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
2007 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
2010 static PyTypeObject PLy_PlanType = {
2011 PyObject_HEAD_INIT(NULL)
2013 "PLyPlan", /* tp_name */
2014 sizeof(PLyPlanObject), /* tp_size */
2015 0, /* tp_itemsize */
2020 PLy_plan_dealloc, /* tp_dealloc */
2022 PLy_plan_getattr, /* tp_getattr */
2026 0, /* tp_as_number */
2027 0, /* tp_as_sequence */
2028 0, /* tp_as_mapping */
2032 0, /* tp_getattro */
2033 0, /* tp_setattro */
2034 0, /* tp_as_buffer */
2035 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2036 PLy_plan_doc, /* tp_doc */
2039 static PyMethodDef PLy_plan_methods[] = {
2040 {"status", PLy_plan_status, METH_VARARGS, NULL},
2041 {NULL, NULL, 0, NULL}
2044 static PySequenceMethods PLy_result_as_sequence = {
2045 PLy_result_length, /* sq_length */
2046 NULL, /* sq_concat */
2047 NULL, /* sq_repeat */
2048 PLy_result_item, /* sq_item */
2049 PLy_result_slice, /* sq_slice */
2050 PLy_result_ass_item, /* sq_ass_item */
2051 PLy_result_ass_slice, /* sq_ass_slice */
2054 static PyTypeObject PLy_ResultType = {
2055 PyObject_HEAD_INIT(NULL)
2057 "PLyResult", /* tp_name */
2058 sizeof(PLyResultObject), /* tp_size */
2059 0, /* tp_itemsize */
2064 PLy_result_dealloc, /* tp_dealloc */
2066 PLy_result_getattr, /* tp_getattr */
2070 0, /* tp_as_number */
2071 &PLy_result_as_sequence, /* tp_as_sequence */
2072 0, /* tp_as_mapping */
2076 0, /* tp_getattro */
2077 0, /* tp_setattro */
2078 0, /* tp_as_buffer */
2079 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2080 PLy_result_doc, /* tp_doc */
2083 static PyMethodDef PLy_result_methods[] = {
2084 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
2085 {"status", PLy_result_status, METH_VARARGS, NULL},
2086 {NULL, NULL, 0, NULL}
2089 static PyMethodDef PLy_methods[] = {
2093 {"debug", PLy_debug, METH_VARARGS, NULL},
2094 {"log", PLy_log, METH_VARARGS, NULL},
2095 {"info", PLy_info, METH_VARARGS, NULL},
2096 {"notice", PLy_notice, METH_VARARGS, NULL},
2097 {"warning", PLy_warning, METH_VARARGS, NULL},
2098 {"error", PLy_error, METH_VARARGS, NULL},
2099 {"fatal", PLy_fatal, METH_VARARGS, NULL},
2102 * create a stored plan
2104 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
2107 * execute a plan or query
2109 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
2111 {NULL, NULL, 0, NULL}
2115 /* plan object methods */
2121 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
2129 return (PyObject *) ob;
2134 PLy_plan_dealloc(PyObject * arg)
2136 PLyPlanObject *ob = (PLyPlanObject *) arg;
2139 SPI_freeplan(ob->plan);
2141 PLy_free(ob->types);
2146 for (i = 0; i < ob->nargs; i++)
2147 PLy_typeinfo_dealloc(&ob->args[i]);
2151 arg->ob_type->tp_free(arg);
2156 PLy_plan_getattr(PyObject * self, char *name)
2158 return Py_FindMethod(PLy_plan_methods, self, name);
2162 PLy_plan_status(PyObject * self, PyObject * args)
2164 if (PyArg_ParseTuple(args, ""))
2168 /* return PyInt_FromLong(self->status); */
2170 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
2176 /* result object methods */
2179 PLy_result_new(void)
2181 PLyResultObject *ob;
2183 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
2186 /* ob->tuples = NULL; */
2189 ob->status = Py_None;
2190 ob->nrows = PyInt_FromLong(-1);
2191 ob->rows = PyList_New(0);
2193 return (PyObject *) ob;
2197 PLy_result_dealloc(PyObject * arg)
2199 PLyResultObject *ob = (PLyResultObject *) arg;
2201 Py_XDECREF(ob->nrows);
2202 Py_XDECREF(ob->rows);
2203 Py_XDECREF(ob->status);
2205 arg->ob_type->tp_free(arg);
2209 PLy_result_getattr(PyObject * self, char *name)
2211 return Py_FindMethod(PLy_result_methods, self, name);
2215 PLy_result_nrows(PyObject * self, PyObject * args)
2217 PLyResultObject *ob = (PLyResultObject *) self;
2219 Py_INCREF(ob->nrows);
2224 PLy_result_status(PyObject * self, PyObject * args)
2226 PLyResultObject *ob = (PLyResultObject *) self;
2228 Py_INCREF(ob->status);
2233 PLy_result_length(PyObject * arg)
2235 PLyResultObject *ob = (PLyResultObject *) arg;
2237 return PyList_Size(ob->rows);
2241 PLy_result_item(PyObject * arg, Py_ssize_t idx)
2244 PLyResultObject *ob = (PLyResultObject *) arg;
2246 rv = PyList_GetItem(ob->rows, idx);
2253 PLy_result_ass_item(PyObject * arg, Py_ssize_t idx, PyObject * item)
2256 PLyResultObject *ob = (PLyResultObject *) arg;
2259 rv = PyList_SetItem(ob->rows, idx, item);
2264 PLy_result_slice(PyObject * arg, Py_ssize_t lidx, Py_ssize_t hidx)
2267 PLyResultObject *ob = (PLyResultObject *) arg;
2269 rv = PyList_GetSlice(ob->rows, lidx, hidx);
2277 PLy_result_ass_slice(PyObject * arg, Py_ssize_t lidx, Py_ssize_t hidx, PyObject * slice)
2280 PLyResultObject *ob = (PLyResultObject *) arg;
2282 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
2288 PLy_spi_prepare(PyObject * self, PyObject * args)
2290 PLyPlanObject *plan;
2291 PyObject *list = NULL;
2292 PyObject *volatile optr = NULL;
2295 MemoryContext oldcontext;
2297 /* Can't execute more if we have an unhandled error */
2298 if (PLy_error_in_progress)
2300 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2304 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
2306 PyErr_SetString(PLy_exc_spi_error,
2307 "Invalid arguments for plpy.prepare()");
2311 if (list && (!PySequence_Check(list)))
2313 PyErr_SetString(PLy_exc_spi_error,
2314 "Second argument in plpy.prepare() must be a sequence");
2318 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
2321 oldcontext = CurrentMemoryContext;
2329 nargs = PySequence_Length(list);
2332 plan->nargs = nargs;
2333 plan->types = PLy_malloc(sizeof(Oid) * nargs);
2334 plan->values = PLy_malloc(sizeof(Datum) * nargs);
2335 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
2338 * the other loop might throw an exception, if PLyTypeInfo
2339 * member isn't properly initialized the Py_DECREF(plan) will
2342 for (i = 0; i < nargs; i++)
2344 PLy_typeinfo_init(&plan->args[i]);
2345 plan->values[i] = PointerGetDatum(NULL);
2348 for (i = 0; i < nargs; i++)
2354 Form_pg_type typeStruct;
2356 optr = PySequence_GetItem(list, i);
2357 if (!PyString_Check(optr))
2358 elog(ERROR, "Type names must be strings.");
2359 sptr = PyString_AsString(optr);
2361 /********************************************************
2362 * Resolve argument type names and then look them up by
2363 * oid in the system cache, and remember the required
2364 *information for input conversion.
2365 ********************************************************/
2367 parseTypeString(sptr, &typeId, &typmod);
2369 typeTup = SearchSysCache(TYPEOID,
2370 ObjectIdGetDatum(typeId),
2372 if (!HeapTupleIsValid(typeTup))
2373 elog(ERROR, "cache lookup failed for type %u", typeId);
2376 optr = NULL; /* this is important */
2378 plan->types[i] = typeId;
2379 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2380 if (typeStruct->typtype != TYPTYPE_COMPOSITE)
2381 PLy_output_datum_func(&plan->args[i], typeTup);
2383 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
2384 ReleaseSysCache(typeTup);
2389 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2390 if (plan->plan == NULL)
2391 elog(ERROR, "SPI_prepare failed: %s",
2392 SPI_result_code_string(SPI_result));
2394 /* transfer plan from procCxt to topCxt */
2395 tmpplan = plan->plan;
2396 plan->plan = SPI_saveplan(tmpplan);
2397 SPI_freeplan(tmpplan);
2398 if (plan->plan == NULL)
2399 elog(ERROR, "SPI_saveplan failed: %s",
2400 SPI_result_code_string(SPI_result));
2404 MemoryContextSwitchTo(oldcontext);
2405 PLy_error_in_progress = CopyErrorData();
2409 if (!PyErr_Occurred())
2410 PyErr_SetString(PLy_exc_spi_error,
2411 "Unknown error in PLy_spi_prepare");
2412 /* XXX this oughta be replaced with errcontext mechanism */
2413 PLy_elog(WARNING, "in function %s:",
2414 PLy_procedure_name(PLy_curr_procedure));
2419 return (PyObject *) plan;
2422 /* execute(query="select * from foo", limit=5)
2423 * execute(plan=plan, values=(foo, bar), limit=5)
2426 PLy_spi_execute(PyObject * self, PyObject * args)
2430 PyObject *list = NULL;
2433 /* Can't execute more if we have an unhandled error */
2434 if (PLy_error_in_progress)
2436 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2440 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
2441 return PLy_spi_execute_query(query, limit);
2445 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
2446 is_PLyPlanObject(plan))
2447 return PLy_spi_execute_plan(plan, list, limit);
2449 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2454 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
2459 PLyPlanObject *plan;
2460 MemoryContext oldcontext;
2464 if (!PySequence_Check(list) || PyString_Check(list))
2466 char *msg = "plpy.execute() takes a sequence as its second argument";
2468 PyErr_SetString(PLy_exc_spi_error, msg);
2471 nargs = PySequence_Length(list);
2476 plan = (PLyPlanObject *) ob;
2478 if (nargs != plan->nargs)
2481 PyObject *so = PyObject_Str(list);
2484 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2485 PLy_procedure_name(PLy_curr_procedure));
2486 sv = PyString_AsString(so);
2487 PLy_exception_set(PLy_exc_spi_error,
2488 "Expected sequence of %d arguments, got %d. %s",
2489 plan->nargs, nargs, sv);
2495 oldcontext = CurrentMemoryContext;
2498 char *nulls = palloc(nargs * sizeof(char));
2501 for (j = 0; j < nargs; j++)
2506 elem = PySequence_GetItem(list, j);
2507 if (elem != Py_None)
2509 so = PyObject_Str(elem);
2511 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2512 PLy_procedure_name(PLy_curr_procedure));
2517 char *sv = PyString_AsString(so);
2520 InputFunctionCall(&(plan->args[j].out.d.typfunc),
2522 plan->args[j].out.d.typioparam,
2539 InputFunctionCall(&(plan->args[j].out.d.typfunc),
2541 plan->args[j].out.d.typioparam,
2547 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2548 PLy_curr_procedure->fn_readonly, limit);
2556 MemoryContextSwitchTo(oldcontext);
2557 PLy_error_in_progress = CopyErrorData();
2561 * cleanup plan->values array
2563 for (k = 0; k < nargs; k++)
2565 if (!plan->args[k].out.d.typbyval &&
2566 (plan->values[k] != PointerGetDatum(NULL)))
2568 pfree(DatumGetPointer(plan->values[k]));
2569 plan->values[k] = PointerGetDatum(NULL);
2573 if (!PyErr_Occurred())
2574 PyErr_SetString(PLy_exc_error,
2575 "Unknown error in PLy_spi_execute_plan");
2576 /* XXX this oughta be replaced with errcontext mechanism */
2577 PLy_elog(WARNING, "in function %s:",
2578 PLy_procedure_name(PLy_curr_procedure));
2583 for (i = 0; i < nargs; i++)
2585 if (!plan->args[i].out.d.typbyval &&
2586 (plan->values[i] != PointerGetDatum(NULL)))
2588 pfree(DatumGetPointer(plan->values[i]));
2589 plan->values[i] = PointerGetDatum(NULL);
2595 PLy_exception_set(PLy_exc_spi_error,
2596 "SPI_execute_plan failed: %s",
2597 SPI_result_code_string(rv));
2601 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2605 PLy_spi_execute_query(char *query, long limit)
2608 MemoryContext oldcontext;
2610 oldcontext = CurrentMemoryContext;
2613 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2617 MemoryContextSwitchTo(oldcontext);
2618 PLy_error_in_progress = CopyErrorData();
2620 if (!PyErr_Occurred())
2621 PyErr_SetString(PLy_exc_spi_error,
2622 "Unknown error in PLy_spi_execute_query");
2623 /* XXX this oughta be replaced with errcontext mechanism */
2624 PLy_elog(WARNING, "in function %s:",
2625 PLy_procedure_name(PLy_curr_procedure));
2632 PLy_exception_set(PLy_exc_spi_error,
2633 "SPI_execute failed: %s",
2634 SPI_result_code_string(rv));
2638 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2642 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2644 PLyResultObject *result;
2645 MemoryContext oldcontext;
2647 result = (PLyResultObject *) PLy_result_new();
2648 Py_DECREF(result->status);
2649 result->status = PyInt_FromLong(status);
2651 if (status > 0 && tuptable == NULL)
2653 Py_DECREF(result->nrows);
2654 result->nrows = PyInt_FromLong(rows);
2656 else if (status > 0 && tuptable != NULL)
2661 Py_DECREF(result->nrows);
2662 result->nrows = PyInt_FromLong(rows);
2663 PLy_typeinfo_init(&args);
2665 oldcontext = CurrentMemoryContext;
2670 Py_DECREF(result->rows);
2671 result->rows = PyList_New(rows);
2673 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2674 for (i = 0; i < rows; i++)
2676 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2679 PyList_SetItem(result->rows, i, row);
2681 PLy_typeinfo_dealloc(&args);
2683 SPI_freetuptable(tuptable);
2688 MemoryContextSwitchTo(oldcontext);
2689 PLy_error_in_progress = CopyErrorData();
2691 if (!PyErr_Occurred())
2692 PyErr_SetString(PLy_exc_error,
2693 "Unknown error in PLy_spi_execute_fetch_result");
2695 PLy_typeinfo_dealloc(&args);
2701 return (PyObject *) result;
2706 * language handler and interpreter initialization
2710 * _PG_init() - library load-time initialization
2712 * DO NOT make this static nor change its name!
2717 /* Be sure we do initialization only once (should be redundant now) */
2718 static bool inited = false;
2726 if (PyErr_Occurred())
2727 PLy_elog(FATAL, "untrapped error in initialization");
2728 PLy_procedure_cache = PyDict_New();
2729 if (PLy_procedure_cache == NULL)
2730 PLy_elog(ERROR, "could not create procedure cache");
2736 PLy_init_interp(void)
2740 mainmod = PyImport_AddModule("__main__");
2741 if (mainmod == NULL || PyErr_Occurred())
2742 PLy_elog(ERROR, "could not import \"__main__\" module.");
2744 PLy_interp_globals = PyModule_GetDict(mainmod);
2745 PLy_interp_safe_globals = PyDict_New();
2746 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2748 if (PLy_interp_globals == NULL || PyErr_Occurred())
2749 PLy_elog(ERROR, "could not initialize globals");
2762 * initialize plpy module
2764 if (PyType_Ready(&PLy_PlanType) < 0)
2765 elog(ERROR, "could not init PLy_PlanType");
2766 if (PyType_Ready(&PLy_ResultType) < 0)
2767 elog(ERROR, "could not init PLy_ResultType");
2769 plpy = Py_InitModule("plpy", PLy_methods);
2770 plpy_dict = PyModule_GetDict(plpy);
2772 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2774 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2775 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2776 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2777 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2778 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2779 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2782 * initialize main module, and add plpy
2784 main_mod = PyImport_AddModule("__main__");
2785 main_dict = PyModule_GetDict(main_mod);
2786 plpy_mod = PyImport_AddModule("plpy");
2787 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2788 if (PyErr_Occurred())
2789 elog(ERROR, "could not init plpy");
2792 /* the python interface to the elog function
2793 * don't confuse these with PLy_elog
2795 static PyObject *PLy_output(volatile int, PyObject *, PyObject *);
2798 PLy_debug(PyObject * self, PyObject * args)
2800 return PLy_output(DEBUG2, self, args);
2804 PLy_log(PyObject * self, PyObject * args)
2806 return PLy_output(LOG, self, args);
2810 PLy_info(PyObject * self, PyObject * args)
2812 return PLy_output(INFO, self, args);
2816 PLy_notice(PyObject * self, PyObject * args)
2818 return PLy_output(NOTICE, self, args);
2822 PLy_warning(PyObject * self, PyObject * args)
2824 return PLy_output(WARNING, self, args);
2828 PLy_error(PyObject * self, PyObject * args)
2830 return PLy_output(ERROR, self, args);
2834 PLy_fatal(PyObject * self, PyObject * args)
2836 return PLy_output(FATAL, self, args);
2841 PLy_output(volatile int level, PyObject * self, PyObject * args)
2845 MemoryContext oldcontext;
2847 so = PyObject_Str(args);
2848 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2851 sv = "could not parse error message in `plpy.elog'";
2854 oldcontext = CurrentMemoryContext;
2857 elog(level, "%s", sv);
2861 MemoryContextSwitchTo(oldcontext);
2862 PLy_error_in_progress = CopyErrorData();
2867 * returning NULL here causes the python interpreter to bail. when
2868 * control passes back to PLy_procedure_call, we check for PG
2869 * exceptions and re-throw the error.
2871 PyErr_SetString(PLy_exc_error, sv);
2879 * return a legal object so the interpreter will continue on its merry way
2887 * Get the name of the last procedure called by the backend (the
2888 * innermost, if a plpython procedure call calls the backend and the
2889 * backend calls another plpython procedure).
2891 * NB: this returns the SQL name, not the internal Python procedure name
2894 PLy_procedure_name(PLyProcedure * proc)
2897 return "<unknown procedure>";
2898 return proc->proname;
2901 /* output a python traceback/exception via the postgresql elog
2902 * function. not pretty.
2905 PLy_exception_set(PyObject * exc, const char *fmt,...)
2911 vsnprintf(buf, sizeof(buf), fmt, ap);
2914 PyErr_SetString(exc, buf);
2917 /* Emit a PG error or notice, together with any available info about the
2918 * current Python error. This should be used to propagate Python errors
2922 PLy_elog(int elevel, const char *fmt,...)
2926 StringInfoData emsg;
2928 xmsg = PLy_traceback(&xlevel);
2930 initStringInfo(&emsg);
2937 success = appendStringInfoVA(&emsg, fmt, ap);
2941 enlargeStringInfo(&emsg, emsg.maxlen);
2947 (errmsg("plpython: %s", emsg.data),
2948 (xmsg) ? errdetail("%s", xmsg) : 0));
2965 PLy_traceback(int *xlevel)
2974 StringInfoData xstr;
2977 * get the current exception
2979 PyErr_Fetch(&e, &v, &tb);
2982 * oops, no exception, return
2990 PyErr_NormalizeException(&e, &v, &tb);
2993 eob = PyObject_Str(e);
2994 if (v && ((vob = PyObject_Str(v)) != NULL))
2995 vstr = PyString_AsString(vob);
3000 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
3001 * because that function calls us, so we could end up with infinite
3002 * recursion. I'm not even sure if eob could be NULL here -- would an
3003 * Assert() be more appropriate?
3005 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
3006 initStringInfo(&xstr);
3007 appendStringInfo(&xstr, "%s: %s", estr, vstr);
3014 * intuit an appropriate error level based on the exception type
3016 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
3018 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
3027 /* python module code */
3029 /* some dumb utility functions */
3031 PLy_malloc(size_t bytes)
3033 void *ptr = malloc(bytes);
3037 (errcode(ERRCODE_OUT_OF_MEMORY),
3038 errmsg("out of memory")));
3043 PLy_malloc0(size_t bytes)
3045 void *ptr = PLy_malloc(bytes);
3047 MemSet(ptr, 0, bytes);
3052 PLy_strdup(const char *str)
3057 len = strlen(str) + 1;
3058 result = PLy_malloc(len);
3059 memcpy(result, str, len);
3064 /* define this away */