1 /**********************************************************************
2 * plpython.c - python as a procedural language for PostgreSQL
4 * src/pl/plpython/plpython.c
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)
44 * Python 2/3 strings/unicode/bytes handling. Python 2 has strings
45 * and unicode, Python 3 has strings, which are unicode on the C
46 * level, and bytes. The porting convention, which is similarly used
47 * in Python 2.6, is that "Unicode" is always unicode, and "Bytes" are
48 * bytes in Python 3 and strings in Python 2. Since we keep
49 * supporting Python 2 and its usual strings, we provide a
50 * compatibility layer for Python 3 that when asked to convert a C
51 * string to a Python string it converts the C string from the
52 * PostgreSQL server encoding to a Python Unicode object.
55 #if PY_VERSION_HEX < 0x02060000
56 /* This is exactly the compatibility layer that Python 2.6 uses. */
57 #define PyBytes_AsString PyString_AsString
58 #define PyBytes_FromStringAndSize PyString_FromStringAndSize
59 #define PyBytes_Size PyString_Size
60 #define PyObject_Bytes PyObject_Str
63 #if PY_MAJOR_VERSION >= 3
64 #define PyString_Check(x) 0
65 #define PyString_AsString(x) PLyUnicode_AsString(x)
66 #define PyString_FromString(x) PLyUnicode_FromString(x)
70 * Python 3 only has long.
72 #if PY_MAJOR_VERSION >= 3
73 #define PyInt_FromLong(x) PyLong_FromLong(x)
77 * PyVarObject_HEAD_INIT was added in Python 2.6. Its use is
78 * necessary to handle both Python 2 and 3. This replacement
79 * definition is for Python <=2.5
81 #ifndef PyVarObject_HEAD_INIT
82 #define PyVarObject_HEAD_INIT(type, size) \
83 PyObject_HEAD_INIT(type) size,
92 /* postgreSQL stuff */
93 #include "catalog/pg_proc.h"
94 #include "catalog/pg_type.h"
95 #include "commands/trigger.h"
96 #include "executor/spi.h"
99 #include "mb/pg_wchar.h"
100 #include "miscadmin.h"
101 #include "nodes/makefuncs.h"
102 #include "parser/parse_type.h"
103 #include "tcop/tcopprot.h"
104 #include "utils/builtins.h"
105 #include "utils/hsearch.h"
106 #include "utils/lsyscache.h"
107 #include "utils/memutils.h"
108 #include "utils/syscache.h"
109 #include "utils/typcache.h"
111 /* define our text domain for translations */
113 #define TEXTDOMAIN PG_TEXTDOMAIN("plpython")
120 /* convert Postgresql Datum or tuple into a PyObject.
121 * input to Python. Tuples are converted to dictionary
126 typedef PyObject *(*PLyDatumToObFunc) (struct PLyDatumToOb *, Datum);
128 typedef struct PLyDatumToOb
130 PLyDatumToObFunc func;
131 FmgrInfo typfunc; /* The type's output function */
132 Oid typoid; /* The OID of the type */
137 struct PLyDatumToOb *elm;
140 typedef struct PLyTupleToOb
146 typedef union PLyTypeInput
152 /* convert PyObject to a Postgresql Datum or tuple.
157 typedef Datum (*PLyObToDatumFunc) (struct PLyObToDatum *, int32 typmod,
160 typedef struct PLyObToDatum
162 PLyObToDatumFunc func;
163 FmgrInfo typfunc; /* The type's input function */
164 Oid typoid; /* The OID of the type */
169 struct PLyObToDatum *elm;
172 typedef struct PLyObToTuple
178 typedef union PLyTypeOutput
184 /* all we need to move Postgresql data to Python objects,
187 typedef struct PLyTypeInfo
193 * is_rowtype can be: -1 = not known yet (initial state); 0 = scalar
194 * datatype; 1 = rowtype; 2 = rowtype, but I/O functions not set up yet
200 /* cached procedure data */
201 typedef struct PLyProcedure
203 char *proname; /* SQL name of procedure */
204 char *pyname; /* Python name of procedure */
205 TransactionId fn_xmin;
206 ItemPointerData fn_tid;
208 PLyTypeInfo result; /* also used to store info for trigger tuple
210 bool is_setof; /* true, if procedure returns result set */
211 PyObject *setof; /* contents of result set. */
212 char **argnames; /* Argument names */
213 PLyTypeInfo args[FUNC_MAX_ARGS];
215 PyObject *code; /* compiled procedure code */
216 PyObject *statics; /* data saved across calls, local scope */
217 PyObject *globals; /* data saved across calls, global scope */
221 /* the procedure cache entry */
222 typedef struct PLyProcedureEntry
224 Oid fn_oid; /* hash key */
230 typedef struct PLyPlanObject
233 void *plan; /* return of an SPI_saveplan */
240 typedef struct PLyResultObject
243 /* HeapTuple *tuples; */
244 PyObject *nrows; /* number of rows returned by query */
245 PyObject *rows; /* data rows, or None if no data returned */
246 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
250 /* function declarations */
252 #if PY_MAJOR_VERSION >= 3
253 /* Use separate names to avoid clash in pg_pltemplate */
254 #define plpython_call_handler plpython3_call_handler
255 #define plpython_inline_handler plpython3_inline_handler
258 /* exported functions */
259 Datum plpython_call_handler(PG_FUNCTION_ARGS);
260 Datum plpython_inline_handler(PG_FUNCTION_ARGS);
263 PG_FUNCTION_INFO_V1(plpython_call_handler);
264 PG_FUNCTION_INFO_V1(plpython_inline_handler);
266 /* most of the remaining of the declarations, all static */
268 /* these should only be called once at the first call
269 * of plpython_call_handler. initialize the python interpreter
272 static void PLy_init_interp(void);
273 static void PLy_init_plpy(void);
275 /* call PyErr_SetString with a vprint interface and translation support */
277 PLy_exception_set(PyObject *, const char *,...)
278 __attribute__((format(printf, 2, 3)));
280 /* same, with pluralized message */
282 PLy_exception_set_plural(PyObject *, const char *, const char *,
284 __attribute__((format(printf, 2, 5)))
285 __attribute__((format(printf, 3, 5)));
287 /* Get the innermost python procedure called from the backend */
288 static char *PLy_procedure_name(PLyProcedure *);
290 /* some utility functions */
292 PLy_elog(int, const char *,...)
293 __attribute__((format(printf, 2, 3)));
294 static char *PLy_traceback(int *);
296 static void *PLy_malloc(size_t);
297 static void *PLy_malloc0(size_t);
298 static char *PLy_strdup(const char *);
299 static void PLy_free(void *);
301 static PyObject *PLyUnicode_Bytes(PyObject *unicode);
302 static char *PLyUnicode_AsString(PyObject *unicode);
304 #if PY_MAJOR_VERSION >= 3
305 static PyObject *PLyUnicode_FromString(const char *s);
308 /* sub handlers for functions and triggers */
309 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
310 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
312 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
313 static void PLy_function_delete_args(PLyProcedure *);
314 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
316 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
317 TriggerData *, HeapTuple);
319 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
321 static PLyProcedure *PLy_procedure_get(Oid fn_oid, bool is_trigger);
323 static PLyProcedure *PLy_procedure_create(HeapTuple procTup,
324 Oid fn_oid, bool is_trigger);
326 static void PLy_procedure_compile(PLyProcedure *, const char *);
327 static char *PLy_procedure_munge_source(const char *, const char *);
328 static void PLy_procedure_delete(PLyProcedure *);
330 static void PLy_typeinfo_init(PLyTypeInfo *);
331 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
332 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
333 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
334 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
335 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
336 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
337 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
339 /* conversion functions */
340 static PyObject *PLyBool_FromBool(PLyDatumToOb *arg, Datum d);
341 static PyObject *PLyFloat_FromFloat4(PLyDatumToOb *arg, Datum d);
342 static PyObject *PLyFloat_FromFloat8(PLyDatumToOb *arg, Datum d);
343 static PyObject *PLyFloat_FromNumeric(PLyDatumToOb *arg, Datum d);
344 static PyObject *PLyInt_FromInt16(PLyDatumToOb *arg, Datum d);
345 static PyObject *PLyInt_FromInt32(PLyDatumToOb *arg, Datum d);
346 static PyObject *PLyLong_FromInt64(PLyDatumToOb *arg, Datum d);
347 static PyObject *PLyBytes_FromBytea(PLyDatumToOb *arg, Datum d);
348 static PyObject *PLyString_FromDatum(PLyDatumToOb *arg, Datum d);
349 static PyObject *PLyList_FromArray(PLyDatumToOb *arg, Datum d);
351 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
353 static Datum PLyObject_ToBool(PLyObToDatum *, int32, PyObject *);
354 static Datum PLyObject_ToBytea(PLyObToDatum *, int32, PyObject *);
355 static Datum PLyObject_ToDatum(PLyObToDatum *, int32, PyObject *);
356 static Datum PLySequence_ToArray(PLyObToDatum *, int32, PyObject *);
358 static HeapTuple PLyMapping_ToTuple(PLyTypeInfo *, PyObject *);
359 static HeapTuple PLySequence_ToTuple(PLyTypeInfo *, PyObject *);
360 static HeapTuple PLyObject_ToTuple(PLyTypeInfo *, PyObject *);
363 * Currently active plpython function
365 static PLyProcedure *PLy_curr_procedure = NULL;
368 * When a callback from Python into PG incurs an error, we temporarily store
369 * the error information here, and return NULL to the Python interpreter.
370 * Any further callback attempts immediately fail, and when the Python
371 * interpreter returns to the calling function, we re-throw the error (even if
372 * Python thinks it trapped the error and doesn't return NULL). Eventually
373 * this ought to be improved to let Python code really truly trap the error,
374 * but that's more of a change from the pre-8.0 semantics than I have time for
375 * now --- it will only be possible if the callback query is executed inside a
378 static ErrorData *PLy_error_in_progress = NULL;
380 static PyObject *PLy_interp_globals = NULL;
381 static PyObject *PLy_interp_safe_globals = NULL;
382 static HTAB *PLy_procedure_cache = NULL;
383 static HTAB *PLy_trigger_cache = NULL;
385 /* Python exceptions */
386 static PyObject *PLy_exc_error = NULL;
387 static PyObject *PLy_exc_fatal = NULL;
388 static PyObject *PLy_exc_spi_error = NULL;
390 /* some globals for the python module */
391 static char PLy_plan_doc[] = {
392 "Store a PostgreSQL plan"
395 static char PLy_result_doc[] = {
396 "Results of a PostgreSQL query"
401 * the function definitions
405 * This routine is a crock, and so is everyplace that calls it. The problem
406 * is that the cached form of plpython functions/queries is allocated permanently
407 * (mostly via malloc()) and never released until backend exit. Subsidiary
408 * data structures such as fmgr info records therefore must live forever
409 * as well. A better implementation would store all this stuff in a per-
410 * function memory context that could be reclaimed at need. In the meantime,
411 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
412 * it might allocate, and whatever the eventual function might allocate using
413 * fn_mcxt, will live forever too.
416 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
418 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
422 plpython_error_callback(void *arg)
424 if (PLy_curr_procedure)
425 errcontext("PL/Python function \"%s\"",
426 PLy_procedure_name(PLy_curr_procedure));
430 plpython_inline_error_callback(void *arg)
432 errcontext("PL/Python anonymous code block");
436 plpython_trigger_error_callback(void *arg)
438 if (PLy_curr_procedure)
439 errcontext("while modifying trigger row");
443 plpython_return_error_callback(void *arg)
445 if (PLy_curr_procedure)
446 errcontext("while creating return value");
450 plpython_call_handler(PG_FUNCTION_ARGS)
453 PLyProcedure *save_curr_proc;
454 ErrorContextCallback plerrcontext;
456 if (SPI_connect() != SPI_OK_CONNECT)
457 elog(ERROR, "SPI_connect failed");
459 save_curr_proc = PLy_curr_procedure;
462 * Setup error traceback support for ereport()
464 plerrcontext.callback = plpython_error_callback;
465 plerrcontext.previous = error_context_stack;
466 error_context_stack = &plerrcontext;
472 if (CALLED_AS_TRIGGER(fcinfo))
476 proc = PLy_procedure_get(fcinfo->flinfo->fn_oid, true);
477 PLy_curr_procedure = proc;
478 trv = PLy_trigger_handler(fcinfo, proc);
479 retval = PointerGetDatum(trv);
483 proc = PLy_procedure_get(fcinfo->flinfo->fn_oid, false);
484 PLy_curr_procedure = proc;
485 retval = PLy_function_handler(fcinfo, proc);
490 PLy_curr_procedure = save_curr_proc;
496 /* Pop the error context stack */
497 error_context_stack = plerrcontext.previous;
499 PLy_curr_procedure = save_curr_proc;
505 plpython_inline_handler(PG_FUNCTION_ARGS)
507 InlineCodeBlock *codeblock = (InlineCodeBlock *) DatumGetPointer(PG_GETARG_DATUM(0));
508 FunctionCallInfoData fake_fcinfo;
510 PLyProcedure *save_curr_proc;
511 PLyProcedure *volatile proc = NULL;
512 ErrorContextCallback plerrcontext;
514 if (SPI_connect() != SPI_OK_CONNECT)
515 elog(ERROR, "SPI_connect failed");
517 save_curr_proc = PLy_curr_procedure;
520 * Setup error traceback support for ereport()
522 plerrcontext.callback = plpython_inline_error_callback;
523 plerrcontext.previous = error_context_stack;
524 error_context_stack = &plerrcontext;
526 MemSet(&fake_fcinfo, 0, sizeof(fake_fcinfo));
527 MemSet(&flinfo, 0, sizeof(flinfo));
528 fake_fcinfo.flinfo = &flinfo;
529 flinfo.fn_oid = InvalidOid;
530 flinfo.fn_mcxt = CurrentMemoryContext;
532 proc = PLy_malloc0(sizeof(PLyProcedure));
533 proc->pyname = PLy_strdup("__plpython_inline_block");
534 proc->result.out.d.typoid = VOIDOID;
538 PLy_procedure_compile(proc, codeblock->source_text);
539 PLy_curr_procedure = proc;
540 PLy_function_handler(&fake_fcinfo, proc);
544 PLy_procedure_delete(proc);
545 PLy_curr_procedure = save_curr_proc;
551 PLy_procedure_delete(proc);
553 /* Pop the error context stack */
554 error_context_stack = plerrcontext.previous;
556 PLy_curr_procedure = save_curr_proc;
561 /* trigger and function sub handlers
563 * the python function is expected to return Py_None if the tuple is
564 * acceptable and unmodified. Otherwise it should return a PyString
565 * object who's value is SKIP, or MODIFY. SKIP means don't perform
566 * this action. MODIFY means the tuple has been modified, so update
567 * tuple and perform action. SKIP and MODIFY assume the trigger fires
568 * BEFORE the event and is ROW level. postgres expects the function
569 * to take no arguments and return an argument of type trigger.
572 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *proc)
575 PyObject *volatile plargs = NULL;
576 PyObject *volatile plrv = NULL;
579 Assert(CALLED_AS_TRIGGER(fcinfo));
582 * Input/output conversion for trigger tuples. Use the result
583 * TypeInfo variable to store the tuple conversion info. We do
584 * this over again on each call to cover the possibility that the
585 * relation's tupdesc changed since the trigger was last called.
586 * PLy_input_tuple_funcs and PLy_output_tuple_funcs are
587 * responsible for not doing repetitive work.
589 tdata = (TriggerData *) fcinfo->context;
591 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
592 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
596 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
597 plrv = PLy_procedure_call(proc, "TD", plargs);
599 Assert(plrv != NULL);
600 Assert(!PLy_error_in_progress);
603 * Disconnect from SPI manager
605 if (SPI_finish() != SPI_OK_FINISH)
606 elog(ERROR, "SPI_finish failed");
609 * return of None means we're happy with the tuple
615 if (PyString_Check(plrv))
616 srv = PyString_AsString(plrv);
617 else if (PyUnicode_Check(plrv))
618 srv = PLyUnicode_AsString(plrv);
622 (errcode(ERRCODE_DATA_EXCEPTION),
623 errmsg("unexpected return value from trigger procedure"),
624 errdetail("Expected None or a string.")));
625 srv = NULL; /* keep compiler quiet */
628 if (pg_strcasecmp(srv, "SKIP") == 0)
630 else if (pg_strcasecmp(srv, "MODIFY") == 0)
632 TriggerData *tdata = (TriggerData *) fcinfo->context;
634 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
635 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
636 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
639 (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
641 else if (pg_strcasecmp(srv, "OK") != 0)
644 * accept "OK" as an alternative to None; otherwise, raise an
648 (errcode(ERRCODE_DATA_EXCEPTION),
649 errmsg("unexpected return value from trigger procedure"),
650 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
670 PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd, TriggerData *tdata,
673 PyObject *volatile plntup;
674 PyObject *volatile plkeys;
675 PyObject *volatile platt;
676 PyObject *volatile plval;
677 PyObject *volatile plstr;
683 int *volatile modattrs;
684 Datum *volatile modvalues;
685 char *volatile modnulls;
687 ErrorContextCallback plerrcontext;
689 plerrcontext.callback = plpython_trigger_error_callback;
690 plerrcontext.previous = error_context_stack;
691 error_context_stack = &plerrcontext;
693 plntup = plkeys = platt = plval = plstr = NULL;
700 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
702 (errmsg("TD[\"new\"] deleted, cannot modify row")));
703 if (!PyDict_Check(plntup))
705 (errmsg("TD[\"new\"] is not a dictionary")));
708 plkeys = PyDict_Keys(plntup);
709 natts = PyList_Size(plkeys);
711 modattrs = (int *) palloc(natts * sizeof(int));
712 modvalues = (Datum *) palloc(natts * sizeof(Datum));
713 modnulls = (char *) palloc(natts * sizeof(char));
715 tupdesc = tdata->tg_relation->rd_att;
717 for (i = 0; i < natts; i++)
721 platt = PyList_GetItem(plkeys, i);
722 if (PyString_Check(platt))
723 plattstr = PyString_AsString(platt);
724 else if (PyUnicode_Check(platt))
725 plattstr = PLyUnicode_AsString(platt);
729 (errmsg("TD[\"new\"] dictionary key at ordinal position %d is not a string", i)));
730 plattstr = NULL; /* keep compiler quiet */
732 attn = SPI_fnumber(tupdesc, plattstr);
733 if (attn == SPI_ERROR_NOATTRIBUTE)
735 (errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
739 plval = PyDict_GetItem(plntup, platt);
741 elog(FATAL, "Python interpreter is probably corrupted");
747 if (tupdesc->attrs[atti]->attisdropped)
749 modvalues[i] = (Datum) 0;
752 else if (plval != Py_None)
754 PLyObToDatum *att = &proc->result.out.r.atts[atti];
756 modvalues[i] = (att->func) (att,
757 tupdesc->attrs[atti]->atttypmod,
764 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
766 proc->result.out.r.atts[atti].typioparam,
767 tupdesc->attrs[atti]->atttypmod);
775 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
776 modattrs, modvalues, modnulls);
778 elog(ERROR, "SPI_modifytuple failed: error %d", SPI_result);
805 error_context_stack = plerrcontext.previous;
811 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
813 TriggerData *tdata = (TriggerData *) fcinfo->context;
824 PyObject *volatile pltdata = NULL;
829 pltdata = PyDict_New();
831 PLy_elog(ERROR, "could not create new dictionary while building trigger arguments");
833 pltname = PyString_FromString(tdata->tg_trigger->tgname);
834 PyDict_SetItemString(pltdata, "name", pltname);
837 stroid = DatumGetCString(DirectFunctionCall1(oidout,
838 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
839 pltrelid = PyString_FromString(stroid);
840 PyDict_SetItemString(pltdata, "relid", pltrelid);
844 stroid = SPI_getrelname(tdata->tg_relation);
845 plttablename = PyString_FromString(stroid);
846 PyDict_SetItemString(pltdata, "table_name", plttablename);
847 Py_DECREF(plttablename);
850 stroid = SPI_getnspname(tdata->tg_relation);
851 plttableschema = PyString_FromString(stroid);
852 PyDict_SetItemString(pltdata, "table_schema", plttableschema);
853 Py_DECREF(plttableschema);
856 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
857 pltwhen = PyString_FromString("BEFORE");
858 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
859 pltwhen = PyString_FromString("AFTER");
860 else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
861 pltwhen = PyString_FromString("INSTEAD OF");
864 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
865 pltwhen = NULL; /* keep compiler quiet */
867 PyDict_SetItemString(pltdata, "when", pltwhen);
870 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
872 pltlevel = PyString_FromString("ROW");
873 PyDict_SetItemString(pltdata, "level", pltlevel);
876 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
878 pltevent = PyString_FromString("INSERT");
880 PyDict_SetItemString(pltdata, "old", Py_None);
881 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
882 tdata->tg_relation->rd_att);
883 PyDict_SetItemString(pltdata, "new", pytnew);
885 *rv = tdata->tg_trigtuple;
887 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
889 pltevent = PyString_FromString("DELETE");
891 PyDict_SetItemString(pltdata, "new", Py_None);
892 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
893 tdata->tg_relation->rd_att);
894 PyDict_SetItemString(pltdata, "old", pytold);
896 *rv = tdata->tg_trigtuple;
898 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
900 pltevent = PyString_FromString("UPDATE");
902 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
903 tdata->tg_relation->rd_att);
904 PyDict_SetItemString(pltdata, "new", pytnew);
906 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
907 tdata->tg_relation->rd_att);
908 PyDict_SetItemString(pltdata, "old", pytold);
910 *rv = tdata->tg_newtuple;
914 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
915 pltevent = NULL; /* keep compiler quiet */
918 PyDict_SetItemString(pltdata, "event", pltevent);
921 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
923 pltlevel = PyString_FromString("STATEMENT");
924 PyDict_SetItemString(pltdata, "level", pltlevel);
927 PyDict_SetItemString(pltdata, "old", Py_None);
928 PyDict_SetItemString(pltdata, "new", Py_None);
931 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
932 pltevent = PyString_FromString("INSERT");
933 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
934 pltevent = PyString_FromString("DELETE");
935 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
936 pltevent = PyString_FromString("UPDATE");
937 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
938 pltevent = PyString_FromString("TRUNCATE");
941 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
942 pltevent = NULL; /* keep compiler quiet */
945 PyDict_SetItemString(pltdata, "event", pltevent);
949 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
951 if (tdata->tg_trigger->tgnargs)
959 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
960 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
962 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
965 * stolen, don't Py_DECREF
967 PyList_SetItem(pltargs, i, pltarg);
975 PyDict_SetItemString(pltdata, "args", pltargs);
990 /* function handler and friends */
992 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *proc)
995 PyObject *volatile plargs = NULL;
996 PyObject *volatile plrv = NULL;
997 ErrorContextCallback plerrcontext;
1001 if (!proc->is_setof || proc->setof == NULL)
1004 * Simple type returning function or first time for SETOF function:
1005 * actually execute the function.
1007 plargs = PLy_function_build_args(fcinfo, proc);
1008 plrv = PLy_procedure_call(proc, "args", plargs);
1009 if (!proc->is_setof)
1012 * SETOF function parameters will be deleted when last row is
1015 PLy_function_delete_args(proc);
1016 Assert(plrv != NULL);
1017 Assert(!PLy_error_in_progress);
1021 * If it returns a set, call the iterator to get the next return item.
1022 * We stay in the SPI context while doing this, because PyIter_Next()
1023 * calls back into Python code which might contain SPI calls.
1027 bool has_error = false;
1028 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1030 if (proc->setof == NULL)
1032 /* first time -- do checks and setup */
1033 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1034 (rsi->allowedModes & SFRM_ValuePerCall) == 0)
1037 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1038 errmsg("unsupported set function return mode"),
1039 errdetail("PL/Python set-returning functions only support returning only value per call.")));
1041 rsi->returnMode = SFRM_ValuePerCall;
1043 /* Make iterator out of returned object */
1044 proc->setof = PyObject_GetIter(plrv);
1048 if (proc->setof == NULL)
1050 (errcode(ERRCODE_DATATYPE_MISMATCH),
1051 errmsg("returned object cannot be iterated"),
1052 errdetail("PL/Python set-returning functions must return an iterable object.")));
1055 /* Fetch next from iterator */
1056 plrv = PyIter_Next(proc->setof);
1058 rsi->isDone = ExprMultipleResult;
1061 rsi->isDone = ExprEndResult;
1062 has_error = PyErr_Occurred() != NULL;
1065 if (rsi->isDone == ExprEndResult)
1067 /* Iterator is exhausted or error happened */
1068 Py_DECREF(proc->setof);
1074 PLy_function_delete_args(proc);
1078 (errcode(ERRCODE_DATA_EXCEPTION),
1079 errmsg("error fetching next item from iterator")));
1081 /* Disconnect from the SPI manager before returning */
1082 if (SPI_finish() != SPI_OK_FINISH)
1083 elog(ERROR, "SPI_finish failed");
1085 fcinfo->isnull = true;
1086 return (Datum) NULL;
1091 * Disconnect from SPI manager and then create the return values datum
1092 * (if the input function does a palloc for it this must not be
1093 * allocated in the SPI memory context because SPI_finish would free
1096 if (SPI_finish() != SPI_OK_FINISH)
1097 elog(ERROR, "SPI_finish failed");
1099 plerrcontext.callback = plpython_return_error_callback;
1100 plerrcontext.previous = error_context_stack;
1101 error_context_stack = &plerrcontext;
1104 * If the function is declared to return void, the Python return value
1105 * must be None. For void-returning functions, we also treat a None
1106 * return value as a special "void datum" rather than NULL (as is the
1107 * case for non-void-returning functions).
1109 if (proc->result.out.d.typoid == VOIDOID)
1111 if (plrv != Py_None)
1113 (errcode(ERRCODE_DATATYPE_MISMATCH),
1114 errmsg("PL/Python function with return type \"void\" did not return None")));
1116 fcinfo->isnull = false;
1119 else if (plrv == Py_None)
1121 fcinfo->isnull = true;
1122 if (proc->result.is_rowtype < 1)
1123 rv = InputFunctionCall(&proc->result.out.d.typfunc,
1125 proc->result.out.d.typioparam,
1131 else if (proc->result.is_rowtype >= 1)
1133 HeapTuple tuple = NULL;
1135 if (PySequence_Check(plrv))
1136 /* composite type as sequence (tuple, list etc) */
1137 tuple = PLySequence_ToTuple(&proc->result, plrv);
1138 else if (PyMapping_Check(plrv))
1139 /* composite type as mapping (currently only dict) */
1140 tuple = PLyMapping_ToTuple(&proc->result, plrv);
1142 /* returned as smth, must provide method __getattr__(name) */
1143 tuple = PLyObject_ToTuple(&proc->result, plrv);
1147 fcinfo->isnull = false;
1148 rv = HeapTupleGetDatum(tuple);
1152 fcinfo->isnull = true;
1158 fcinfo->isnull = false;
1159 rv = (proc->result.out.d.func) (&proc->result.out.d, -1, plrv);
1171 error_context_stack = plerrcontext.previous;
1180 PLy_procedure_call(PLyProcedure *proc, char *kargs, PyObject *vargs)
1184 PyDict_SetItemString(proc->globals, kargs, vargs);
1185 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
1186 proc->globals, proc->globals);
1189 * If there was an error in a PG callback, propagate that no matter what
1190 * Python claims about its success.
1192 if (PLy_error_in_progress)
1194 ErrorData *edata = PLy_error_in_progress;
1196 PLy_error_in_progress = NULL;
1197 ReThrowError(edata);
1200 if (rv == NULL || PyErr_Occurred())
1203 PLy_elog(ERROR, NULL);
1210 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc)
1212 PyObject *volatile arg = NULL;
1213 PyObject *volatile args = NULL;
1218 args = PyList_New(proc->nargs);
1219 for (i = 0; i < proc->nargs; i++)
1221 if (proc->args[i].is_rowtype > 0)
1223 if (fcinfo->argnull[i])
1231 HeapTupleData tmptup;
1233 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
1234 /* Extract rowtype info and find a tupdesc */
1235 tupType = HeapTupleHeaderGetTypeId(td);
1236 tupTypmod = HeapTupleHeaderGetTypMod(td);
1237 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1239 /* Set up I/O funcs if not done yet */
1240 if (proc->args[i].is_rowtype != 1)
1241 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
1243 /* Build a temporary HeapTuple control structure */
1244 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1247 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
1248 ReleaseTupleDesc(tupdesc);
1253 if (fcinfo->argnull[i])
1257 arg = (proc->args[i].in.d.func) (&(proc->args[i].in.d),
1268 if (PyList_SetItem(args, i, arg) == -1)
1269 PLy_elog(ERROR, "PyList_SetItem() failed, while setting up arguments");
1271 if (proc->argnames && proc->argnames[i] &&
1272 PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1)
1273 PLy_elog(ERROR, "PyDict_SetItemString() failed, while setting up arguments");
1291 PLy_function_delete_args(PLyProcedure *proc)
1295 if (!proc->argnames)
1298 for (i = 0; i < proc->nargs; i++)
1299 if (proc->argnames[i])
1300 PyDict_DelItemString(proc->globals, proc->argnames[i]);
1304 * Decide whether a cached PLyProcedure struct is still valid
1307 PLy_procedure_valid(PLyProcedure *proc, HeapTuple procTup)
1309 Assert(proc != NULL);
1311 /* If the pg_proc tuple has changed, it's not valid */
1312 return (proc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&
1313 ItemPointerEquals(&proc->fn_tid, &procTup->t_self));
1318 * PLyProcedure functions
1321 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
1322 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
1323 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
1326 static PLyProcedure *
1327 PLy_procedure_get(Oid fn_oid, bool is_trigger)
1330 PLyProcedureEntry *entry;
1333 procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
1334 if (!HeapTupleIsValid(procTup))
1335 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1337 /* Look for the function in the corresponding cache */
1339 entry = hash_search(PLy_trigger_cache,
1340 &fn_oid, HASH_ENTER, &found);
1342 entry = hash_search(PLy_procedure_cache,
1343 &fn_oid, HASH_ENTER, &found);
1349 /* Haven't found it, create a new cache entry */
1350 entry->proc = PLy_procedure_create(procTup, fn_oid, is_trigger);
1352 else if (!PLy_procedure_valid(entry->proc, procTup))
1354 /* Found it, but it's invalid, free and reuse the cache entry */
1355 PLy_procedure_delete(entry->proc);
1356 PLy_free(entry->proc);
1357 entry->proc = PLy_procedure_create(procTup, fn_oid, is_trigger);
1359 /* Found it and it's valid, it's fine to use it */
1363 /* Do not leave an uninitialised entry in the cache */
1365 hash_search(PLy_trigger_cache,
1366 &fn_oid, HASH_REMOVE, NULL);
1368 hash_search(PLy_procedure_cache,
1369 &fn_oid, HASH_REMOVE, NULL);
1374 ReleaseSysCache(procTup);
1380 * Create a new PLyProcedure structure
1382 static PLyProcedure *
1383 PLy_procedure_create(HeapTuple procTup, Oid fn_oid, bool is_trigger)
1385 char procName[NAMEDATALEN + 256];
1386 Form_pg_proc procStruct;
1387 PLyProcedure *volatile proc;
1388 char *volatile procSource = NULL;
1394 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1395 rv = snprintf(procName, sizeof(procName),
1396 "__plpython_procedure_%s_%u",
1397 NameStr(procStruct->proname),
1399 if (rv >= sizeof(procName) || rv < 0)
1400 elog(ERROR, "procedure name would overrun buffer");
1402 proc = PLy_malloc(sizeof(PLyProcedure));
1403 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1404 proc->pyname = PLy_strdup(procName);
1405 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1406 proc->fn_tid = procTup->t_self;
1407 /* Remember if function is STABLE/IMMUTABLE */
1409 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1410 PLy_typeinfo_init(&proc->result);
1411 for (i = 0; i < FUNC_MAX_ARGS; i++)
1412 PLy_typeinfo_init(&proc->args[i]);
1414 proc->code = proc->statics = NULL;
1415 proc->globals = NULL;
1416 proc->is_setof = procStruct->proretset;
1418 proc->argnames = NULL;
1423 * get information required for output conversion of the return value,
1424 * but only if this isn't a trigger.
1428 HeapTuple rvTypeTup;
1429 Form_pg_type rvTypeStruct;
1431 rvTypeTup = SearchSysCache1(TYPEOID,
1432 ObjectIdGetDatum(procStruct->prorettype));
1433 if (!HeapTupleIsValid(rvTypeTup))
1434 elog(ERROR, "cache lookup failed for type %u",
1435 procStruct->prorettype);
1436 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1438 /* Disallow pseudotype result, except for void */
1439 if (rvTypeStruct->typtype == TYPTYPE_PSEUDO &&
1440 procStruct->prorettype != VOIDOID)
1442 if (procStruct->prorettype == TRIGGEROID)
1444 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1445 errmsg("trigger functions can only be called as triggers")));
1448 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1449 errmsg("PL/Python functions cannot return type %s",
1450 format_type_be(procStruct->prorettype))));
1453 if (rvTypeStruct->typtype == TYPTYPE_COMPOSITE)
1456 * Tuple: set up later, during first call to
1457 * PLy_function_handler
1459 proc->result.out.d.typoid = procStruct->prorettype;
1460 proc->result.is_rowtype = 2;
1463 PLy_output_datum_func(&proc->result, rvTypeTup);
1465 ReleaseSysCache(rvTypeTup);
1469 * Now get information required for input conversion of the
1470 * procedure's arguments. Note that we ignore output arguments here
1471 * --- since we don't support returning record, and that was already
1472 * checked above, there's no need to worry about multiple output
1475 if (procStruct->pronargs)
1484 /* extract argument type info from the pg_proc tuple */
1485 total = get_func_arg_info(procTup, &types, &names, &modes);
1487 /* count number of in+inout args into proc->nargs */
1489 proc->nargs = total;
1492 /* proc->nargs was initialized to 0 above */
1493 for (i = 0; i < total; i++)
1495 if (modes[i] != PROARGMODE_OUT &&
1496 modes[i] != PROARGMODE_TABLE)
1501 proc->argnames = (char **) PLy_malloc0(sizeof(char *) * proc->nargs);
1502 for (i = pos = 0; i < total; i++)
1504 HeapTuple argTypeTup;
1505 Form_pg_type argTypeStruct;
1508 (modes[i] == PROARGMODE_OUT ||
1509 modes[i] == PROARGMODE_TABLE))
1510 continue; /* skip OUT arguments */
1512 Assert(types[i] == procStruct->proargtypes.values[pos]);
1514 argTypeTup = SearchSysCache1(TYPEOID,
1515 ObjectIdGetDatum(types[i]));
1516 if (!HeapTupleIsValid(argTypeTup))
1517 elog(ERROR, "cache lookup failed for type %u", types[i]);
1518 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1520 /* check argument type is OK, set up I/O function info */
1521 switch (argTypeStruct->typtype)
1523 case TYPTYPE_PSEUDO:
1524 /* Disallow pseudotype argument */
1526 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1527 errmsg("PL/Python functions cannot accept type %s",
1528 format_type_be(types[i]))));
1530 case TYPTYPE_COMPOSITE:
1531 /* we'll set IO funcs at first call */
1532 proc->args[pos].is_rowtype = 2;
1535 PLy_input_datum_func(&(proc->args[pos]),
1541 /* get argument name */
1542 proc->argnames[pos] = names ? PLy_strdup(names[i]) : NULL;
1544 ReleaseSysCache(argTypeTup);
1551 * get the text of the function.
1553 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1554 Anum_pg_proc_prosrc, &isnull);
1556 elog(ERROR, "null prosrc");
1557 procSource = TextDatumGetCString(prosrcdatum);
1559 PLy_procedure_compile(proc, procSource);
1566 PLy_procedure_delete(proc);
1578 * Insert the procedure into the Python interpreter
1581 PLy_procedure_compile(PLyProcedure *proc, const char *src)
1583 PyObject *crv = NULL;
1586 proc->globals = PyDict_Copy(PLy_interp_globals);
1589 * SD is private preserved data between calls. GD is global data shared by
1592 proc->statics = PyDict_New();
1593 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1596 * insert the function code into the interpreter
1598 msrc = PLy_procedure_munge_source(proc->pyname, src);
1599 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1605 char call[NAMEDATALEN + 256];
1610 * compile a call to the function
1612 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1613 if (clen < 0 || clen >= sizeof(call))
1614 elog(ERROR, "string would overflow buffer");
1615 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1616 if (proc->code != NULL)
1620 PLy_elog(ERROR, "could not compile PL/Python function \"%s\"", proc->proname);
1624 PLy_procedure_munge_source(const char *name, const char *src)
1633 * room for function source and the def statement
1635 mlen = (strlen(src) * 2) + strlen(name) + 16;
1637 mrc = PLy_malloc(mlen);
1638 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1639 Assert(plen >= 0 && plen < mlen);
1646 if (*sp == '\r' && *(sp + 1) == '\n')
1649 if (*sp == '\n' || *sp == '\r')
1662 if (mp > (mrc + mlen))
1663 elog(FATAL, "buffer overrun in PLy_munge_source");
1669 PLy_procedure_delete(PLyProcedure *proc)
1673 Py_XDECREF(proc->code);
1674 Py_XDECREF(proc->statics);
1675 Py_XDECREF(proc->globals);
1677 PLy_free(proc->proname);
1679 PLy_free(proc->pyname);
1680 for (i = 0; i < proc->nargs; i++)
1682 if (proc->args[i].is_rowtype == 1)
1684 if (proc->args[i].in.r.atts)
1685 PLy_free(proc->args[i].in.r.atts);
1686 if (proc->args[i].out.r.atts)
1687 PLy_free(proc->args[i].out.r.atts);
1689 if (proc->argnames && proc->argnames[i])
1690 PLy_free(proc->argnames[i]);
1693 PLy_free(proc->argnames);
1697 * Conversion functions. Remember output from Python is input to
1698 * PostgreSQL, and vice versa.
1701 PLy_input_tuple_funcs(PLyTypeInfo *arg, TupleDesc desc)
1705 if (arg->is_rowtype == 0)
1706 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1707 arg->is_rowtype = 1;
1709 if (arg->in.r.natts != desc->natts)
1712 PLy_free(arg->in.r.atts);
1713 arg->in.r.natts = desc->natts;
1714 arg->in.r.atts = PLy_malloc0(desc->natts * sizeof(PLyDatumToOb));
1717 for (i = 0; i < desc->natts; i++)
1721 if (desc->attrs[i]->attisdropped)
1724 if (arg->in.r.atts[i].typoid == desc->attrs[i]->atttypid)
1725 continue; /* already set up this entry */
1727 typeTup = SearchSysCache1(TYPEOID,
1728 ObjectIdGetDatum(desc->attrs[i]->atttypid));
1729 if (!HeapTupleIsValid(typeTup))
1730 elog(ERROR, "cache lookup failed for type %u",
1731 desc->attrs[i]->atttypid);
1733 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1734 desc->attrs[i]->atttypid,
1737 ReleaseSysCache(typeTup);
1742 PLy_output_tuple_funcs(PLyTypeInfo *arg, TupleDesc desc)
1746 if (arg->is_rowtype == 0)
1747 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1748 arg->is_rowtype = 1;
1750 if (arg->out.r.natts != desc->natts)
1752 if (arg->out.r.atts)
1753 PLy_free(arg->out.r.atts);
1754 arg->out.r.natts = desc->natts;
1755 arg->out.r.atts = PLy_malloc0(desc->natts * sizeof(PLyDatumToOb));
1758 for (i = 0; i < desc->natts; i++)
1762 if (desc->attrs[i]->attisdropped)
1765 if (arg->out.r.atts[i].typoid == desc->attrs[i]->atttypid)
1766 continue; /* already set up this entry */
1768 typeTup = SearchSysCache1(TYPEOID,
1769 ObjectIdGetDatum(desc->attrs[i]->atttypid));
1770 if (!HeapTupleIsValid(typeTup))
1771 elog(ERROR, "cache lookup failed for type %u",
1772 desc->attrs[i]->atttypid);
1774 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
1776 ReleaseSysCache(typeTup);
1781 PLy_output_datum_func(PLyTypeInfo *arg, HeapTuple typeTup)
1783 if (arg->is_rowtype > 0)
1784 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
1785 arg->is_rowtype = 0;
1786 PLy_output_datum_func2(&(arg->out.d), typeTup);
1790 PLy_output_datum_func2(PLyObToDatum *arg, HeapTuple typeTup)
1792 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1795 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
1796 arg->typoid = HeapTupleGetOid(typeTup);
1797 arg->typioparam = getTypeIOParam(typeTup);
1798 arg->typbyval = typeStruct->typbyval;
1800 element_type = get_element_type(arg->typoid);
1803 * Select a conversion function to convert Python objects to PostgreSQL
1804 * datums. Most data types can go through the generic function.
1806 switch (getBaseType(element_type ? element_type : arg->typoid))
1809 arg->func = PLyObject_ToBool;
1812 arg->func = PLyObject_ToBytea;
1815 arg->func = PLyObject_ToDatum;
1824 if (type_is_rowtype(element_type))
1826 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1827 errmsg("PL/Python functions cannot return type %s",
1828 format_type_be(arg->typoid)),
1829 errdetail("PL/Python does not support conversion to arrays of row types.")));
1831 arg->elm = PLy_malloc0(sizeof(*arg->elm));
1832 arg->elm->func = arg->func;
1833 arg->func = PLySequence_ToArray;
1835 arg->elm->typoid = element_type;
1836 get_type_io_data(element_type, IOFunc_input,
1837 &arg->elm->typlen, &arg->elm->typbyval, &arg->elm->typalign, &dummy_delim,
1838 &arg->elm->typioparam, &funcid);
1839 perm_fmgr_info(funcid, &arg->elm->typfunc);
1844 PLy_input_datum_func(PLyTypeInfo *arg, Oid typeOid, HeapTuple typeTup)
1846 if (arg->is_rowtype > 0)
1847 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
1848 arg->is_rowtype = 0;
1849 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
1853 PLy_input_datum_func2(PLyDatumToOb *arg, Oid typeOid, HeapTuple typeTup)
1855 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1856 Oid element_type = get_element_type(typeOid);
1858 /* Get the type's conversion information */
1859 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
1860 arg->typoid = HeapTupleGetOid(typeTup);
1861 arg->typioparam = getTypeIOParam(typeTup);
1862 arg->typbyval = typeStruct->typbyval;
1863 arg->typlen = typeStruct->typlen;
1864 arg->typalign = typeStruct->typalign;
1866 /* Determine which kind of Python object we will convert to */
1867 switch (getBaseType(element_type ? element_type : typeOid))
1870 arg->func = PLyBool_FromBool;
1873 arg->func = PLyFloat_FromFloat4;
1876 arg->func = PLyFloat_FromFloat8;
1879 arg->func = PLyFloat_FromNumeric;
1882 arg->func = PLyInt_FromInt16;
1885 arg->func = PLyInt_FromInt32;
1888 arg->func = PLyLong_FromInt64;
1891 arg->func = PLyBytes_FromBytea;
1894 arg->func = PLyString_FromDatum;
1903 arg->elm = PLy_malloc0(sizeof(*arg->elm));
1904 arg->elm->func = arg->func;
1905 arg->func = PLyList_FromArray;
1906 arg->elm->typoid = element_type;
1907 get_type_io_data(element_type, IOFunc_output,
1908 &arg->elm->typlen, &arg->elm->typbyval, &arg->elm->typalign, &dummy_delim,
1909 &arg->elm->typioparam, &funcid);
1910 perm_fmgr_info(funcid, &arg->elm->typfunc);
1915 PLy_typeinfo_init(PLyTypeInfo *arg)
1917 arg->is_rowtype = -1;
1918 arg->in.r.natts = arg->out.r.natts = 0;
1919 arg->in.r.atts = NULL;
1920 arg->out.r.atts = NULL;
1924 PLy_typeinfo_dealloc(PLyTypeInfo *arg)
1926 if (arg->is_rowtype == 1)
1929 PLy_free(arg->in.r.atts);
1930 if (arg->out.r.atts)
1931 PLy_free(arg->out.r.atts);
1936 PLyBool_FromBool(PLyDatumToOb *arg, Datum d)
1939 * We would like to use Py_RETURN_TRUE and Py_RETURN_FALSE here for
1940 * generating SQL from trigger functions, but those are only supported in
1941 * Python >= 2.3, and we support older versions.
1942 * http://docs.python.org/api/boolObjects.html
1944 if (DatumGetBool(d))
1945 return PyBool_FromLong(1);
1946 return PyBool_FromLong(0);
1950 PLyFloat_FromFloat4(PLyDatumToOb *arg, Datum d)
1952 return PyFloat_FromDouble(DatumGetFloat4(d));
1956 PLyFloat_FromFloat8(PLyDatumToOb *arg, Datum d)
1958 return PyFloat_FromDouble(DatumGetFloat8(d));
1962 PLyFloat_FromNumeric(PLyDatumToOb *arg, Datum d)
1965 * Numeric is cast to a PyFloat: This results in a loss of precision Would
1966 * it be better to cast to PyString?
1968 Datum f = DirectFunctionCall1(numeric_float8, d);
1969 double x = DatumGetFloat8(f);
1971 return PyFloat_FromDouble(x);
1975 PLyInt_FromInt16(PLyDatumToOb *arg, Datum d)
1977 return PyInt_FromLong(DatumGetInt16(d));
1981 PLyInt_FromInt32(PLyDatumToOb *arg, Datum d)
1983 return PyInt_FromLong(DatumGetInt32(d));
1987 PLyLong_FromInt64(PLyDatumToOb *arg, Datum d)
1989 /* on 32 bit platforms "long" may be too small */
1990 if (sizeof(int64) > sizeof(long))
1991 return PyLong_FromLongLong(DatumGetInt64(d));
1993 return PyLong_FromLong(DatumGetInt64(d));
1997 PLyBytes_FromBytea(PLyDatumToOb *arg, Datum d)
1999 text *txt = DatumGetByteaP(d);
2000 char *str = VARDATA(txt);
2001 size_t size = VARSIZE(txt) - VARHDRSZ;
2003 return PyBytes_FromStringAndSize(str, size);
2007 PLyString_FromDatum(PLyDatumToOb *arg, Datum d)
2009 char *x = OutputFunctionCall(&arg->typfunc, d);
2010 PyObject *r = PyString_FromString(x);
2017 PLyList_FromArray(PLyDatumToOb *arg, Datum d)
2019 ArrayType *array = DatumGetArrayTypeP(d);
2020 PLyDatumToOb *elm = arg->elm;
2026 if (ARR_NDIM(array) == 0)
2027 return PyList_New(0);
2029 if (ARR_NDIM(array) != 1)
2031 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2032 errmsg("cannot convert multidimensional array to Python list"),
2033 errdetail("PL/Python only supports one-dimensional arrays.")));
2035 length = ARR_DIMS(array)[0];
2036 lbound = ARR_LBOUND(array)[0];
2037 list = PyList_New(length);
2039 for (i = 0; i < length; i++)
2045 offset = lbound + i;
2046 elem = array_ref(array, 1, &offset, arg->typlen,
2047 elm->typlen, elm->typbyval, elm->typalign,
2052 PyList_SET_ITEM(list, i, Py_None);
2055 PyList_SET_ITEM(list, i, elm->func(elm, elem));
2062 PLyDict_FromTuple(PLyTypeInfo *info, HeapTuple tuple, TupleDesc desc)
2064 PyObject *volatile dict;
2067 if (info->is_rowtype != 1)
2068 elog(ERROR, "PLyTypeInfo structure describes a datum");
2070 dict = PyDict_New();
2072 PLy_elog(ERROR, "could not create new dictionary");
2076 for (i = 0; i < info->in.r.natts; i++)
2083 if (desc->attrs[i]->attisdropped)
2086 key = NameStr(desc->attrs[i]->attname);
2087 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
2089 if (is_null || info->in.r.atts[i].func == NULL)
2090 PyDict_SetItemString(dict, key, Py_None);
2093 value = (info->in.r.atts[i].func) (&info->in.r.atts[i], vattr);
2094 PyDict_SetItemString(dict, key, value);
2110 * Convert a Python object to a PostgreSQL bool datum. This can't go
2111 * through the generic conversion function, because Python attaches a
2112 * Boolean value to everything, more things than the PostgreSQL bool
2116 PLyObject_ToBool(PLyObToDatum *arg, int32 typmod, PyObject *plrv)
2120 Assert(plrv != Py_None);
2121 rv = BoolGetDatum(PyObject_IsTrue(plrv));
2123 if (get_typtype(arg->typoid) == TYPTYPE_DOMAIN)
2124 domain_check(rv, false, arg->typoid, &arg->typfunc.fn_extra, arg->typfunc.fn_mcxt);
2130 * Convert a Python object to a PostgreSQL bytea datum. This doesn't
2131 * go through the generic conversion function to circumvent problems
2132 * with embedded nulls. And it's faster this way.
2135 PLyObject_ToBytea(PLyObToDatum *arg, int32 typmod, PyObject *plrv)
2137 PyObject *volatile plrv_so = NULL;
2140 Assert(plrv != Py_None);
2142 plrv_so = PyObject_Bytes(plrv);
2144 PLy_elog(ERROR, "could not create bytes representation of Python object");
2148 char *plrv_sc = PyBytes_AsString(plrv_so);
2149 size_t len = PyBytes_Size(plrv_so);
2150 size_t size = len + VARHDRSZ;
2151 bytea *result = palloc(size);
2153 SET_VARSIZE(result, size);
2154 memcpy(VARDATA(result), plrv_sc, len);
2155 rv = PointerGetDatum(result);
2159 Py_XDECREF(plrv_so);
2164 Py_XDECREF(plrv_so);
2166 if (get_typtype(arg->typoid) == TYPTYPE_DOMAIN)
2167 domain_check(rv, false, arg->typoid, &arg->typfunc.fn_extra, arg->typfunc.fn_mcxt);
2173 * Generic conversion function: Convert PyObject to cstring and
2174 * cstring into PostgreSQL type.
2177 PLyObject_ToDatum(PLyObToDatum *arg, int32 typmod, PyObject *plrv)
2179 PyObject *volatile plrv_bo = NULL;
2182 Assert(plrv != Py_None);
2184 if (PyUnicode_Check(plrv))
2185 plrv_bo = PLyUnicode_Bytes(plrv);
2188 #if PY_MAJOR_VERSION >= 3
2189 PyObject *s = PyObject_Str(plrv);
2191 plrv_bo = PLyUnicode_Bytes(s);
2194 plrv_bo = PyObject_Str(plrv);
2198 PLy_elog(ERROR, "could not create string representation of Python object");
2202 char *plrv_sc = PyBytes_AsString(plrv_bo);
2203 size_t plen = PyBytes_Size(plrv_bo);
2204 size_t slen = strlen(plrv_sc);
2208 (errcode(ERRCODE_DATATYPE_MISMATCH),
2209 errmsg("could not convert Python object into cstring: Python string representation appears to contain null bytes")));
2210 else if (slen > plen)
2211 elog(ERROR, "could not convert Python object into cstring: Python string longer than reported length");
2212 pg_verifymbstr(plrv_sc, slen, false);
2213 rv = InputFunctionCall(&arg->typfunc,
2220 Py_XDECREF(plrv_bo);
2225 Py_XDECREF(plrv_bo);
2231 PLySequence_ToArray(PLyObToDatum *arg, int32 typmod, PyObject *plrv)
2240 Assert(plrv != Py_None);
2242 if (!PySequence_Check(plrv))
2243 PLy_elog(ERROR, "return value of function with array return type is not a Python sequence");
2245 len = PySequence_Length(plrv);
2246 elems = palloc(sizeof(*elems) * len);
2247 nulls = palloc(sizeof(*nulls) * len);
2249 for (i = 0; i < len; i++)
2251 PyObject *obj = PySequence_GetItem(plrv, i);
2260 * We don't support arrays of row types yet, so the first argument
2263 elems[i] = arg->elm->func(arg->elm, -1, obj);
2269 array = construct_md_array(elems, nulls, 1, &len, &lbs,
2270 get_element_type(arg->typoid), arg->elm->typlen, arg->elm->typbyval, arg->elm->typalign);
2271 return PointerGetDatum(array);
2275 PLyMapping_ToTuple(PLyTypeInfo *info, PyObject *mapping)
2283 Assert(PyMapping_Check(mapping));
2285 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
2286 if (info->is_rowtype == 2)
2287 PLy_output_tuple_funcs(info, desc);
2288 Assert(info->is_rowtype == 1);
2291 values = palloc(sizeof(Datum) * desc->natts);
2292 nulls = palloc(sizeof(bool) * desc->natts);
2293 for (i = 0; i < desc->natts; ++i)
2296 PyObject *volatile value;
2299 key = NameStr(desc->attrs[i]->attname);
2301 att = &info->out.r.atts[i];
2304 value = PyMapping_GetItemString(mapping, key);
2305 if (value == Py_None)
2307 values[i] = (Datum) NULL;
2312 values[i] = (att->func) (att, -1, value);
2317 (errcode(ERRCODE_UNDEFINED_COLUMN),
2318 errmsg("key \"%s\" not found in mapping", key),
2319 errhint("To return null in a column, "
2320 "add the value None to the mapping with the key named after the column.")));
2333 tuple = heap_form_tuple(desc, values, nulls);
2334 ReleaseTupleDesc(desc);
2343 PLySequence_ToTuple(PLyTypeInfo *info, PyObject *sequence)
2351 Assert(PySequence_Check(sequence));
2354 * Check that sequence length is exactly same as PG tuple's. We actually
2355 * can ignore exceeding items or assume missing ones as null but to avoid
2356 * plpython developer's errors we are strict here
2358 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
2359 if (PySequence_Length(sequence) != desc->natts)
2361 (errcode(ERRCODE_DATATYPE_MISMATCH),
2362 errmsg("length of returned sequence did not match number of columns in row")));
2364 if (info->is_rowtype == 2)
2365 PLy_output_tuple_funcs(info, desc);
2366 Assert(info->is_rowtype == 1);
2369 values = palloc(sizeof(Datum) * desc->natts);
2370 nulls = palloc(sizeof(bool) * desc->natts);
2371 for (i = 0; i < desc->natts; ++i)
2373 PyObject *volatile value;
2377 att = &info->out.r.atts[i];
2380 value = PySequence_GetItem(sequence, i);
2382 if (value == Py_None)
2384 values[i] = (Datum) NULL;
2389 values[i] = (att->func) (att, -1, value);
2404 tuple = heap_form_tuple(desc, values, nulls);
2405 ReleaseTupleDesc(desc);
2414 PLyObject_ToTuple(PLyTypeInfo *info, PyObject *object)
2422 desc = lookup_rowtype_tupdesc(info->out.d.typoid, -1);
2423 if (info->is_rowtype == 2)
2424 PLy_output_tuple_funcs(info, desc);
2425 Assert(info->is_rowtype == 1);
2428 values = palloc(sizeof(Datum) * desc->natts);
2429 nulls = palloc(sizeof(bool) * desc->natts);
2430 for (i = 0; i < desc->natts; ++i)
2433 PyObject *volatile value;
2436 key = NameStr(desc->attrs[i]->attname);
2438 att = &info->out.r.atts[i];
2441 value = PyObject_GetAttrString(object, key);
2442 if (value == Py_None)
2444 values[i] = (Datum) NULL;
2449 values[i] = (att->func) (att, -1, value);
2454 (errcode(ERRCODE_UNDEFINED_COLUMN),
2455 errmsg("attribute \"%s\" does not exist in Python object", key),
2456 errhint("To return null in a column, "
2457 "let the returned object have an attribute named "
2458 "after column with value None.")));
2471 tuple = heap_form_tuple(desc, values, nulls);
2472 ReleaseTupleDesc(desc);
2480 /* initialization, some python variables function declared here */
2482 /* interface to postgresql elog */
2483 static PyObject *PLy_debug(PyObject *, PyObject *);
2484 static PyObject *PLy_log(PyObject *, PyObject *);
2485 static PyObject *PLy_info(PyObject *, PyObject *);
2486 static PyObject *PLy_notice(PyObject *, PyObject *);
2487 static PyObject *PLy_warning(PyObject *, PyObject *);
2488 static PyObject *PLy_error(PyObject *, PyObject *);
2489 static PyObject *PLy_fatal(PyObject *, PyObject *);
2491 /* PLyPlanObject, PLyResultObject and SPI interface */
2492 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
2493 static PyObject *PLy_plan_new(void);
2494 static void PLy_plan_dealloc(PyObject *);
2495 static PyObject *PLy_plan_status(PyObject *, PyObject *);
2497 static PyObject *PLy_result_new(void);
2498 static void PLy_result_dealloc(PyObject *);
2499 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
2500 static PyObject *PLy_result_status(PyObject *, PyObject *);
2501 static Py_ssize_t PLy_result_length(PyObject *);
2502 static PyObject *PLy_result_item(PyObject *, Py_ssize_t);
2503 static PyObject *PLy_result_slice(PyObject *, Py_ssize_t, Py_ssize_t);
2504 static int PLy_result_ass_item(PyObject *, Py_ssize_t, PyObject *);
2505 static int PLy_result_ass_slice(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
2508 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
2509 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
2510 static PyObject *PLy_spi_execute_query(char *query, long limit);
2511 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
2512 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
2515 static PyMethodDef PLy_plan_methods[] = {
2516 {"status", PLy_plan_status, METH_VARARGS, NULL},
2517 {NULL, NULL, 0, NULL}
2520 static PyTypeObject PLy_PlanType = {
2521 PyVarObject_HEAD_INIT(NULL, 0)
2522 "PLyPlan", /* tp_name */
2523 sizeof(PLyPlanObject), /* tp_size */
2524 0, /* tp_itemsize */
2529 PLy_plan_dealloc, /* tp_dealloc */
2535 0, /* tp_as_number */
2536 0, /* tp_as_sequence */
2537 0, /* tp_as_mapping */
2541 0, /* tp_getattro */
2542 0, /* tp_setattro */
2543 0, /* tp_as_buffer */
2544 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2545 PLy_plan_doc, /* tp_doc */
2546 0, /* tp_traverse */
2548 0, /* tp_richcompare */
2549 0, /* tp_weaklistoffset */
2551 0, /* tp_iternext */
2552 PLy_plan_methods, /* tp_tpmethods */
2555 static PySequenceMethods PLy_result_as_sequence = {
2556 PLy_result_length, /* sq_length */
2557 NULL, /* sq_concat */
2558 NULL, /* sq_repeat */
2559 PLy_result_item, /* sq_item */
2560 PLy_result_slice, /* sq_slice */
2561 PLy_result_ass_item, /* sq_ass_item */
2562 PLy_result_ass_slice, /* sq_ass_slice */
2565 static PyMethodDef PLy_result_methods[] = {
2566 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
2567 {"status", PLy_result_status, METH_VARARGS, NULL},
2568 {NULL, NULL, 0, NULL}
2571 static PyTypeObject PLy_ResultType = {
2572 PyVarObject_HEAD_INIT(NULL, 0)
2573 "PLyResult", /* tp_name */
2574 sizeof(PLyResultObject), /* tp_size */
2575 0, /* tp_itemsize */
2580 PLy_result_dealloc, /* tp_dealloc */
2586 0, /* tp_as_number */
2587 &PLy_result_as_sequence, /* tp_as_sequence */
2588 0, /* tp_as_mapping */
2592 0, /* tp_getattro */
2593 0, /* tp_setattro */
2594 0, /* tp_as_buffer */
2595 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2596 PLy_result_doc, /* tp_doc */
2597 0, /* tp_traverse */
2599 0, /* tp_richcompare */
2600 0, /* tp_weaklistoffset */
2602 0, /* tp_iternext */
2603 PLy_result_methods, /* tp_tpmethods */
2606 static PyMethodDef PLy_methods[] = {
2610 {"debug", PLy_debug, METH_VARARGS, NULL},
2611 {"log", PLy_log, METH_VARARGS, NULL},
2612 {"info", PLy_info, METH_VARARGS, NULL},
2613 {"notice", PLy_notice, METH_VARARGS, NULL},
2614 {"warning", PLy_warning, METH_VARARGS, NULL},
2615 {"error", PLy_error, METH_VARARGS, NULL},
2616 {"fatal", PLy_fatal, METH_VARARGS, NULL},
2619 * create a stored plan
2621 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
2624 * execute a plan or query
2626 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
2628 {NULL, NULL, 0, NULL}
2631 #if PY_MAJOR_VERSION >= 3
2632 static PyModuleDef PLy_module = {
2633 PyModuleDef_HEAD_INIT, /* m_base */
2634 "plpy", /* m_name */
2637 PLy_methods, /* m_methods */
2641 /* plan object methods */
2647 if ((ob = PyObject_NEW(PLyPlanObject, &PLy_PlanType)) == NULL)
2655 return (PyObject *) ob;
2660 PLy_plan_dealloc(PyObject *arg)
2662 PLyPlanObject *ob = (PLyPlanObject *) arg;
2665 SPI_freeplan(ob->plan);
2667 PLy_free(ob->types);
2672 for (i = 0; i < ob->nargs; i++)
2673 PLy_typeinfo_dealloc(&ob->args[i]);
2677 arg->ob_type->tp_free(arg);
2682 PLy_plan_status(PyObject *self, PyObject *args)
2684 if (PyArg_ParseTuple(args, ""))
2688 /* return PyInt_FromLong(self->status); */
2690 PLy_exception_set(PLy_exc_error, "plan.status takes no arguments");
2696 /* result object methods */
2699 PLy_result_new(void)
2701 PLyResultObject *ob;
2703 if ((ob = PyObject_NEW(PLyResultObject, &PLy_ResultType)) == NULL)
2706 /* ob->tuples = NULL; */
2709 ob->status = Py_None;
2710 ob->nrows = PyInt_FromLong(-1);
2711 ob->rows = PyList_New(0);
2713 return (PyObject *) ob;
2717 PLy_result_dealloc(PyObject *arg)
2719 PLyResultObject *ob = (PLyResultObject *) arg;
2721 Py_XDECREF(ob->nrows);
2722 Py_XDECREF(ob->rows);
2723 Py_XDECREF(ob->status);
2725 arg->ob_type->tp_free(arg);
2729 PLy_result_nrows(PyObject *self, PyObject *args)
2731 PLyResultObject *ob = (PLyResultObject *) self;
2733 Py_INCREF(ob->nrows);
2738 PLy_result_status(PyObject *self, PyObject *args)
2740 PLyResultObject *ob = (PLyResultObject *) self;
2742 Py_INCREF(ob->status);
2747 PLy_result_length(PyObject *arg)
2749 PLyResultObject *ob = (PLyResultObject *) arg;
2751 return PyList_Size(ob->rows);
2755 PLy_result_item(PyObject *arg, Py_ssize_t idx)
2758 PLyResultObject *ob = (PLyResultObject *) arg;
2760 rv = PyList_GetItem(ob->rows, idx);
2767 PLy_result_ass_item(PyObject *arg, Py_ssize_t idx, PyObject *item)
2770 PLyResultObject *ob = (PLyResultObject *) arg;
2773 rv = PyList_SetItem(ob->rows, idx, item);
2778 PLy_result_slice(PyObject *arg, Py_ssize_t lidx, Py_ssize_t hidx)
2781 PLyResultObject *ob = (PLyResultObject *) arg;
2783 rv = PyList_GetSlice(ob->rows, lidx, hidx);
2791 PLy_result_ass_slice(PyObject *arg, Py_ssize_t lidx, Py_ssize_t hidx, PyObject *slice)
2794 PLyResultObject *ob = (PLyResultObject *) arg;
2796 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
2802 PLy_spi_prepare(PyObject *self, PyObject *args)
2804 PLyPlanObject *plan;
2805 PyObject *list = NULL;
2806 PyObject *volatile optr = NULL;
2809 volatile MemoryContext oldcontext;
2811 /* Can't execute more if we have an unhandled error */
2812 if (PLy_error_in_progress)
2814 PLy_exception_set(PLy_exc_error, "transaction aborted");
2818 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
2820 PLy_exception_set(PLy_exc_spi_error,
2821 "invalid arguments for plpy.prepare");
2825 if (list && (!PySequence_Check(list)))
2827 PLy_exception_set(PLy_exc_spi_error,
2828 "second argument of plpy.prepare must be a sequence");
2832 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
2835 oldcontext = CurrentMemoryContext;
2843 nargs = PySequence_Length(list);
2846 plan->nargs = nargs;
2847 plan->types = PLy_malloc(sizeof(Oid) * nargs);
2848 plan->values = PLy_malloc(sizeof(Datum) * nargs);
2849 plan->args = PLy_malloc(sizeof(PLyTypeInfo) * nargs);
2852 * the other loop might throw an exception, if PLyTypeInfo
2853 * member isn't properly initialized the Py_DECREF(plan) will
2856 for (i = 0; i < nargs; i++)
2858 PLy_typeinfo_init(&plan->args[i]);
2859 plan->values[i] = PointerGetDatum(NULL);
2862 for (i = 0; i < nargs; i++)
2868 Form_pg_type typeStruct;
2870 optr = PySequence_GetItem(list, i);
2871 if (PyString_Check(optr))
2872 sptr = PyString_AsString(optr);
2873 else if (PyUnicode_Check(optr))
2874 sptr = PLyUnicode_AsString(optr);
2878 (errmsg("plpy.prepare: type name at ordinal position %d is not a string", i)));
2879 sptr = NULL; /* keep compiler quiet */
2882 /********************************************************
2883 * Resolve argument type names and then look them up by
2884 * oid in the system cache, and remember the required
2885 *information for input conversion.
2886 ********************************************************/
2888 parseTypeString(sptr, &typeId, &typmod);
2890 typeTup = SearchSysCache1(TYPEOID,
2891 ObjectIdGetDatum(typeId));
2892 if (!HeapTupleIsValid(typeTup))
2893 elog(ERROR, "cache lookup failed for type %u", typeId);
2896 optr = NULL; /* this is important */
2898 plan->types[i] = typeId;
2899 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2900 if (typeStruct->typtype != TYPTYPE_COMPOSITE)
2901 PLy_output_datum_func(&plan->args[i], typeTup);
2904 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2905 errmsg("plpy.prepare does not support composite types")));
2906 ReleaseSysCache(typeTup);
2911 pg_verifymbstr(query, strlen(query), false);
2912 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
2913 if (plan->plan == NULL)
2914 elog(ERROR, "SPI_prepare failed: %s",
2915 SPI_result_code_string(SPI_result));
2917 /* transfer plan from procCxt to topCxt */
2918 tmpplan = plan->plan;
2919 plan->plan = SPI_saveplan(tmpplan);
2920 SPI_freeplan(tmpplan);
2921 if (plan->plan == NULL)
2922 elog(ERROR, "SPI_saveplan failed: %s",
2923 SPI_result_code_string(SPI_result));
2927 MemoryContextSwitchTo(oldcontext);
2928 PLy_error_in_progress = CopyErrorData();
2932 if (!PyErr_Occurred())
2933 PLy_exception_set(PLy_exc_spi_error,
2934 "unrecognized error in PLy_spi_prepare");
2935 PLy_elog(WARNING, NULL);
2940 return (PyObject *) plan;
2943 /* execute(query="select * from foo", limit=5)
2944 * execute(plan=plan, values=(foo, bar), limit=5)
2947 PLy_spi_execute(PyObject *self, PyObject *args)
2951 PyObject *list = NULL;
2954 /* Can't execute more if we have an unhandled error */
2955 if (PLy_error_in_progress)
2957 PLy_exception_set(PLy_exc_error, "transaction aborted");
2961 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
2962 return PLy_spi_execute_query(query, limit);
2966 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
2967 is_PLyPlanObject(plan))
2968 return PLy_spi_execute_plan(plan, list, limit);
2970 PLy_exception_set(PLy_exc_error, "plpy.execute expected a query or a plan");
2975 PLy_spi_execute_plan(PyObject *ob, PyObject *list, long limit)
2980 PLyPlanObject *plan;
2981 volatile MemoryContext oldcontext;
2985 if (!PySequence_Check(list) || PyString_Check(list) || PyUnicode_Check(list))
2987 PLy_exception_set(PLy_exc_spi_error, "plpy.execute takes a sequence as its second argument");
2990 nargs = PySequence_Length(list);
2995 plan = (PLyPlanObject *) ob;
2997 if (nargs != plan->nargs)
3000 PyObject *so = PyObject_Str(list);
3003 PLy_elog(ERROR, "could not execute plan");
3004 sv = PyString_AsString(so);
3005 PLy_exception_set_plural(PLy_exc_spi_error,
3006 "Expected sequence of %d argument, got %d: %s",
3007 "Expected sequence of %d arguments, got %d: %s",
3009 plan->nargs, nargs, sv);
3015 oldcontext = CurrentMemoryContext;
3018 char *nulls = palloc(nargs * sizeof(char));
3021 for (j = 0; j < nargs; j++)
3025 elem = PySequence_GetItem(list, j);
3026 if (elem != Py_None)
3031 plan->args[j].out.d.func(&(plan->args[j].out.d),
3049 InputFunctionCall(&(plan->args[j].out.d.typfunc),
3051 plan->args[j].out.d.typioparam,
3057 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
3058 PLy_curr_procedure->fn_readonly, limit);
3066 MemoryContextSwitchTo(oldcontext);
3067 PLy_error_in_progress = CopyErrorData();
3071 * cleanup plan->values array
3073 for (k = 0; k < nargs; k++)
3075 if (!plan->args[k].out.d.typbyval &&
3076 (plan->values[k] != PointerGetDatum(NULL)))
3078 pfree(DatumGetPointer(plan->values[k]));
3079 plan->values[k] = PointerGetDatum(NULL);
3083 if (!PyErr_Occurred())
3084 PLy_exception_set(PLy_exc_error,
3085 "unrecognized error in PLy_spi_execute_plan");
3086 PLy_elog(WARNING, NULL);
3091 for (i = 0; i < nargs; i++)
3093 if (!plan->args[i].out.d.typbyval &&
3094 (plan->values[i] != PointerGetDatum(NULL)))
3096 pfree(DatumGetPointer(plan->values[i]));
3097 plan->values[i] = PointerGetDatum(NULL);
3103 PLy_exception_set(PLy_exc_spi_error,
3104 "SPI_execute_plan failed: %s",
3105 SPI_result_code_string(rv));
3109 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
3113 PLy_spi_execute_query(char *query, long limit)
3116 volatile MemoryContext oldcontext;
3118 oldcontext = CurrentMemoryContext;
3121 pg_verifymbstr(query, strlen(query), false);
3122 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
3126 MemoryContextSwitchTo(oldcontext);
3127 PLy_error_in_progress = CopyErrorData();
3129 if (!PyErr_Occurred())
3130 PLy_exception_set(PLy_exc_spi_error,
3131 "unrecognized error in PLy_spi_execute_query");
3132 PLy_elog(WARNING, NULL);
3139 PLy_exception_set(PLy_exc_spi_error,
3140 "SPI_execute failed: %s",
3141 SPI_result_code_string(rv));
3145 return PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
3149 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
3151 PLyResultObject *result;
3152 volatile MemoryContext oldcontext;
3154 result = (PLyResultObject *) PLy_result_new();
3155 Py_DECREF(result->status);
3156 result->status = PyInt_FromLong(status);
3158 if (status > 0 && tuptable == NULL)
3160 Py_DECREF(result->nrows);
3161 result->nrows = PyInt_FromLong(rows);
3163 else if (status > 0 && tuptable != NULL)
3168 Py_DECREF(result->nrows);
3169 result->nrows = PyInt_FromLong(rows);
3170 PLy_typeinfo_init(&args);
3172 oldcontext = CurrentMemoryContext;
3177 Py_DECREF(result->rows);
3178 result->rows = PyList_New(rows);
3180 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
3181 for (i = 0; i < rows; i++)
3183 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
3186 PyList_SetItem(result->rows, i, row);
3192 MemoryContextSwitchTo(oldcontext);
3193 PLy_error_in_progress = CopyErrorData();
3195 if (!PyErr_Occurred())
3196 PLy_exception_set(PLy_exc_error,
3197 "unrecognized error in PLy_spi_execute_fetch_result");
3198 PLy_typeinfo_dealloc(&args);
3199 SPI_freetuptable(tuptable);
3205 PLy_typeinfo_dealloc(&args);
3206 SPI_freetuptable(tuptable);
3209 return (PyObject *) result;
3214 * language handler and interpreter initialization
3217 #if PY_MAJOR_VERSION >= 3
3218 static PyMODINIT_FUNC
3221 return PyModule_Create(&PLy_module);
3226 static const int plpython_python_version = PY_MAJOR_VERSION;
3229 * _PG_init() - library load-time initialization
3231 * DO NOT make this static nor change its name!
3236 /* Be sure we do initialization only once (should be redundant now) */
3237 static bool inited = false;
3238 const int **version_ptr;
3244 /* Be sure we don't run Python 2 and 3 in the same session (might crash) */
3245 version_ptr = (const int **) find_rendezvous_variable("plpython_python_version");
3246 if (!(*version_ptr))
3247 *version_ptr = &plpython_python_version;
3250 if (**version_ptr != plpython_python_version)
3252 (errmsg("Python major version mismatch in session"),
3253 errdetail("This session has previously used Python major version %d, and it is now attempting to use Python major version %d.",
3254 **version_ptr, plpython_python_version),
3255 errhint("Start a new session to use a different Python major version.")));
3258 pg_bindtextdomain(TEXTDOMAIN);
3260 #if PY_MAJOR_VERSION >= 3
3261 PyImport_AppendInittab("plpy", PyInit_plpy);
3264 #if PY_MAJOR_VERSION >= 3
3265 PyImport_ImportModule("plpy");
3269 if (PyErr_Occurred())
3270 PLy_elog(FATAL, "untrapped error in initialization");
3272 memset(&hash_ctl, 0, sizeof(hash_ctl));
3273 hash_ctl.keysize = sizeof(Oid);
3274 hash_ctl.entrysize = sizeof(PLyProcedureEntry);
3275 hash_ctl.hash = oid_hash;
3276 PLy_procedure_cache = hash_create("PL/Python procedures", 32, &hash_ctl,
3277 HASH_ELEM | HASH_FUNCTION);
3279 memset(&hash_ctl, 0, sizeof(hash_ctl));
3280 hash_ctl.keysize = sizeof(Oid);
3281 hash_ctl.entrysize = sizeof(PLyProcedureEntry);
3282 hash_ctl.hash = oid_hash;
3283 PLy_trigger_cache = hash_create("PL/Python triggers", 32, &hash_ctl,
3284 HASH_ELEM | HASH_FUNCTION);
3290 PLy_init_interp(void)
3294 mainmod = PyImport_AddModule("__main__");
3295 if (mainmod == NULL || PyErr_Occurred())
3296 PLy_elog(ERROR, "could not import \"__main__\" module");
3298 PLy_interp_globals = PyModule_GetDict(mainmod);
3299 PLy_interp_safe_globals = PyDict_New();
3300 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
3302 if (PLy_interp_globals == NULL || PyErr_Occurred())
3303 PLy_elog(ERROR, "could not initialize globals");
3316 * initialize plpy module
3318 if (PyType_Ready(&PLy_PlanType) < 0)
3319 elog(ERROR, "could not initialize PLy_PlanType");
3320 if (PyType_Ready(&PLy_ResultType) < 0)
3321 elog(ERROR, "could not initialize PLy_ResultType");
3323 #if PY_MAJOR_VERSION >= 3
3324 plpy = PyModule_Create(&PLy_module);
3326 plpy = Py_InitModule("plpy", PLy_methods);
3328 plpy_dict = PyModule_GetDict(plpy);
3330 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
3332 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
3333 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
3334 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
3335 PyDict_SetItemString(plpy_dict, "Error", PLy_exc_error);
3336 PyDict_SetItemString(plpy_dict, "Fatal", PLy_exc_fatal);
3337 PyDict_SetItemString(plpy_dict, "SPIError", PLy_exc_spi_error);
3340 * initialize main module, and add plpy
3342 main_mod = PyImport_AddModule("__main__");
3343 main_dict = PyModule_GetDict(main_mod);
3344 plpy_mod = PyImport_AddModule("plpy");
3345 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
3346 if (PyErr_Occurred())
3347 elog(ERROR, "could not initialize plpy");
3350 /* the python interface to the elog function
3351 * don't confuse these with PLy_elog
3353 static PyObject *PLy_output(volatile int, PyObject *, PyObject *);
3356 PLy_debug(PyObject *self, PyObject *args)
3358 return PLy_output(DEBUG2, self, args);
3362 PLy_log(PyObject *self, PyObject *args)
3364 return PLy_output(LOG, self, args);
3368 PLy_info(PyObject *self, PyObject *args)
3370 return PLy_output(INFO, self, args);
3374 PLy_notice(PyObject *self, PyObject *args)
3376 return PLy_output(NOTICE, self, args);
3380 PLy_warning(PyObject *self, PyObject *args)
3382 return PLy_output(WARNING, self, args);
3386 PLy_error(PyObject *self, PyObject *args)
3388 return PLy_output(ERROR, self, args);
3392 PLy_fatal(PyObject *self, PyObject *args)
3394 return PLy_output(FATAL, self, args);
3399 PLy_output(volatile int level, PyObject *self, PyObject *args)
3401 PyObject *volatile so;
3403 volatile MemoryContext oldcontext;
3405 if (PyTuple_Size(args) == 1)
3408 * Treat single argument specially to avoid undesirable ('tuple',)
3413 PyArg_UnpackTuple(args, "plpy.elog", 1, 1, &o);
3414 so = PyObject_Str(o);
3417 so = PyObject_Str(args);
3418 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
3421 sv = dgettext(TEXTDOMAIN, "could not parse error message in plpy.elog");
3424 oldcontext = CurrentMemoryContext;
3427 pg_verifymbstr(sv, strlen(sv), false);
3428 elog(level, "%s", sv);
3432 MemoryContextSwitchTo(oldcontext);
3433 PLy_error_in_progress = CopyErrorData();
3436 PyErr_SetString(PLy_exc_error, sv);
3439 * Note: If sv came from PyString_AsString(), it points into storage
3440 * owned by so. So free so after using sv.
3445 * returning NULL here causes the python interpreter to bail. when
3446 * control passes back to PLy_procedure_call, we check for PG
3447 * exceptions and re-throw the error.
3456 * return a legal object so the interpreter will continue on its merry way
3464 * Get the name of the last procedure called by the backend (the
3465 * innermost, if a plpython procedure call calls the backend and the
3466 * backend calls another plpython procedure).
3468 * NB: this returns the SQL name, not the internal Python procedure name
3471 PLy_procedure_name(PLyProcedure *proc)
3474 return "<unknown procedure>";
3475 return proc->proname;
3479 * Call PyErr_SetString with a vprint interface and translation support
3482 PLy_exception_set(PyObject *exc, const char *fmt,...)
3488 vsnprintf(buf, sizeof(buf), dgettext(TEXTDOMAIN, fmt), ap);
3491 PyErr_SetString(exc, buf);
3495 * The same, pluralized.
3498 PLy_exception_set_plural(PyObject *exc,
3499 const char *fmt_singular, const char *fmt_plural,
3500 unsigned long n,...)
3506 vsnprintf(buf, sizeof(buf),
3507 dngettext(TEXTDOMAIN, fmt_singular, fmt_plural, n),
3511 PyErr_SetString(exc, buf);
3514 /* Emit a PG error or notice, together with any available info about
3515 * the current Python error, previously set by PLy_exception_set().
3516 * This should be used to propagate Python errors into PG. If fmt is
3517 * NULL, the Python error becomes the primary error message, otherwise
3518 * it becomes the detail.
3521 PLy_elog(int elevel, const char *fmt,...)
3525 StringInfoData emsg;
3527 xmsg = PLy_traceback(&xlevel);
3531 initStringInfo(&emsg);
3538 success = appendStringInfoVA(&emsg, dgettext(TEXTDOMAIN, fmt), ap);
3542 enlargeStringInfo(&emsg, emsg.maxlen);
3550 (errmsg("PL/Python: %s", emsg.data),
3551 (xmsg) ? errdetail("%s", xmsg) : 0));
3554 (errmsg("PL/Python: %s", xmsg)));
3573 PLy_traceback(int *xlevel)
3579 PyObject *e_module_o;
3580 char *e_type_s = NULL;
3581 char *e_module_s = NULL;
3582 PyObject *vob = NULL;
3584 StringInfoData xstr;
3587 * get the current exception
3589 PyErr_Fetch(&e, &v, &tb);
3592 * oops, no exception, return
3600 PyErr_NormalizeException(&e, &v, &tb);
3603 e_type_o = PyObject_GetAttrString(e, "__name__");
3604 e_module_o = PyObject_GetAttrString(e, "__module__");
3606 e_type_s = PyString_AsString(e_type_o);
3608 e_module_s = PyString_AsString(e_module_o);
3610 if (v && ((vob = PyObject_Str(v)) != NULL))
3611 vstr = PyString_AsString(vob);
3615 initStringInfo(&xstr);
3616 if (!e_type_s || !e_module_s)
3618 if (PyString_Check(e))
3619 /* deprecated string exceptions */
3620 appendStringInfoString(&xstr, PyString_AsString(e));
3622 /* shouldn't happen */
3623 appendStringInfoString(&xstr, "unrecognized exception");
3625 /* mimics behavior of traceback.format_exception_only */
3626 else if (strcmp(e_module_s, "builtins") == 0
3627 || strcmp(e_module_s, "__main__") == 0
3628 || strcmp(e_module_s, "exceptions") == 0)
3629 appendStringInfo(&xstr, "%s", e_type_s);
3631 appendStringInfo(&xstr, "%s.%s", e_module_s, e_type_s);
3632 appendStringInfo(&xstr, ": %s", vstr);
3634 Py_XDECREF(e_type_o);
3635 Py_XDECREF(e_module_o);
3640 * intuit an appropriate error level based on the exception type
3642 if (PLy_exc_error && PyErr_GivenExceptionMatches(e, PLy_exc_error))
3644 else if (PLy_exc_fatal && PyErr_GivenExceptionMatches(e, PLy_exc_fatal))
3653 /* python module code */
3655 /* some dumb utility functions */
3657 PLy_malloc(size_t bytes)
3659 void *ptr = malloc(bytes);
3663 (errcode(ERRCODE_OUT_OF_MEMORY),
3664 errmsg("out of memory")));
3669 PLy_malloc0(size_t bytes)
3671 void *ptr = PLy_malloc(bytes);
3673 MemSet(ptr, 0, bytes);
3678 PLy_strdup(const char *str)
3683 len = strlen(str) + 1;
3684 result = PLy_malloc(len);
3685 memcpy(result, str, len);
3690 /* define this away */
3698 * Convert a Python unicode object to a Python string/bytes object in
3699 * PostgreSQL server encoding. Reference ownership is passed to the
3703 PLyUnicode_Bytes(PyObject *unicode)
3706 const char *serverenc;
3709 * Python understands almost all PostgreSQL encoding names, but it doesn't
3712 if (GetDatabaseEncoding() == PG_SQL_ASCII)
3713 serverenc = "ascii";
3715 serverenc = GetDatabaseEncodingName();
3716 rv = PyUnicode_AsEncodedString(unicode, serverenc, "strict");
3718 PLy_elog(ERROR, "could not convert Python Unicode object to PostgreSQL server encoding");
3723 * Convert a Python unicode object to a C string in PostgreSQL server
3724 * encoding. No Python object reference is passed out of this
3725 * function. The result is palloc'ed.
3727 * Note that this function is disguised as PyString_AsString() when
3728 * using Python 3. That function retuns a pointer into the internal
3729 * memory of the argument, which isn't exactly the interface of this
3730 * function. But in either case you get a rather short-lived
3731 * reference that you ought to better leave alone.
3734 PLyUnicode_AsString(PyObject *unicode)
3736 PyObject *o = PLyUnicode_Bytes(unicode);
3737 char *rv = pstrdup(PyBytes_AsString(o));
3743 #if PY_MAJOR_VERSION >= 3
3745 * Convert a C string in the PostgreSQL server encoding to a Python
3746 * unicode object. Reference ownership is passed to the caller.
3749 PLyUnicode_FromString(const char *s)
3754 utf8string = (char *) pg_do_encoding_conversion((unsigned char *) s,
3756 GetDatabaseEncoding(),
3759 o = PyUnicode_FromString(utf8string);
3761 if (utf8string != s)
3767 #endif /* PY_MAJOR_VERSION >= 3 */