1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * $PostgreSQL: pgsql/src/pl/plpython/plpython.c,v 1.107 2008/03/25 22:42:45 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(TextDatumGetCString(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 = TextDatumGetCString(prosrcdatum);
1313 PLy_procedure_compile(proc, procSource);
1317 proc->me = PyCObject_FromVoidPtr(proc, NULL);
1318 PyDict_SetItemString(PLy_procedure_cache, key, proc->me);
1322 PLy_procedure_delete(proc);
1334 PLy_procedure_compile(PLyProcedure * proc, const char *src)
1336 PyObject *crv = NULL;
1339 proc->globals = PyDict_Copy(PLy_interp_globals);
1342 * SD is private preserved data between calls. GD is global data shared by
1345 proc->statics = PyDict_New();
1346 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1349 * insert the function code into the interpreter
1351 msrc = PLy_procedure_munge_source(proc->pyname, src);
1352 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1355 if (crv != NULL && (!PyErr_Occurred()))
1358 char call[NAMEDATALEN + 256];
1363 * compile a call to the function
1365 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1366 if (clen < 0 || clen >= sizeof(call))
1367 elog(ERROR, "string would overflow buffer");
1368 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1369 if (proc->code != NULL && (!PyErr_Occurred()))
1375 PLy_elog(ERROR, "could not compile function \"%s\"", proc->proname);
1379 PLy_procedure_munge_source(const char *name, const char *src)
1388 * room for function source and the def statement
1390 mlen = (strlen(src) * 2) + strlen(name) + 16;
1392 mrc = PLy_malloc(mlen);
1393 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1394 Assert(plen >= 0 && plen < mlen);
1401 if (*sp == '\r' && *(sp + 1) == '\n')
1404 if (*sp == '\n' || *sp == '\r')
1417 if (mp > (mrc + mlen))
1418 elog(FATAL, "buffer overrun in PLy_munge_source");
1424 PLy_procedure_delete(PLyProcedure * proc)
1428 Py_XDECREF(proc->code);
1429 Py_XDECREF(proc->statics);
1430 Py_XDECREF(proc->globals);
1431 Py_XDECREF(proc->me);
1433 PLy_free(proc->proname);
1435 PLy_free(proc->pyname);
1436 for (i = 0; i < proc->nargs; i++)
1438 if (proc->args[i].is_rowtype == 1)
1440 if (proc->args[i].in.r.atts)
1441 PLy_free(proc->args[i].in.r.atts);
1442 if (proc->args[i].out.r.atts)
1443 PLy_free(proc->args[i].out.r.atts);
1445 if (proc->argnames && proc->argnames[i])
1446 PLy_free(proc->argnames[i]);
1449 PLy_free(proc->argnames);
1452 /* conversion functions. remember output from python is
1453 * input to postgresql, and vis versa.
1456 PLy_input_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1460 if (arg->is_rowtype == 0)
1461 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1462 arg->is_rowtype = 1;
1464 if (arg->in.r.natts != desc->natts)
1467 PLy_free(arg->in.r.atts);
1468 arg->in.r.natts = desc->natts;
1469 arg->in.r.atts = PLy_malloc0(desc->natts * sizeof(PLyDatumToOb));
1472 for (i = 0; i < desc->natts; i++)
1476 if (desc->attrs[i]->attisdropped)
1479 if (arg->in.r.atts[i].typoid == desc->attrs[i]->atttypid)
1480 continue; /* already set up this entry */
1482 typeTup = SearchSysCache(TYPEOID,
1483 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1485 if (!HeapTupleIsValid(typeTup))
1486 elog(ERROR, "cache lookup failed for type %u",
1487 desc->attrs[i]->atttypid);
1489 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1490 desc->attrs[i]->atttypid,
1493 ReleaseSysCache(typeTup);
1498 PLy_output_tuple_funcs(PLyTypeInfo * arg, TupleDesc desc)
1502 if (arg->is_rowtype == 0)
1503 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1504 arg->is_rowtype = 1;
1506 if (arg->out.r.natts != desc->natts)
1508 if (arg->out.r.atts)
1509 PLy_free(arg->out.r.atts);
1510 arg->out.r.natts = desc->natts;
1511 arg->out.r.atts = PLy_malloc0(desc->natts * sizeof(PLyDatumToOb));
1514 for (i = 0; i < desc->natts; i++)
1518 if (desc->attrs[i]->attisdropped)
1521 if (arg->out.r.atts[i].typoid == desc->attrs[i]->atttypid)
1522 continue; /* already set up this entry */
1524 typeTup = SearchSysCache(TYPEOID,
1525 ObjectIdGetDatum(desc->attrs[i]->atttypid),
1527 if (!HeapTupleIsValid(typeTup))
1528 elog(ERROR, "cache lookup failed for type %u",
1529 desc->attrs[i]->atttypid);
1531 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1533 ReleaseSysCache(typeTup);
1538 PLy_output_datum_func(PLyTypeInfo * arg, HeapTuple typeTup)
1540 if (arg->is_rowtype > 0)
1541 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1542 arg->is_rowtype = 0;
1543 PLy_output_datum_func2(&(arg->out.d), typeTup);
1547 PLy_output_datum_func2(PLyObToDatum * arg, HeapTuple typeTup)
1549 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1551 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1552 arg->typoid = HeapTupleGetOid(typeTup);
1553 arg->typioparam = getTypeIOParam(typeTup);
1554 arg->typbyval = typeStruct->typbyval;
1558 PLy_input_datum_func(PLyTypeInfo * arg, Oid typeOid, HeapTuple typeTup)
1560 if (arg->is_rowtype > 0)
1561 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1562 arg->is_rowtype = 0;
1563 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1567 PLy_input_datum_func2(PLyDatumToOb * arg, Oid typeOid, HeapTuple typeTup)
1569 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1571 /* Get the type's conversion information */
1572 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1573 arg->typoid = HeapTupleGetOid(typeTup);
1574 arg->typioparam = getTypeIOParam(typeTup);
1575 arg->typbyval = typeStruct->typbyval;
1577 /* Determine which kind of Python object we will convert to */
1581 arg->func = PLyBool_FromString;
1586 arg->func = PLyFloat_FromString;
1590 arg->func = PLyInt_FromString;
1593 arg->func = PLyLong_FromString;
1596 arg->func = PLyString_FromString;
1602 PLy_typeinfo_init(PLyTypeInfo * arg)
1604 arg->is_rowtype = -1;
1605 arg->in.r.natts = arg->out.r.natts = 0;
1606 arg->in.r.atts = NULL;
1607 arg->out.r.atts = NULL;
1611 PLy_typeinfo_dealloc(PLyTypeInfo * arg)
1613 if (arg->is_rowtype == 1)
1616 PLy_free(arg->in.r.atts);
1617 if (arg->out.r.atts)
1618 PLy_free(arg->out.r.atts);
1622 /* assumes that a bool is always returned as a 't' or 'f' */
1624 PLyBool_FromString(const char *src)
1627 * We would like to use Py_RETURN_TRUE and Py_RETURN_FALSE here for
1628 * generating SQL from trigger functions, but those are only supported in
1629 * Python >= 2.3, and we support older versions.
1630 * http://docs.python.org/api/boolObjects.html
1633 return PyBool_FromLong(1);
1634 return PyBool_FromLong(0);
1638 PLyFloat_FromString(const char *src)
1644 v = strtod(src, &eptr);
1645 if (*eptr != '\0' || errno)
1647 return PyFloat_FromDouble(v);
1651 PLyInt_FromString(const char *src)
1657 v = strtol(src, &eptr, 0);
1658 if (*eptr != '\0' || errno)
1660 return PyInt_FromLong(v);
1664 PLyLong_FromString(const char *src)
1666 return PyLong_FromString((char *) src, NULL, 0);
1670 PLyString_FromString(const char *src)
1672 return PyString_FromString(src);
1676 PLyDict_FromTuple(PLyTypeInfo * info, HeapTuple tuple, TupleDesc desc)
1678 PyObject *volatile dict;
1681 if (info->is_rowtype != 1)
1682 elog(ERROR, "PLyTypeInfo structure describes a datum");
1684 dict = PyDict_New();
1686 PLy_elog(ERROR, "could not create tuple dictionary");
1690 for (i = 0; i < info->in.r.natts; i++)
1698 if (desc->attrs[i]->attisdropped)
1701 key = NameStr(desc->attrs[i]->attname);
1702 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
1704 if (is_null || info->in.r.atts[i].func == NULL)
1705 PyDict_SetItemString(dict, key, Py_None);
1708 vsrc = OutputFunctionCall(&info->in.r.atts[i].typfunc,
1712 * no exceptions allowed
1714 value = info->in.r.atts[i].func(vsrc);
1716 PyDict_SetItemString(dict, key, value);
1733 PLyMapping_ToTuple(PLyTypeInfo * info, PyObject * mapping)
1741 Assert(PyMapping_Check(mapping));
1743 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1744 if (info->is_rowtype == 2)
1745 PLy_output_tuple_funcs(info, desc);
1746 Assert(info->is_rowtype == 1);
1749 values = palloc(sizeof(Datum) * desc->natts);
1750 nulls = palloc(sizeof(char) * desc->natts);
1751 for (i = 0; i < desc->natts; ++i)
1754 PyObject *volatile value,
1757 key = NameStr(desc->attrs[i]->attname);
1761 value = PyMapping_GetItemString(mapping, key);
1762 if (value == Py_None)
1764 values[i] = (Datum) NULL;
1771 so = PyObject_Str(value);
1773 PLy_elog(ERROR, "cannot convert mapping type");
1774 valuestr = PyString_AsString(so);
1776 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1778 ,info->out.r.atts[i].typioparam
1786 (errcode(ERRCODE_UNDEFINED_COLUMN),
1787 errmsg("no mapping found with key \"%s\"", key),
1788 errhint("to return null in specific column, "
1789 "add value None to map with key named after column")));
1803 tuple = heap_formtuple(desc, values, nulls);
1804 ReleaseTupleDesc(desc);
1813 PLySequence_ToTuple(PLyTypeInfo * info, PyObject * sequence)
1821 Assert(PySequence_Check(sequence));
1824 * Check that sequence length is exactly same as PG tuple's. We actually
1825 * can ignore exceeding items or assume missing ones as null but to avoid
1826 * plpython developer's errors we are strict here
1828 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1829 if (PySequence_Length(sequence) != desc->natts)
1831 (errcode(ERRCODE_DATATYPE_MISMATCH),
1832 errmsg("returned sequence's length must be same as tuple's length")));
1834 if (info->is_rowtype == 2)
1835 PLy_output_tuple_funcs(info, desc);
1836 Assert(info->is_rowtype == 1);
1839 values = palloc(sizeof(Datum) * desc->natts);
1840 nulls = palloc(sizeof(char) * desc->natts);
1841 for (i = 0; i < desc->natts; ++i)
1843 PyObject *volatile value,
1849 value = PySequence_GetItem(sequence, i);
1851 if (value == Py_None)
1853 values[i] = (Datum) NULL;
1860 so = PyObject_Str(value);
1862 PLy_elog(ERROR, "cannot convert sequence type");
1863 valuestr = PyString_AsString(so);
1864 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1866 ,info->out.r.atts[i].typioparam
1885 tuple = heap_formtuple(desc, values, nulls);
1886 ReleaseTupleDesc(desc);
1895 PLyObject_ToTuple(PLyTypeInfo * info, PyObject * object)
1903 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
1904 if (info->is_rowtype == 2)
1905 PLy_output_tuple_funcs(info, desc);
1906 Assert(info->is_rowtype == 1);
1909 values = palloc(sizeof(Datum) * desc->natts);
1910 nulls = palloc(sizeof(char) * desc->natts);
1911 for (i = 0; i < desc->natts; ++i)
1914 PyObject *volatile value,
1917 key = NameStr(desc->attrs[i]->attname);
1921 value = PyObject_GetAttrString(object, key);
1922 if (value == Py_None)
1924 values[i] = (Datum) NULL;
1931 so = PyObject_Str(value);
1933 PLy_elog(ERROR, "cannot convert object type");
1934 valuestr = PyString_AsString(so);
1935 values[i] = InputFunctionCall(&info->out.r.atts[i].typfunc
1937 ,info->out.r.atts[i].typioparam
1945 (errcode(ERRCODE_UNDEFINED_COLUMN),
1946 errmsg("no attribute named \"%s\"", key),
1947 errhint("to return null in specific column, "
1948 "let returned object to have attribute named "
1949 "after column with value None")));
1963 tuple = heap_formtuple(desc, values, nulls);
1964 ReleaseTupleDesc(desc);
1972 /* initialization, some python variables function declared here */
1974 /* interface to postgresql elog */
1975 static PyObject *PLy_debug(PyObject *, PyObject *);
1976 static PyObject *PLy_log(PyObject *, PyObject *);
1977 static PyObject *PLy_info(PyObject *, PyObject *);
1978 static PyObject *PLy_notice(PyObject *, PyObject *);
1979 static PyObject *PLy_warning(PyObject *, PyObject *);
1980 static PyObject *PLy_error(PyObject *, PyObject *);
1981 static PyObject *PLy_fatal(PyObject *, PyObject *);
1983 /* PLyPlanObject, PLyResultObject and SPI interface */
1984 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
1985 static PyObject *PLy_plan_new(void);
1986 static void PLy_plan_dealloc(PyObject *);
1987 static PyObject *PLy_plan_getattr(PyObject *, char *);
1988 static PyObject *PLy_plan_status(PyObject *, PyObject *);
1990 static PyObject *PLy_result_new(void);
1991 static void PLy_result_dealloc(PyObject *);
1992 static PyObject *PLy_result_getattr(PyObject *, char *);
1993 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
1994 static PyObject *PLy_result_status(PyObject *, PyObject *);
1995 static Py_ssize_t PLy_result_length(PyObject *);
1996 static PyObject *PLy_result_item(PyObject *, Py_ssize_t);
1997 static PyObject *PLy_result_slice(PyObject *, Py_ssize_t, Py_ssize_t);
1998 static int PLy_result_ass_item(PyObject *, Py_ssize_t, PyObject *);
1999 static int PLy_result_ass_slice(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
2002 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
2003 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
2004 static PyObject *PLy_spi_execute_query(char *query, long limit);
2005 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
2006 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
2009 static PyTypeObject PLy_PlanType = {
2010 PyObject_HEAD_INIT(NULL)
2012 "PLyPlan", /* tp_name */
2013 sizeof(PLyPlanObject), /* tp_size */
2014 0, /* tp_itemsize */
2019 PLy_plan_dealloc, /* tp_dealloc */
2021 PLy_plan_getattr, /* tp_getattr */
2025 0, /* tp_as_number */
2026 0, /* tp_as_sequence */
2027 0, /* tp_as_mapping */
2031 0, /* tp_getattro */
2032 0, /* tp_setattro */
2033 0, /* tp_as_buffer */
2034 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2035 PLy_plan_doc, /* tp_doc */
2038 static PyMethodDef PLy_plan_methods[] = {
2039 {"status", PLy_plan_status, METH_VARARGS, NULL},
2040 {NULL, NULL, 0, NULL}
2043 static PySequenceMethods PLy_result_as_sequence = {
2044 PLy_result_length, /* sq_length */
2045 NULL, /* sq_concat */
2046 NULL, /* sq_repeat */
2047 PLy_result_item, /* sq_item */
2048 PLy_result_slice, /* sq_slice */
2049 PLy_result_ass_item, /* sq_ass_item */
2050 PLy_result_ass_slice, /* sq_ass_slice */
2053 static PyTypeObject PLy_ResultType = {
2054 PyObject_HEAD_INIT(NULL)
2056 "PLyResult", /* tp_name */
2057 sizeof(PLyResultObject), /* tp_size */
2058 0, /* tp_itemsize */
2063 PLy_result_dealloc, /* tp_dealloc */
2065 PLy_result_getattr, /* tp_getattr */
2069 0, /* tp_as_number */
2070 &PLy_result_as_sequence, /* tp_as_sequence */
2071 0, /* tp_as_mapping */
2075 0, /* tp_getattro */
2076 0, /* tp_setattro */
2077 0, /* tp_as_buffer */
2078 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2079 PLy_result_doc, /* tp_doc */
2082 static PyMethodDef PLy_result_methods[] = {
2083 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
2084 {"status", PLy_result_status, METH_VARARGS, NULL},
2085 {NULL, NULL, 0, NULL}
2088 static PyMethodDef PLy_methods[] = {
2092 {"debug", PLy_debug, METH_VARARGS, NULL},
2093 {"log", PLy_log, METH_VARARGS, NULL},
2094 {"info", PLy_info, METH_VARARGS, NULL},
2095 {"notice", PLy_notice, METH_VARARGS, NULL},
2096 {"warning", PLy_warning, METH_VARARGS, NULL},
2097 {"error", PLy_error, METH_VARARGS, NULL},
2098 {"fatal", PLy_fatal, METH_VARARGS, NULL},
2101 * create a stored plan
2103 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
2106 * execute a plan or query
2108 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
2110 {NULL, NULL, 0, NULL}
2114 /* plan object methods */
2120 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
2128 return (PyObject *) ob;
2133 PLy_plan_dealloc(PyObject * arg)
2135 PLyPlanObject *ob = (PLyPlanObject *) arg;
2138 SPI_freeplan(ob->plan);
2140 PLy_free(ob->types);
2145 for (i = 0; i < ob->nargs; i++)
2146 PLy_typeinfo_dealloc(&ob->args[i]);
2150 arg->ob_type->tp_free(arg);
2155 PLy_plan_getattr(PyObject * self, char *name)
2157 return Py_FindMethod(PLy_plan_methods, self, name);
2161 PLy_plan_status(PyObject * self, PyObject * args)
2163 if (PyArg_ParseTuple(args, ""))
2167 /* return PyInt_FromLong(self->status); */
2169 PyErr_SetString(PLy_exc_error, "plan.status() takes no arguments");
2175 /* result object methods */
2178 PLy_result_new(void)
2180 PLyResultObject *ob;
2182 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
2185 /* ob->tuples = NULL; */
2188 ob->status = Py_None;
2189 ob->nrows = PyInt_FromLong(-1);
2190 ob->rows = PyList_New(0);
2192 return (PyObject *) ob;
2196 PLy_result_dealloc(PyObject * arg)
2198 PLyResultObject *ob = (PLyResultObject *) arg;
2200 Py_XDECREF(ob->nrows);
2201 Py_XDECREF(ob->rows);
2202 Py_XDECREF(ob->status);
2204 arg->ob_type->tp_free(arg);
2208 PLy_result_getattr(PyObject * self, char *name)
2210 return Py_FindMethod(PLy_result_methods, self, name);
2214 PLy_result_nrows(PyObject * self, PyObject * args)
2216 PLyResultObject *ob = (PLyResultObject *) self;
2218 Py_INCREF(ob->nrows);
2223 PLy_result_status(PyObject * self, PyObject * args)
2225 PLyResultObject *ob = (PLyResultObject *) self;
2227 Py_INCREF(ob->status);
2232 PLy_result_length(PyObject * arg)
2234 PLyResultObject *ob = (PLyResultObject *) arg;
2236 return PyList_Size(ob->rows);
2240 PLy_result_item(PyObject * arg, Py_ssize_t idx)
2243 PLyResultObject *ob = (PLyResultObject *) arg;
2245 rv = PyList_GetItem(ob->rows, idx);
2252 PLy_result_ass_item(PyObject * arg, Py_ssize_t idx, PyObject * item)
2255 PLyResultObject *ob = (PLyResultObject *) arg;
2258 rv = PyList_SetItem(ob->rows, idx, item);
2263 PLy_result_slice(PyObject * arg, Py_ssize_t lidx, Py_ssize_t hidx)
2266 PLyResultObject *ob = (PLyResultObject *) arg;
2268 rv = PyList_GetSlice(ob->rows, lidx, hidx);
2276 PLy_result_ass_slice(PyObject * arg, Py_ssize_t lidx, Py_ssize_t hidx, PyObject * slice)
2279 PLyResultObject *ob = (PLyResultObject *) arg;
2281 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
2287 PLy_spi_prepare(PyObject * self, PyObject * args)
2289 PLyPlanObject *plan;
2290 PyObject *list = NULL;
2291 PyObject *volatile optr = NULL;
2294 MemoryContext oldcontext;
2296 /* Can't execute more if we have an unhandled error */
2297 if (PLy_error_in_progress)
2299 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2303 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
2305 PyErr_SetString(PLy_exc_spi_error,
2306 "Invalid arguments for plpy.prepare()");
2310 if (list && (!PySequence_Check(list)))
2312 PyErr_SetString(PLy_exc_spi_error,
2313 "Second argument in plpy.prepare() must be a sequence");
2317 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
2320 oldcontext = CurrentMemoryContext;
2328 nargs = PySequence_Length(list);
2331 plan->nargs = nargs;
2332 plan->types = PLy_malloc(sizeof(Oid) * nargs);
2333 plan->values = PLy_malloc(sizeof(Datum) * nargs);
2334 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
2337 * the other loop might throw an exception, if PLyTypeInfo
2338 * member isn't properly initialized the Py_DECREF(plan) will
2341 for (i = 0; i < nargs; i++)
2343 PLy_typeinfo_init(&plan->args[i]);
2344 plan->values[i] = PointerGetDatum(NULL);
2347 for (i = 0; i < nargs; i++)
2353 Form_pg_type typeStruct;
2355 optr = PySequence_GetItem(list, i);
2356 if (!PyString_Check(optr))
2357 elog(ERROR, "Type names must be strings.");
2358 sptr = PyString_AsString(optr);
2360 /********************************************************
2361 * Resolve argument type names and then look them up by
2362 * oid in the system cache, and remember the required
2363 *information for input conversion.
2364 ********************************************************/
2366 parseTypeString(sptr, &typeId, &typmod);
2368 typeTup = SearchSysCache(TYPEOID,
2369 ObjectIdGetDatum(typeId),
2371 if (!HeapTupleIsValid(typeTup))
2372 elog(ERROR, "cache lookup failed for type %u", typeId);
2375 optr = NULL; /* this is important */
2377 plan->types[i] = typeId;
2378 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2379 if (typeStruct->typtype != TYPTYPE_COMPOSITE)
2380 PLy_output_datum_func(&plan->args[i], typeTup);
2382 elog(ERROR, "tuples not handled in plpy.prepare, yet.");
2383 ReleaseSysCache(typeTup);
2388 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2389 if (plan->plan == NULL)
2390 elog(ERROR, "SPI_prepare failed: %s",
2391 SPI_result_code_string(SPI_result));
2393 /* transfer plan from procCxt to topCxt */
2394 tmpplan = plan->plan;
2395 plan->plan = SPI_saveplan(tmpplan);
2396 SPI_freeplan(tmpplan);
2397 if (plan->plan == NULL)
2398 elog(ERROR, "SPI_saveplan failed: %s",
2399 SPI_result_code_string(SPI_result));
2403 MemoryContextSwitchTo(oldcontext);
2404 PLy_error_in_progress = CopyErrorData();
2408 if (!PyErr_Occurred())
2409 PyErr_SetString(PLy_exc_spi_error,
2410 "Unknown error in PLy_spi_prepare");
2411 /* XXX this oughta be replaced with errcontext mechanism */
2412 PLy_elog(WARNING, "in function %s:",
2413 PLy_procedure_name(PLy_curr_procedure));
2418 return (PyObject *) plan;
2421 /* execute(query="select * from foo", limit=5)
2422 * execute(plan=plan, values=(foo, bar), limit=5)
2425 PLy_spi_execute(PyObject * self, PyObject * args)
2429 PyObject *list = NULL;
2432 /* Can't execute more if we have an unhandled error */
2433 if (PLy_error_in_progress)
2435 PyErr_SetString(PLy_exc_error, "Transaction aborted.");
2439 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
2440 return PLy_spi_execute_query(query, limit);
2444 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
2445 is_PLyPlanObject(plan))
2446 return PLy_spi_execute_plan(plan, list, limit);
2448 PyErr_SetString(PLy_exc_error, "Expected a query or plan.");
2453 PLy_spi_execute_plan(PyObject * ob, PyObject * list, long limit)
2458 PLyPlanObject *plan;
2459 MemoryContext oldcontext;
2463 if (!PySequence_Check(list) || PyString_Check(list))
2465 char *msg = "plpy.execute() takes a sequence as its second argument";
2467 PyErr_SetString(PLy_exc_spi_error, msg);
2470 nargs = PySequence_Length(list);
2475 plan = (PLyPlanObject *) ob;
2477 if (nargs != plan->nargs)
2480 PyObject *so = PyObject_Str(list);
2483 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2484 PLy_procedure_name(PLy_curr_procedure));
2485 sv = PyString_AsString(so);
2486 PLy_exception_set(PLy_exc_spi_error,
2487 "Expected sequence of %d arguments, got %d. %s",
2488 plan->nargs, nargs, sv);
2494 oldcontext = CurrentMemoryContext;
2497 char *nulls = palloc(nargs * sizeof(char));
2500 for (j = 0; j < nargs; j++)
2505 elem = PySequence_GetItem(list, j);
2506 if (elem != Py_None)
2508 so = PyObject_Str(elem);
2510 PLy_elog(ERROR, "function \"%s\" could not execute plan",
2511 PLy_procedure_name(PLy_curr_procedure));
2516 char *sv = PyString_AsString(so);
2519 InputFunctionCall(&(plan->args[j].out.d.typfunc),
2521 plan->args[j].out.d.typioparam,
2538 InputFunctionCall(&(plan->args[j].out.d.typfunc),
2540 plan->args[j].out.d.typioparam,
2546 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
2547 PLy_curr_procedure->fn_readonly, limit);
2555 MemoryContextSwitchTo(oldcontext);
2556 PLy_error_in_progress = CopyErrorData();
2560 * cleanup plan->values array
2562 for (k = 0; k < nargs; k++)
2564 if (!plan->args[k].out.d.typbyval &&
2565 (plan->values[k] != PointerGetDatum(NULL)))
2567 pfree(DatumGetPointer(plan->values[k]));
2568 plan->values[k] = PointerGetDatum(NULL);
2572 if (!PyErr_Occurred())
2573 PyErr_SetString(PLy_exc_error,
2574 "Unknown error in PLy_spi_execute_plan");
2575 /* XXX this oughta be replaced with errcontext mechanism */
2576 PLy_elog(WARNING, "in function %s:",
2577 PLy_procedure_name(PLy_curr_procedure));
2582 for (i = 0; i < nargs; i++)
2584 if (!plan->args[i].out.d.typbyval &&
2585 (plan->values[i] != PointerGetDatum(NULL)))
2587 pfree(DatumGetPointer(plan->values[i]));
2588 plan->values[i] = PointerGetDatum(NULL);
2594 PLy_exception_set(PLy_exc_spi_error,
2595 "SPI_execute_plan failed: %s",
2596 SPI_result_code_string(rv));
2600 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2604 PLy_spi_execute_query(char *query, long limit)
2607 MemoryContext oldcontext;
2609 oldcontext = CurrentMemoryContext;
2612 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
2616 MemoryContextSwitchTo(oldcontext);
2617 PLy_error_in_progress = CopyErrorData();
2619 if (!PyErr_Occurred())
2620 PyErr_SetString(PLy_exc_spi_error,
2621 "Unknown error in PLy_spi_execute_query");
2622 /* XXX this oughta be replaced with errcontext mechanism */
2623 PLy_elog(WARNING, "in function %s:",
2624 PLy_procedure_name(PLy_curr_procedure));
2631 PLy_exception_set(PLy_exc_spi_error,
2632 "SPI_execute failed: %s",
2633 SPI_result_code_string(rv));
2637 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
2641 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
2643 PLyResultObject *result;
2644 MemoryContext oldcontext;
2646 result = (PLyResultObject *) PLy_result_new();
2647 Py_DECREF(result->status);
2648 result->status = PyInt_FromLong(status);
2650 if (status > 0 && tuptable == NULL)
2652 Py_DECREF(result->nrows);
2653 result->nrows = PyInt_FromLong(rows);
2655 else if (status > 0 && tuptable != NULL)
2660 Py_DECREF(result->nrows);
2661 result->nrows = PyInt_FromLong(rows);
2662 PLy_typeinfo_init(&args);
2664 oldcontext = CurrentMemoryContext;
2669 Py_DECREF(result->rows);
2670 result->rows = PyList_New(rows);
2672 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
2673 for (i = 0; i < rows; i++)
2675 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
2678 PyList_SetItem(result->rows, i, row);
2680 PLy_typeinfo_dealloc(&args);
2682 SPI_freetuptable(tuptable);
2687 MemoryContextSwitchTo(oldcontext);
2688 PLy_error_in_progress = CopyErrorData();
2690 if (!PyErr_Occurred())
2691 PyErr_SetString(PLy_exc_error,
2692 "Unknown error in PLy_spi_execute_fetch_result");
2694 PLy_typeinfo_dealloc(&args);
2700 return (PyObject *) result;
2705 * language handler and interpreter initialization
2709 * _PG_init() - library load-time initialization
2711 * DO NOT make this static nor change its name!
2716 /* Be sure we do initialization only once (should be redundant now) */
2717 static bool inited = false;
2725 if (PyErr_Occurred())
2726 PLy_elog(FATAL, "untrapped error in initialization");
2727 PLy_procedure_cache = PyDict_New();
2728 if (PLy_procedure_cache == NULL)
2729 PLy_elog(ERROR, "could not create procedure cache");
2735 PLy_init_interp(void)
2739 mainmod = PyImport_AddModule("__main__");
2740 if (mainmod == NULL || PyErr_Occurred())
2741 PLy_elog(ERROR, "could not import \"__main__\" module.");
2743 PLy_interp_globals = PyModule_GetDict(mainmod);
2744 PLy_interp_safe_globals = PyDict_New();
2745 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
2747 if (PLy_interp_globals == NULL || PyErr_Occurred())
2748 PLy_elog(ERROR, "could not initialize globals");
2761 * initialize plpy module
2763 if (PyType_Ready(&PLy_PlanType) < 0)
2764 elog(ERROR, "could not init PLy_PlanType");
2765 if (PyType_Ready(&PLy_ResultType) < 0)
2766 elog(ERROR, "could not init PLy_ResultType");
2768 plpy = Py_InitModule("plpy", PLy_methods);
2769 plpy_dict = PyModule_GetDict(plpy);
2771 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
2773 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
2774 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
2775 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
2776 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
2777 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
2778 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
2781 * initialize main module, and add plpy
2783 main_mod = PyImport_AddModule("__main__");
2784 main_dict = PyModule_GetDict(main_mod);
2785 plpy_mod = PyImport_AddModule("plpy");
2786 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
2787 if (PyErr_Occurred())
2788 elog(ERROR, "could not init plpy");
2791 /* the python interface to the elog function
2792 * don't confuse these with PLy_elog
2794 static PyObject *PLy_output(volatile int, PyObject *, PyObject *);
2797 PLy_debug(PyObject * self, PyObject * args)
2799 return PLy_output(DEBUG2, self, args);
2803 PLy_log(PyObject * self, PyObject * args)
2805 return PLy_output(LOG, self, args);
2809 PLy_info(PyObject * self, PyObject * args)
2811 return PLy_output(INFO, self, args);
2815 PLy_notice(PyObject * self, PyObject * args)
2817 return PLy_output(NOTICE, self, args);
2821 PLy_warning(PyObject * self, PyObject * args)
2823 return PLy_output(WARNING, self, args);
2827 PLy_error(PyObject * self, PyObject * args)
2829 return PLy_output(ERROR, self, args);
2833 PLy_fatal(PyObject * self, PyObject * args)
2835 return PLy_output(FATAL, self, args);
2840 PLy_output(volatile int level, PyObject * self, PyObject * args)
2844 MemoryContext oldcontext;
2846 so = PyObject_Str(args);
2847 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
2850 sv = "could not parse error message in `plpy.elog'";
2853 oldcontext = CurrentMemoryContext;
2856 elog(level, "%s", sv);
2860 MemoryContextSwitchTo(oldcontext);
2861 PLy_error_in_progress = CopyErrorData();
2866 * returning NULL here causes the python interpreter to bail. when
2867 * control passes back to PLy_procedure_call, we check for PG
2868 * exceptions and re-throw the error.
2870 PyErr_SetString(PLy_exc_error, sv);
2878 * return a legal object so the interpreter will continue on its merry way
2886 * Get the name of the last procedure called by the backend (the
2887 * innermost, if a plpython procedure call calls the backend and the
2888 * backend calls another plpython procedure).
2890 * NB: this returns the SQL name, not the internal Python procedure name
2893 PLy_procedure_name(PLyProcedure * proc)
2896 return "<unknown procedure>";
2897 return proc->proname;
2900 /* output a python traceback/exception via the postgresql elog
2901 * function. not pretty.
2904 PLy_exception_set(PyObject * exc, const char *fmt,...)
2910 vsnprintf(buf, sizeof(buf), fmt, ap);
2913 PyErr_SetString(exc, buf);
2916 /* Emit a PG error or notice, together with any available info about the
2917 * current Python error. This should be used to propagate Python errors
2921 PLy_elog(int elevel, const char *fmt,...)
2925 StringInfoData emsg;
2927 xmsg = PLy_traceback(&xlevel);
2929 initStringInfo(&emsg);
2936 success = appendStringInfoVA(&emsg, fmt, ap);
2940 enlargeStringInfo(&emsg, emsg.maxlen);
2946 (errmsg("plpython: %s", emsg.data),
2947 (xmsg) ? errdetail("%s", xmsg) : 0));
2964 PLy_traceback(int *xlevel)
2973 StringInfoData xstr;
2976 * get the current exception
2978 PyErr_Fetch(&e, &v, &tb);
2981 * oops, no exception, return
2989 PyErr_NormalizeException(&e, &v, &tb);
2992 eob = PyObject_Str(e);
2993 if (v && ((vob = PyObject_Str(v)) != NULL))
2994 vstr = PyString_AsString(vob);
2999 * I'm not sure what to do if eob is NULL here -- we can't call PLy_elog
3000 * because that function calls us, so we could end up with infinite
3001 * recursion. I'm not even sure if eob could be NULL here -- would an
3002 * Assert() be more appropriate?
3004 estr = eob ? PyString_AsString(eob) : "Unknown Exception";
3005 initStringInfo(&xstr);
3006 appendStringInfo(&xstr, "%s: %s", estr, vstr);
3013 * intuit an appropriate error level based on the exception type
3015 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
3017 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
3026 /* python module code */
3028 /* some dumb utility functions */
3030 PLy_malloc(size_t bytes)
3032 void *ptr = malloc(bytes);
3036 (errcode(ERRCODE_OUT_OF_MEMORY),
3037 errmsg("out of memory")));
3042 PLy_malloc0(size_t bytes)
3044 void *ptr = PLy_malloc(bytes);
3046 MemSet(ptr, 0, bytes);
3051 PLy_strdup(const char *str)
3056 len = strlen(str) + 1;
3057 result = PLy_malloc(len);
3058 memcpy(result, str, len);
3063 /* define this away */