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)
74 #define PyInt_AsLong(x) PyLong_AsLong(x)
78 * PyVarObject_HEAD_INIT was added in Python 2.6. Its use is
79 * necessary to handle both Python 2 and 3. This replacement
80 * definition is for Python <=2.5
82 #ifndef PyVarObject_HEAD_INIT
83 #define PyVarObject_HEAD_INIT(type, size) \
84 PyObject_HEAD_INIT(type) size,
93 /* postgreSQL stuff */
94 #include "catalog/pg_proc.h"
95 #include "catalog/pg_type.h"
96 #include "commands/trigger.h"
97 #include "executor/spi.h"
100 #include "mb/pg_wchar.h"
101 #include "miscadmin.h"
102 #include "nodes/makefuncs.h"
103 #include "parser/parse_type.h"
104 #include "tcop/tcopprot.h"
105 #include "access/transam.h"
106 #include "access/xact.h"
107 #include "utils/builtins.h"
108 #include "utils/hsearch.h"
109 #include "utils/lsyscache.h"
110 #include "utils/memutils.h"
111 #include "utils/syscache.h"
112 #include "utils/typcache.h"
114 /* define our text domain for translations */
116 #define TEXTDOMAIN PG_TEXTDOMAIN("plpython")
123 /* convert Postgresql Datum or tuple into a PyObject.
124 * input to Python. Tuples are converted to dictionary
129 typedef PyObject *(*PLyDatumToObFunc) (struct PLyDatumToOb *, Datum);
131 typedef struct PLyDatumToOb
133 PLyDatumToObFunc func;
134 FmgrInfo typfunc; /* The type's output function */
135 Oid typoid; /* The OID of the type */
136 int32 typmod; /* The typmod of the type */
141 struct PLyDatumToOb *elm;
144 typedef struct PLyTupleToOb
150 typedef union PLyTypeInput
156 /* convert PyObject to a Postgresql Datum or tuple.
161 typedef Datum (*PLyObToDatumFunc) (struct PLyObToDatum *, int32 typmod,
164 typedef struct PLyObToDatum
166 PLyObToDatumFunc func;
167 FmgrInfo typfunc; /* The type's input function */
168 Oid typoid; /* The OID of the type */
169 int32 typmod; /* The typmod of the type */
174 struct PLyObToDatum *elm;
177 typedef struct PLyObToTuple
183 typedef union PLyTypeOutput
189 /* all we need to move Postgresql data to Python objects,
192 typedef struct PLyTypeInfo
198 * is_rowtype can be: -1 = not known yet (initial state); 0 = scalar
199 * datatype; 1 = rowtype; 2 = rowtype, but I/O functions not set up yet
202 /* used to check if the type has been modified */
204 TransactionId typrel_xmin;
205 ItemPointerData typrel_tid;
209 /* cached procedure data */
210 typedef struct PLyProcedure
212 char *proname; /* SQL name of procedure */
213 char *pyname; /* Python name of procedure */
214 TransactionId fn_xmin;
215 ItemPointerData fn_tid;
217 PLyTypeInfo result; /* also used to store info for trigger tuple
219 bool is_setof; /* true, if procedure returns result set */
220 PyObject *setof; /* contents of result set. */
221 char *src; /* textual procedure code, after mangling */
222 char **argnames; /* Argument names */
223 PLyTypeInfo args[FUNC_MAX_ARGS];
225 PyObject *code; /* compiled procedure code */
226 PyObject *statics; /* data saved across calls, local scope */
227 PyObject *globals; /* data saved across calls, global scope */
231 /* the procedure cache entry */
232 typedef struct PLyProcedureEntry
234 Oid fn_oid; /* hash key */
238 /* explicit subtransaction data */
239 typedef struct PLySubtransactionData
241 MemoryContext oldcontext;
242 ResourceOwner oldowner;
243 } PLySubtransactionData;
247 typedef struct PLyPlanObject
250 void *plan; /* return of an SPI_saveplan */
257 typedef struct PLyResultObject
260 /* HeapTuple *tuples; */
261 PyObject *nrows; /* number of rows returned by query */
262 PyObject *rows; /* data rows, or None if no data returned */
263 PyObject *status; /* query status, SPI_OK_*, or SPI_ERR_* */
266 typedef struct PLySubtransactionObject
271 } PLySubtransactionObject;
273 /* A list of all known exceptions, generated from backend/utils/errcodes.txt */
274 typedef struct ExceptionMap
281 static const ExceptionMap exception_map[] = {
282 #include "spiexceptions.h"
286 /* A hash table mapping sqlstates to exceptions, for speedy lookup */
287 static HTAB *PLy_spi_exceptions;
289 typedef struct PLyExceptionEntry
291 int sqlstate; /* hash key, must be first */
292 PyObject *exc; /* corresponding exception */
296 /* function declarations */
298 #if PY_MAJOR_VERSION >= 3
299 /* Use separate names to avoid clash in pg_pltemplate */
300 #define plpython_validator plpython3_validator
301 #define plpython_call_handler plpython3_call_handler
302 #define plpython_inline_handler plpython3_inline_handler
305 /* exported functions */
306 Datum plpython_validator(PG_FUNCTION_ARGS);
307 Datum plpython_call_handler(PG_FUNCTION_ARGS);
308 Datum plpython_inline_handler(PG_FUNCTION_ARGS);
311 PG_FUNCTION_INFO_V1(plpython_validator);
312 PG_FUNCTION_INFO_V1(plpython_call_handler);
313 PG_FUNCTION_INFO_V1(plpython_inline_handler);
315 /* most of the remaining of the declarations, all static */
318 * These should only be called once from _PG_init. Initialize the
319 * Python interpreter and global data.
321 static void PLy_init_interp(void);
322 static void PLy_init_plpy(void);
324 /* call PyErr_SetString with a vprint interface and translation support */
326 PLy_exception_set(PyObject *, const char *,...)
327 __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3)));
329 /* same, with pluralized message */
331 PLy_exception_set_plural(PyObject *, const char *, const char *,
333 __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 5)))
334 __attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 5)));
336 /* like PLy_exception_set, but conserve more fields from ErrorData */
337 static void PLy_spi_exception_set(PyObject *excclass, ErrorData *edata);
339 /* Get the innermost python procedure called from the backend */
340 static char *PLy_procedure_name(PLyProcedure *);
342 /* some utility functions */
344 PLy_elog(int, const char *,...)
345 __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3)));
346 static void PLy_get_spi_error_data(PyObject *exc, char **detail, char **hint, char **query, int *position);
347 static void PLy_traceback(char **, char **, int *);
349 static void *PLy_malloc(size_t);
350 static void *PLy_malloc0(size_t);
351 static char *PLy_strdup(const char *);
352 static void PLy_free(void *);
354 static PyObject *PLyUnicode_Bytes(PyObject *unicode);
355 static char *PLyUnicode_AsString(PyObject *unicode);
357 #if PY_MAJOR_VERSION >= 3
358 static PyObject *PLyUnicode_FromString(const char *s);
361 /* sub handlers for functions and triggers */
362 static Datum PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *);
363 static HeapTuple PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *);
365 static PyObject *PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *);
366 static void PLy_function_delete_args(PLyProcedure *);
367 static PyObject *PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *,
369 static HeapTuple PLy_modify_tuple(PLyProcedure *, PyObject *,
370 TriggerData *, HeapTuple);
372 static PyObject *PLy_procedure_call(PLyProcedure *, char *, PyObject *);
374 static PLyProcedure *PLy_procedure_get(Oid fn_oid, bool is_trigger);
376 static PLyProcedure *PLy_procedure_create(HeapTuple procTup,
377 Oid fn_oid, bool is_trigger);
379 static void PLy_procedure_compile(PLyProcedure *, const char *);
380 static char *PLy_procedure_munge_source(const char *, const char *);
381 static void PLy_procedure_delete(PLyProcedure *);
383 static void PLy_typeinfo_init(PLyTypeInfo *);
384 static void PLy_typeinfo_dealloc(PLyTypeInfo *);
385 static void PLy_output_datum_func(PLyTypeInfo *, HeapTuple);
386 static void PLy_output_datum_func2(PLyObToDatum *, HeapTuple);
387 static void PLy_input_datum_func(PLyTypeInfo *, Oid, HeapTuple);
388 static void PLy_input_datum_func2(PLyDatumToOb *, Oid, HeapTuple);
389 static void PLy_output_tuple_funcs(PLyTypeInfo *, TupleDesc);
390 static void PLy_input_tuple_funcs(PLyTypeInfo *, TupleDesc);
391 static void PLy_output_record_funcs(PLyTypeInfo *, TupleDesc);
393 /* conversion functions */
394 static PyObject *PLyBool_FromBool(PLyDatumToOb *arg, Datum d);
395 static PyObject *PLyFloat_FromFloat4(PLyDatumToOb *arg, Datum d);
396 static PyObject *PLyFloat_FromFloat8(PLyDatumToOb *arg, Datum d);
397 static PyObject *PLyFloat_FromNumeric(PLyDatumToOb *arg, Datum d);
398 static PyObject *PLyInt_FromInt16(PLyDatumToOb *arg, Datum d);
399 static PyObject *PLyInt_FromInt32(PLyDatumToOb *arg, Datum d);
400 static PyObject *PLyLong_FromInt64(PLyDatumToOb *arg, Datum d);
401 static PyObject *PLyBytes_FromBytea(PLyDatumToOb *arg, Datum d);
402 static PyObject *PLyString_FromDatum(PLyDatumToOb *arg, Datum d);
403 static PyObject *PLyList_FromArray(PLyDatumToOb *arg, Datum d);
405 static PyObject *PLyDict_FromTuple(PLyTypeInfo *, HeapTuple, TupleDesc);
407 static Datum PLyObject_ToBool(PLyObToDatum *, int32, PyObject *);
408 static Datum PLyObject_ToBytea(PLyObToDatum *, int32, PyObject *);
409 static Datum PLyObject_ToComposite(PLyObToDatum *, int32, PyObject *);
410 static Datum PLyObject_ToDatum(PLyObToDatum *, int32, PyObject *);
411 static Datum PLySequence_ToArray(PLyObToDatum *, int32, PyObject *);
413 static HeapTuple PLyObject_ToTuple(PLyTypeInfo *, TupleDesc, PyObject *);
414 static HeapTuple PLyMapping_ToTuple(PLyTypeInfo *, TupleDesc, PyObject *);
415 static HeapTuple PLySequence_ToTuple(PLyTypeInfo *, TupleDesc, PyObject *);
416 static HeapTuple PLyGenericObject_ToTuple(PLyTypeInfo *, TupleDesc, PyObject *);
419 * Currently active plpython function
421 static PLyProcedure *PLy_curr_procedure = NULL;
423 /* list of explicit subtransaction data */
424 static List *explicit_subtransactions = NIL;
426 static PyObject *PLy_interp_globals = NULL;
427 static PyObject *PLy_interp_safe_globals = NULL;
428 static HTAB *PLy_procedure_cache = NULL;
429 static HTAB *PLy_trigger_cache = NULL;
431 /* Python exceptions */
432 static PyObject *PLy_exc_error = NULL;
433 static PyObject *PLy_exc_fatal = NULL;
434 static PyObject *PLy_exc_spi_error = NULL;
436 /* some globals for the python module */
437 static char PLy_plan_doc[] = {
438 "Store a PostgreSQL plan"
441 static char PLy_result_doc[] = {
442 "Results of a PostgreSQL query"
445 static char PLy_subtransaction_doc[] = {
446 "PostgreSQL subtransaction context manager"
451 * the function definitions
455 * This routine is a crock, and so is everyplace that calls it. The problem
456 * is that the cached form of plpython functions/queries is allocated permanently
457 * (mostly via malloc()) and never released until backend exit. Subsidiary
458 * data structures such as fmgr info records therefore must live forever
459 * as well. A better implementation would store all this stuff in a per-
460 * function memory context that could be reclaimed at need. In the meantime,
461 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
462 * it might allocate, and whatever the eventual function might allocate using
463 * fn_mcxt, will live forever too.
466 perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
468 fmgr_info_cxt(functionId, finfo, TopMemoryContext);
472 plpython_error_callback(void *arg)
474 if (PLy_curr_procedure)
475 errcontext("PL/Python function \"%s\"",
476 PLy_procedure_name(PLy_curr_procedure));
480 plpython_inline_error_callback(void *arg)
482 errcontext("PL/Python anonymous code block");
486 plpython_trigger_error_callback(void *arg)
488 if (PLy_curr_procedure)
489 errcontext("while modifying trigger row");
493 plpython_return_error_callback(void *arg)
495 if (PLy_curr_procedure)
496 errcontext("while creating return value");
500 PLy_procedure_is_trigger(Form_pg_proc procStruct)
502 return (procStruct->prorettype == TRIGGEROID ||
503 (procStruct->prorettype == OPAQUEOID &&
504 procStruct->pronargs == 0));
508 plpython_validator(PG_FUNCTION_ARGS)
510 Oid funcoid = PG_GETARG_OID(0);
512 Form_pg_proc procStruct;
515 if (!check_function_bodies)
520 /* Get the new function's pg_proc entry */
521 tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
522 if (!HeapTupleIsValid(tuple))
523 elog(ERROR, "cache lookup failed for function %u", funcoid);
524 procStruct = (Form_pg_proc) GETSTRUCT(tuple);
526 is_trigger = PLy_procedure_is_trigger(procStruct);
528 ReleaseSysCache(tuple);
530 PLy_procedure_get(funcoid, is_trigger);
536 plpython_call_handler(PG_FUNCTION_ARGS)
539 PLyProcedure *save_curr_proc;
540 ErrorContextCallback plerrcontext;
542 if (SPI_connect() != SPI_OK_CONNECT)
543 elog(ERROR, "SPI_connect failed");
545 save_curr_proc = PLy_curr_procedure;
548 * Setup error traceback support for ereport()
550 plerrcontext.callback = plpython_error_callback;
551 plerrcontext.previous = error_context_stack;
552 error_context_stack = &plerrcontext;
558 if (CALLED_AS_TRIGGER(fcinfo))
562 proc = PLy_procedure_get(fcinfo->flinfo->fn_oid, true);
563 PLy_curr_procedure = proc;
564 trv = PLy_trigger_handler(fcinfo, proc);
565 retval = PointerGetDatum(trv);
569 proc = PLy_procedure_get(fcinfo->flinfo->fn_oid, false);
570 PLy_curr_procedure = proc;
571 retval = PLy_function_handler(fcinfo, proc);
576 PLy_curr_procedure = save_curr_proc;
582 /* Pop the error context stack */
583 error_context_stack = plerrcontext.previous;
585 PLy_curr_procedure = save_curr_proc;
591 plpython_inline_handler(PG_FUNCTION_ARGS)
593 InlineCodeBlock *codeblock = (InlineCodeBlock *) DatumGetPointer(PG_GETARG_DATUM(0));
594 FunctionCallInfoData fake_fcinfo;
596 PLyProcedure *save_curr_proc;
598 ErrorContextCallback plerrcontext;
600 if (SPI_connect() != SPI_OK_CONNECT)
601 elog(ERROR, "SPI_connect failed");
603 save_curr_proc = PLy_curr_procedure;
606 * Setup error traceback support for ereport()
608 plerrcontext.callback = plpython_inline_error_callback;
609 plerrcontext.previous = error_context_stack;
610 error_context_stack = &plerrcontext;
612 MemSet(&fake_fcinfo, 0, sizeof(fake_fcinfo));
613 MemSet(&flinfo, 0, sizeof(flinfo));
614 fake_fcinfo.flinfo = &flinfo;
615 flinfo.fn_oid = InvalidOid;
616 flinfo.fn_mcxt = CurrentMemoryContext;
618 MemSet(&proc, 0, sizeof(PLyProcedure));
619 proc.pyname = PLy_strdup("__plpython_inline_block");
620 proc.result.out.d.typoid = VOIDOID;
624 PLy_procedure_compile(&proc, codeblock->source_text);
625 PLy_curr_procedure = &proc;
626 PLy_function_handler(&fake_fcinfo, &proc);
630 PLy_procedure_delete(&proc);
631 PLy_curr_procedure = save_curr_proc;
637 PLy_procedure_delete(&proc);
639 /* Pop the error context stack */
640 error_context_stack = plerrcontext.previous;
642 PLy_curr_procedure = save_curr_proc;
647 /* trigger and function sub handlers
649 * the python function is expected to return Py_None if the tuple is
650 * acceptable and unmodified. Otherwise it should return a PyString
651 * object who's value is SKIP, or MODIFY. SKIP means don't perform
652 * this action. MODIFY means the tuple has been modified, so update
653 * tuple and perform action. SKIP and MODIFY assume the trigger fires
654 * BEFORE the event and is ROW level. postgres expects the function
655 * to take no arguments and return an argument of type trigger.
658 PLy_trigger_handler(FunctionCallInfo fcinfo, PLyProcedure *proc)
661 PyObject *volatile plargs = NULL;
662 PyObject *volatile plrv = NULL;
665 Assert(CALLED_AS_TRIGGER(fcinfo));
668 * Input/output conversion for trigger tuples. Use the result TypeInfo
669 * variable to store the tuple conversion info. We do this over again on
670 * each call to cover the possibility that the relation's tupdesc changed
671 * since the trigger was last called. PLy_input_tuple_funcs and
672 * PLy_output_tuple_funcs are responsible for not doing repetitive work.
674 tdata = (TriggerData *) fcinfo->context;
676 PLy_input_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
677 PLy_output_tuple_funcs(&(proc->result), tdata->tg_relation->rd_att);
681 plargs = PLy_trigger_build_args(fcinfo, proc, &rv);
682 plrv = PLy_procedure_call(proc, "TD", plargs);
684 Assert(plrv != NULL);
687 * Disconnect from SPI manager
689 if (SPI_finish() != SPI_OK_FINISH)
690 elog(ERROR, "SPI_finish failed");
693 * return of None means we're happy with the tuple
699 if (PyString_Check(plrv))
700 srv = PyString_AsString(plrv);
701 else if (PyUnicode_Check(plrv))
702 srv = PLyUnicode_AsString(plrv);
706 (errcode(ERRCODE_DATA_EXCEPTION),
707 errmsg("unexpected return value from trigger procedure"),
708 errdetail("Expected None or a string.")));
709 srv = NULL; /* keep compiler quiet */
712 if (pg_strcasecmp(srv, "SKIP") == 0)
714 else if (pg_strcasecmp(srv, "MODIFY") == 0)
716 TriggerData *tdata = (TriggerData *) fcinfo->context;
718 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event) ||
719 TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
720 rv = PLy_modify_tuple(proc, plargs, tdata, rv);
723 (errmsg("PL/Python trigger function returned \"MODIFY\" in a DELETE trigger -- ignored")));
725 else if (pg_strcasecmp(srv, "OK") != 0)
728 * accept "OK" as an alternative to None; otherwise, raise an
732 (errcode(ERRCODE_DATA_EXCEPTION),
733 errmsg("unexpected return value from trigger procedure"),
734 errdetail("Expected None, \"OK\", \"SKIP\", or \"MODIFY\".")));
754 PLy_modify_tuple(PLyProcedure *proc, PyObject *pltd, TriggerData *tdata,
757 PyObject *volatile plntup;
758 PyObject *volatile plkeys;
759 PyObject *volatile platt;
760 PyObject *volatile plval;
761 PyObject *volatile plstr;
767 int *volatile modattrs;
768 Datum *volatile modvalues;
769 char *volatile modnulls;
771 ErrorContextCallback plerrcontext;
773 plerrcontext.callback = plpython_trigger_error_callback;
774 plerrcontext.previous = error_context_stack;
775 error_context_stack = &plerrcontext;
777 plntup = plkeys = platt = plval = plstr = NULL;
784 if ((plntup = PyDict_GetItemString(pltd, "new")) == NULL)
786 (errmsg("TD[\"new\"] deleted, cannot modify row")));
787 if (!PyDict_Check(plntup))
789 (errmsg("TD[\"new\"] is not a dictionary")));
792 plkeys = PyDict_Keys(plntup);
793 natts = PyList_Size(plkeys);
795 modattrs = (int *) palloc(natts * sizeof(int));
796 modvalues = (Datum *) palloc(natts * sizeof(Datum));
797 modnulls = (char *) palloc(natts * sizeof(char));
799 tupdesc = tdata->tg_relation->rd_att;
801 for (i = 0; i < natts; i++)
805 platt = PyList_GetItem(plkeys, i);
806 if (PyString_Check(platt))
807 plattstr = PyString_AsString(platt);
808 else if (PyUnicode_Check(platt))
809 plattstr = PLyUnicode_AsString(platt);
813 (errmsg("TD[\"new\"] dictionary key at ordinal position %d is not a string", i)));
814 plattstr = NULL; /* keep compiler quiet */
816 attn = SPI_fnumber(tupdesc, plattstr);
817 if (attn == SPI_ERROR_NOATTRIBUTE)
819 (errmsg("key \"%s\" found in TD[\"new\"] does not exist as a column in the triggering row",
823 plval = PyDict_GetItem(plntup, platt);
825 elog(FATAL, "Python interpreter is probably corrupted");
831 if (tupdesc->attrs[atti]->attisdropped)
833 modvalues[i] = (Datum) 0;
836 else if (plval != Py_None)
838 PLyObToDatum *att = &proc->result.out.r.atts[atti];
840 modvalues[i] = (att->func) (att,
841 tupdesc->attrs[atti]->atttypmod,
848 InputFunctionCall(&proc->result.out.r.atts[atti].typfunc,
850 proc->result.out.r.atts[atti].typioparam,
851 tupdesc->attrs[atti]->atttypmod);
859 rtup = SPI_modifytuple(tdata->tg_relation, otup, natts,
860 modattrs, modvalues, modnulls);
862 elog(ERROR, "SPI_modifytuple failed: error %d", SPI_result);
889 error_context_stack = plerrcontext.previous;
895 PLy_trigger_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc, HeapTuple *rv)
897 TriggerData *tdata = (TriggerData *) fcinfo->context;
908 PyObject *volatile pltdata = NULL;
913 pltdata = PyDict_New();
915 PLy_elog(ERROR, "could not create new dictionary while building trigger arguments");
917 pltname = PyString_FromString(tdata->tg_trigger->tgname);
918 PyDict_SetItemString(pltdata, "name", pltname);
921 stroid = DatumGetCString(DirectFunctionCall1(oidout,
922 ObjectIdGetDatum(tdata->tg_relation->rd_id)));
923 pltrelid = PyString_FromString(stroid);
924 PyDict_SetItemString(pltdata, "relid", pltrelid);
928 stroid = SPI_getrelname(tdata->tg_relation);
929 plttablename = PyString_FromString(stroid);
930 PyDict_SetItemString(pltdata, "table_name", plttablename);
931 Py_DECREF(plttablename);
934 stroid = SPI_getnspname(tdata->tg_relation);
935 plttableschema = PyString_FromString(stroid);
936 PyDict_SetItemString(pltdata, "table_schema", plttableschema);
937 Py_DECREF(plttableschema);
940 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
941 pltwhen = PyString_FromString("BEFORE");
942 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
943 pltwhen = PyString_FromString("AFTER");
944 else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
945 pltwhen = PyString_FromString("INSTEAD OF");
948 elog(ERROR, "unrecognized WHEN tg_event: %u", tdata->tg_event);
949 pltwhen = NULL; /* keep compiler quiet */
951 PyDict_SetItemString(pltdata, "when", pltwhen);
954 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
956 pltlevel = PyString_FromString("ROW");
957 PyDict_SetItemString(pltdata, "level", pltlevel);
960 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
962 pltevent = PyString_FromString("INSERT");
964 PyDict_SetItemString(pltdata, "old", Py_None);
965 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
966 tdata->tg_relation->rd_att);
967 PyDict_SetItemString(pltdata, "new", pytnew);
969 *rv = tdata->tg_trigtuple;
971 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
973 pltevent = PyString_FromString("DELETE");
975 PyDict_SetItemString(pltdata, "new", Py_None);
976 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
977 tdata->tg_relation->rd_att);
978 PyDict_SetItemString(pltdata, "old", pytold);
980 *rv = tdata->tg_trigtuple;
982 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
984 pltevent = PyString_FromString("UPDATE");
986 pytnew = PLyDict_FromTuple(&(proc->result), tdata->tg_newtuple,
987 tdata->tg_relation->rd_att);
988 PyDict_SetItemString(pltdata, "new", pytnew);
990 pytold = PLyDict_FromTuple(&(proc->result), tdata->tg_trigtuple,
991 tdata->tg_relation->rd_att);
992 PyDict_SetItemString(pltdata, "old", pytold);
994 *rv = tdata->tg_newtuple;
998 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
999 pltevent = NULL; /* keep compiler quiet */
1002 PyDict_SetItemString(pltdata, "event", pltevent);
1003 Py_DECREF(pltevent);
1005 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
1007 pltlevel = PyString_FromString("STATEMENT");
1008 PyDict_SetItemString(pltdata, "level", pltlevel);
1009 Py_DECREF(pltlevel);
1011 PyDict_SetItemString(pltdata, "old", Py_None);
1012 PyDict_SetItemString(pltdata, "new", Py_None);
1015 if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
1016 pltevent = PyString_FromString("INSERT");
1017 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
1018 pltevent = PyString_FromString("DELETE");
1019 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
1020 pltevent = PyString_FromString("UPDATE");
1021 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
1022 pltevent = PyString_FromString("TRUNCATE");
1025 elog(ERROR, "unrecognized OP tg_event: %u", tdata->tg_event);
1026 pltevent = NULL; /* keep compiler quiet */
1029 PyDict_SetItemString(pltdata, "event", pltevent);
1030 Py_DECREF(pltevent);
1033 elog(ERROR, "unrecognized LEVEL tg_event: %u", tdata->tg_event);
1035 if (tdata->tg_trigger->tgnargs)
1043 pltargs = PyList_New(tdata->tg_trigger->tgnargs);
1044 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
1046 pltarg = PyString_FromString(tdata->tg_trigger->tgargs[i]);
1049 * stolen, don't Py_DECREF
1051 PyList_SetItem(pltargs, i, pltarg);
1059 PyDict_SetItemString(pltdata, "args", pltargs);
1064 Py_XDECREF(pltdata);
1074 /* function handler and friends */
1076 PLy_function_handler(FunctionCallInfo fcinfo, PLyProcedure *proc)
1079 PyObject *volatile plargs = NULL;
1080 PyObject *volatile plrv = NULL;
1081 ErrorContextCallback plerrcontext;
1085 if (!proc->is_setof || proc->setof == NULL)
1088 * Simple type returning function or first time for SETOF
1089 * function: actually execute the function.
1091 plargs = PLy_function_build_args(fcinfo, proc);
1092 plrv = PLy_procedure_call(proc, "args", plargs);
1093 if (!proc->is_setof)
1096 * SETOF function parameters will be deleted when last row is
1099 PLy_function_delete_args(proc);
1101 Assert(plrv != NULL);
1105 * If it returns a set, call the iterator to get the next return item.
1106 * We stay in the SPI context while doing this, because PyIter_Next()
1107 * calls back into Python code which might contain SPI calls.
1111 bool has_error = false;
1112 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1114 if (proc->setof == NULL)
1116 /* first time -- do checks and setup */
1117 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1118 (rsi->allowedModes & SFRM_ValuePerCall) == 0)
1121 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1122 errmsg("unsupported set function return mode"),
1123 errdetail("PL/Python set-returning functions only support returning only value per call.")));
1125 rsi->returnMode = SFRM_ValuePerCall;
1127 /* Make iterator out of returned object */
1128 proc->setof = PyObject_GetIter(plrv);
1132 if (proc->setof == NULL)
1134 (errcode(ERRCODE_DATATYPE_MISMATCH),
1135 errmsg("returned object cannot be iterated"),
1136 errdetail("PL/Python set-returning functions must return an iterable object.")));
1139 /* Fetch next from iterator */
1140 plrv = PyIter_Next(proc->setof);
1142 rsi->isDone = ExprMultipleResult;
1145 rsi->isDone = ExprEndResult;
1146 has_error = PyErr_Occurred() != NULL;
1149 if (rsi->isDone == ExprEndResult)
1151 /* Iterator is exhausted or error happened */
1152 Py_DECREF(proc->setof);
1158 PLy_function_delete_args(proc);
1161 PLy_elog(ERROR, "error fetching next item from iterator");
1163 /* Disconnect from the SPI manager before returning */
1164 if (SPI_finish() != SPI_OK_FINISH)
1165 elog(ERROR, "SPI_finish failed");
1167 fcinfo->isnull = true;
1168 return (Datum) NULL;
1173 * Disconnect from SPI manager and then create the return values datum
1174 * (if the input function does a palloc for it this must not be
1175 * allocated in the SPI memory context because SPI_finish would free
1178 if (SPI_finish() != SPI_OK_FINISH)
1179 elog(ERROR, "SPI_finish failed");
1181 plerrcontext.callback = plpython_return_error_callback;
1182 plerrcontext.previous = error_context_stack;
1183 error_context_stack = &plerrcontext;
1186 * If the function is declared to return void, the Python return value
1187 * must be None. For void-returning functions, we also treat a None
1188 * return value as a special "void datum" rather than NULL (as is the
1189 * case for non-void-returning functions).
1191 if (proc->result.out.d.typoid == VOIDOID)
1193 if (plrv != Py_None)
1195 (errcode(ERRCODE_DATATYPE_MISMATCH),
1196 errmsg("PL/Python function with return type \"void\" did not return None")));
1198 fcinfo->isnull = false;
1201 else if (plrv == Py_None)
1203 fcinfo->isnull = true;
1204 if (proc->result.is_rowtype < 1)
1205 rv = InputFunctionCall(&proc->result.out.d.typfunc,
1207 proc->result.out.d.typioparam,
1213 else if (proc->result.is_rowtype >= 1)
1216 HeapTuple tuple = NULL;
1218 /* make sure it's not an unnamed record */
1219 Assert((proc->result.out.d.typoid == RECORDOID &&
1220 proc->result.out.d.typmod != -1) ||
1221 (proc->result.out.d.typoid != RECORDOID &&
1222 proc->result.out.d.typmod == -1));
1224 desc = lookup_rowtype_tupdesc(proc->result.out.d.typoid,
1225 proc->result.out.d.typmod);
1227 tuple = PLyObject_ToTuple(&proc->result, desc, plrv);
1231 fcinfo->isnull = false;
1232 rv = HeapTupleGetDatum(tuple);
1236 fcinfo->isnull = true;
1242 fcinfo->isnull = false;
1243 rv = (proc->result.out.d.func) (&proc->result.out.d, -1, plrv);
1252 * If there was an error the iterator might have not been exhausted
1253 * yet. Set it to NULL so the next invocation of the function will
1254 * start the iteration again.
1256 Py_XDECREF(proc->setof);
1263 error_context_stack = plerrcontext.previous;
1272 * Abort lingering subtransactions that have been explicitly started
1273 * by plpy.subtransaction().start() and not properly closed.
1276 PLy_abort_open_subtransactions(int save_subxact_level)
1278 Assert(save_subxact_level >= 0);
1280 while (list_length(explicit_subtransactions) > save_subxact_level)
1282 PLySubtransactionData *subtransactiondata;
1284 Assert(explicit_subtransactions != NIL);
1287 (errmsg("forcibly aborting a subtransaction that has not been exited")));
1289 RollbackAndReleaseCurrentSubTransaction();
1291 SPI_restore_connection();
1293 subtransactiondata = (PLySubtransactionData *) linitial(explicit_subtransactions);
1294 explicit_subtransactions = list_delete_first(explicit_subtransactions);
1296 MemoryContextSwitchTo(subtransactiondata->oldcontext);
1297 CurrentResourceOwner = subtransactiondata->oldowner;
1298 PLy_free(subtransactiondata);
1303 PLy_procedure_call(PLyProcedure *proc, char *kargs, PyObject *vargs)
1306 int volatile save_subxact_level = list_length(explicit_subtransactions);
1308 PyDict_SetItemString(proc->globals, kargs, vargs);
1312 #if PY_VERSION_HEX >= 0x03020000
1313 rv = PyEval_EvalCode(proc->code,
1314 proc->globals, proc->globals);
1316 rv = PyEval_EvalCode((PyCodeObject *) proc->code,
1317 proc->globals, proc->globals);
1321 * Since plpy will only let you close subtransactions that you
1322 * started, you cannot *unnest* subtransactions, only *nest* them
1325 Assert(list_length(explicit_subtransactions) >= save_subxact_level);
1329 PLy_abort_open_subtransactions(save_subxact_level);
1334 PLy_abort_open_subtransactions(save_subxact_level);
1336 /* If the Python code returned an error, propagate it */
1338 PLy_elog(ERROR, NULL);
1344 PLy_function_build_args(FunctionCallInfo fcinfo, PLyProcedure *proc)
1346 PyObject *volatile arg = NULL;
1347 PyObject *volatile args = NULL;
1352 args = PyList_New(proc->nargs);
1353 for (i = 0; i < proc->nargs; i++)
1355 if (proc->args[i].is_rowtype > 0)
1357 if (fcinfo->argnull[i])
1365 HeapTupleData tmptup;
1367 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
1368 /* Extract rowtype info and find a tupdesc */
1369 tupType = HeapTupleHeaderGetTypeId(td);
1370 tupTypmod = HeapTupleHeaderGetTypMod(td);
1371 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1373 /* Set up I/O funcs if not done yet */
1374 if (proc->args[i].is_rowtype != 1)
1375 PLy_input_tuple_funcs(&(proc->args[i]), tupdesc);
1377 /* Build a temporary HeapTuple control structure */
1378 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1381 arg = PLyDict_FromTuple(&(proc->args[i]), &tmptup, tupdesc);
1382 ReleaseTupleDesc(tupdesc);
1387 if (fcinfo->argnull[i])
1391 arg = (proc->args[i].in.d.func) (&(proc->args[i].in.d),
1402 if (PyList_SetItem(args, i, arg) == -1)
1403 PLy_elog(ERROR, "PyList_SetItem() failed, while setting up arguments");
1405 if (proc->argnames && proc->argnames[i] &&
1406 PyDict_SetItemString(proc->globals, proc->argnames[i], arg) == -1)
1407 PLy_elog(ERROR, "PyDict_SetItemString() failed, while setting up arguments");
1411 /* Set up output conversion for functions returning RECORD */
1412 if (proc->result.out.d.typoid == RECORDOID)
1416 if (get_call_result_type(fcinfo, NULL, &desc) != TYPEFUNC_COMPOSITE)
1418 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1419 errmsg("function returning record called in context "
1420 "that cannot accept type record")));
1422 /* cache the output conversion functions */
1423 PLy_output_record_funcs(&(proc->result), desc);
1440 PLy_function_delete_args(PLyProcedure *proc)
1444 if (!proc->argnames)
1447 for (i = 0; i < proc->nargs; i++)
1448 if (proc->argnames[i])
1449 PyDict_DelItemString(proc->globals, proc->argnames[i]);
1453 * Decide whether a cached PLyProcedure struct is still valid
1456 PLy_procedure_valid(PLyProcedure *proc, HeapTuple procTup)
1461 Assert(proc != NULL);
1463 /* If the pg_proc tuple has changed, it's not valid */
1464 if (!(proc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&
1465 ItemPointerEquals(&proc->fn_tid, &procTup->t_self)))
1469 /* If there are composite input arguments, they might have changed */
1470 for (i = 0; i < proc->nargs; i++)
1475 /* Short-circuit on first changed argument */
1479 /* Only check input arguments that are composite */
1480 if (proc->args[i].is_rowtype != 1)
1483 Assert(OidIsValid(proc->args[i].typ_relid));
1484 Assert(TransactionIdIsValid(proc->args[i].typrel_xmin));
1485 Assert(ItemPointerIsValid(&proc->args[i].typrel_tid));
1487 /* Get the pg_class tuple for the argument type */
1488 relid = proc->args[i].typ_relid;
1489 relTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1490 if (!HeapTupleIsValid(relTup))
1491 elog(ERROR, "cache lookup failed for relation %u", relid);
1493 /* If it has changed, the function is not valid */
1494 if (!(proc->args[i].typrel_xmin == HeapTupleHeaderGetXmin(relTup->t_data) &&
1495 ItemPointerEquals(&proc->args[i].typrel_tid, &relTup->t_self)))
1498 ReleaseSysCache(relTup);
1506 * PLyProcedure functions
1509 /* PLy_procedure_get: returns a cached PLyProcedure, or creates, stores and
1510 * returns a new PLyProcedure. fcinfo is the call info, tgreloid is the
1511 * relation OID when calling a trigger, or InvalidOid (zero) for ordinary
1514 static PLyProcedure *
1515 PLy_procedure_get(Oid fn_oid, bool is_trigger)
1518 PLyProcedureEntry *volatile entry;
1521 procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
1522 if (!HeapTupleIsValid(procTup))
1523 elog(ERROR, "cache lookup failed for function %u", fn_oid);
1525 /* Look for the function in the corresponding cache */
1527 entry = hash_search(PLy_trigger_cache,
1528 &fn_oid, HASH_ENTER, &found);
1530 entry = hash_search(PLy_procedure_cache,
1531 &fn_oid, HASH_ENTER, &found);
1537 /* Haven't found it, create a new cache entry */
1538 entry->proc = PLy_procedure_create(procTup, fn_oid, is_trigger);
1540 else if (!PLy_procedure_valid(entry->proc, procTup))
1542 /* Found it, but it's invalid, free and reuse the cache entry */
1543 PLy_procedure_delete(entry->proc);
1544 PLy_free(entry->proc);
1545 entry->proc = PLy_procedure_create(procTup, fn_oid, is_trigger);
1547 /* Found it and it's valid, it's fine to use it */
1551 /* Do not leave an uninitialised entry in the cache */
1553 hash_search(PLy_trigger_cache,
1554 &fn_oid, HASH_REMOVE, NULL);
1556 hash_search(PLy_procedure_cache,
1557 &fn_oid, HASH_REMOVE, NULL);
1562 ReleaseSysCache(procTup);
1568 * Create a new PLyProcedure structure
1570 static PLyProcedure *
1571 PLy_procedure_create(HeapTuple procTup, Oid fn_oid, bool is_trigger)
1573 char procName[NAMEDATALEN + 256];
1574 Form_pg_proc procStruct;
1575 PLyProcedure *volatile proc;
1576 char *volatile procSource = NULL;
1582 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1583 rv = snprintf(procName, sizeof(procName),
1584 "__plpython_procedure_%s_%u",
1585 NameStr(procStruct->proname),
1587 if (rv >= sizeof(procName) || rv < 0)
1588 elog(ERROR, "procedure name would overrun buffer");
1590 proc = PLy_malloc(sizeof(PLyProcedure));
1591 proc->proname = PLy_strdup(NameStr(procStruct->proname));
1592 proc->pyname = PLy_strdup(procName);
1593 proc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
1594 proc->fn_tid = procTup->t_self;
1595 /* Remember if function is STABLE/IMMUTABLE */
1597 (procStruct->provolatile != PROVOLATILE_VOLATILE);
1598 PLy_typeinfo_init(&proc->result);
1599 for (i = 0; i < FUNC_MAX_ARGS; i++)
1600 PLy_typeinfo_init(&proc->args[i]);
1602 proc->code = proc->statics = NULL;
1603 proc->globals = NULL;
1604 proc->is_setof = procStruct->proretset;
1607 proc->argnames = NULL;
1612 * get information required for output conversion of the return value,
1613 * but only if this isn't a trigger.
1617 HeapTuple rvTypeTup;
1618 Form_pg_type rvTypeStruct;
1620 rvTypeTup = SearchSysCache1(TYPEOID,
1621 ObjectIdGetDatum(procStruct->prorettype));
1622 if (!HeapTupleIsValid(rvTypeTup))
1623 elog(ERROR, "cache lookup failed for type %u",
1624 procStruct->prorettype);
1625 rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
1627 /* Disallow pseudotype result, except for void or record */
1628 if (rvTypeStruct->typtype == TYPTYPE_PSEUDO)
1630 if (procStruct->prorettype == TRIGGEROID)
1632 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1633 errmsg("trigger functions can only be called as triggers")));
1634 else if (procStruct->prorettype != VOIDOID &&
1635 procStruct->prorettype != RECORDOID)
1637 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1638 errmsg("PL/Python functions cannot return type %s",
1639 format_type_be(procStruct->prorettype))));
1642 if (rvTypeStruct->typtype == TYPTYPE_COMPOSITE ||
1643 procStruct->prorettype == RECORDOID)
1646 * Tuple: set up later, during first call to
1647 * PLy_function_handler
1649 proc->result.out.d.typoid = procStruct->prorettype;
1650 proc->result.out.d.typmod = -1;
1651 proc->result.is_rowtype = 2;
1655 /* do the real work */
1656 PLy_output_datum_func(&proc->result, rvTypeTup);
1659 ReleaseSysCache(rvTypeTup);
1663 * Now get information required for input conversion of the
1664 * procedure's arguments. Note that we ignore output arguments here
1665 * --- since we don't support returning record, and that was already
1666 * checked above, there's no need to worry about multiple output
1669 if (procStruct->pronargs)
1678 /* extract argument type info from the pg_proc tuple */
1679 total = get_func_arg_info(procTup, &types, &names, &modes);
1681 /* count number of in+inout args into proc->nargs */
1683 proc->nargs = total;
1686 /* proc->nargs was initialized to 0 above */
1687 for (i = 0; i < total; i++)
1689 if (modes[i] != PROARGMODE_OUT &&
1690 modes[i] != PROARGMODE_TABLE)
1695 proc->argnames = (char **) PLy_malloc0(sizeof(char *) * proc->nargs);
1696 for (i = pos = 0; i < total; i++)
1698 HeapTuple argTypeTup;
1699 Form_pg_type argTypeStruct;
1702 (modes[i] == PROARGMODE_OUT ||
1703 modes[i] == PROARGMODE_TABLE))
1704 continue; /* skip OUT arguments */
1706 Assert(types[i] == procStruct->proargtypes.values[pos]);
1708 argTypeTup = SearchSysCache1(TYPEOID,
1709 ObjectIdGetDatum(types[i]));
1710 if (!HeapTupleIsValid(argTypeTup))
1711 elog(ERROR, "cache lookup failed for type %u", types[i]);
1712 argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
1714 /* check argument type is OK, set up I/O function info */
1715 switch (argTypeStruct->typtype)
1717 case TYPTYPE_PSEUDO:
1718 /* Disallow pseudotype argument */
1720 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1721 errmsg("PL/Python functions cannot accept type %s",
1722 format_type_be(types[i]))));
1724 case TYPTYPE_COMPOSITE:
1725 /* we'll set IO funcs at first call */
1726 proc->args[pos].is_rowtype = 2;
1729 PLy_input_datum_func(&(proc->args[pos]),
1735 /* get argument name */
1736 proc->argnames[pos] = names ? PLy_strdup(names[i]) : NULL;
1738 ReleaseSysCache(argTypeTup);
1745 * get the text of the function.
1747 prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
1748 Anum_pg_proc_prosrc, &isnull);
1750 elog(ERROR, "null prosrc");
1751 procSource = TextDatumGetCString(prosrcdatum);
1753 PLy_procedure_compile(proc, procSource);
1760 PLy_procedure_delete(proc);
1772 * Insert the procedure into the Python interpreter
1775 PLy_procedure_compile(PLyProcedure *proc, const char *src)
1777 PyObject *crv = NULL;
1780 proc->globals = PyDict_Copy(PLy_interp_globals);
1783 * SD is private preserved data between calls. GD is global data shared by
1786 proc->statics = PyDict_New();
1787 PyDict_SetItemString(proc->globals, "SD", proc->statics);
1790 * insert the function code into the interpreter
1792 msrc = PLy_procedure_munge_source(proc->pyname, src);
1793 /* Save the mangled source for later inclusion in tracebacks */
1794 proc->src = PLy_strdup(msrc);
1795 crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
1801 char call[NAMEDATALEN + 256];
1806 * compile a call to the function
1808 clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
1809 if (clen < 0 || clen >= sizeof(call))
1810 elog(ERROR, "string would overflow buffer");
1811 proc->code = Py_CompileString(call, "<string>", Py_eval_input);
1812 if (proc->code != NULL)
1817 PLy_elog(ERROR, "could not compile PL/Python function \"%s\"",
1820 PLy_elog(ERROR, "could not compile anonymous PL/Python code block");
1824 PLy_procedure_munge_source(const char *name, const char *src)
1833 * room for function source and the def statement
1835 mlen = (strlen(src) * 2) + strlen(name) + 16;
1838 plen = snprintf(mrc, mlen, "def %s():\n\t", name);
1839 Assert(plen >= 0 && plen < mlen);
1846 if (*sp == '\r' && *(sp + 1) == '\n')
1849 if (*sp == '\n' || *sp == '\r')
1862 if (mp > (mrc + mlen))
1863 elog(FATAL, "buffer overrun in PLy_munge_source");
1869 PLy_procedure_delete(PLyProcedure *proc)
1873 Py_XDECREF(proc->code);
1874 Py_XDECREF(proc->statics);
1875 Py_XDECREF(proc->globals);
1877 PLy_free(proc->proname);
1879 PLy_free(proc->pyname);
1880 for (i = 0; i < proc->nargs; i++)
1882 if (proc->args[i].is_rowtype == 1)
1884 if (proc->args[i].in.r.atts)
1885 PLy_free(proc->args[i].in.r.atts);
1886 if (proc->args[i].out.r.atts)
1887 PLy_free(proc->args[i].out.r.atts);
1889 if (proc->argnames && proc->argnames[i])
1890 PLy_free(proc->argnames[i]);
1893 PLy_free(proc->src);
1895 PLy_free(proc->argnames);
1899 * Conversion functions. Remember output from Python is input to
1900 * PostgreSQL, and vice versa.
1903 PLy_input_tuple_funcs(PLyTypeInfo *arg, TupleDesc desc)
1907 if (arg->is_rowtype == 0)
1908 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
1909 arg->is_rowtype = 1;
1911 if (arg->in.r.natts != desc->natts)
1914 PLy_free(arg->in.r.atts);
1915 arg->in.r.natts = desc->natts;
1916 arg->in.r.atts = PLy_malloc0(desc->natts * sizeof(PLyDatumToOb));
1919 /* Can this be an unnamed tuple? If not, then an Assert would be enough */
1920 if (desc->tdtypmod != -1)
1921 elog(ERROR, "received unnamed record type as input");
1923 Assert(OidIsValid(desc->tdtypeid));
1926 * RECORDOID means we got called to create input functions for a tuple
1927 * fetched by plpy.execute or for an anonymous record type
1929 if (desc->tdtypeid != RECORDOID && !TransactionIdIsValid(arg->typrel_xmin))
1933 /* Get the pg_class tuple corresponding to the type of the input */
1934 arg->typ_relid = typeidTypeRelid(desc->tdtypeid);
1935 relTup = SearchSysCache1(RELOID, ObjectIdGetDatum(arg->typ_relid));
1936 if (!HeapTupleIsValid(relTup))
1937 elog(ERROR, "cache lookup failed for relation %u", arg->typ_relid);
1939 /* Extract the XMIN value to later use it in PLy_procedure_valid */
1940 arg->typrel_xmin = HeapTupleHeaderGetXmin(relTup->t_data);
1941 arg->typrel_tid = relTup->t_self;
1943 ReleaseSysCache(relTup);
1946 for (i = 0; i < desc->natts; i++)
1950 if (desc->attrs[i]->attisdropped)
1953 if (arg->in.r.atts[i].typoid == desc->attrs[i]->atttypid)
1954 continue; /* already set up this entry */
1956 typeTup = SearchSysCache1(TYPEOID,
1957 ObjectIdGetDatum(desc->attrs[i]->atttypid));
1958 if (!HeapTupleIsValid(typeTup))
1959 elog(ERROR, "cache lookup failed for type %u",
1960 desc->attrs[i]->atttypid);
1962 PLy_input_datum_func2(&(arg->in.r.atts[i]),
1963 desc->attrs[i]->atttypid,
1966 ReleaseSysCache(typeTup);
1971 PLy_output_record_funcs(PLyTypeInfo *arg, TupleDesc desc)
1974 * If the output record functions are already set, we just have to check
1975 * if the record descriptor has not changed
1977 if ((arg->is_rowtype == 1) &&
1978 (arg->out.d.typmod != -1) &&
1979 (arg->out.d.typmod == desc->tdtypmod))
1982 /* bless the record to make it known to the typcache lookup code */
1983 BlessTupleDesc(desc);
1984 /* save the freshly generated typmod */
1985 arg->out.d.typmod = desc->tdtypmod;
1986 /* proceed with normal I/O function caching */
1987 PLy_output_tuple_funcs(arg, desc);
1990 * it should change is_rowtype to 1, so we won't go through this again
1991 * unless the the output record description changes
1993 Assert(arg->is_rowtype == 1);
1997 PLy_output_tuple_funcs(PLyTypeInfo *arg, TupleDesc desc)
2001 if (arg->is_rowtype == 0)
2002 elog(ERROR, "PLyTypeInfo struct is initialized for a Datum");
2003 arg->is_rowtype = 1;
2005 if (arg->out.r.natts != desc->natts)
2007 if (arg->out.r.atts)
2008 PLy_free(arg->out.r.atts);
2009 arg->out.r.natts = desc->natts;
2010 arg->out.r.atts = PLy_malloc0(desc->natts * sizeof(PLyDatumToOb));
2013 for (i = 0; i < desc->natts; i++)
2017 if (desc->attrs[i]->attisdropped)
2020 if (arg->out.r.atts[i].typoid == desc->attrs[i]->atttypid)
2021 continue; /* already set up this entry */
2023 typeTup = SearchSysCache1(TYPEOID,
2024 ObjectIdGetDatum(desc->attrs[i]->atttypid));
2025 if (!HeapTupleIsValid(typeTup))
2026 elog(ERROR, "cache lookup failed for type %u",
2027 desc->attrs[i]->atttypid);
2029 PLy_output_datum_func2(&(arg->out.r.atts[i]), typeTup);
2031 ReleaseSysCache(typeTup);
2036 PLy_output_datum_func(PLyTypeInfo *arg, HeapTuple typeTup)
2038 if (arg->is_rowtype > 0)
2039 elog(ERROR, "PLyTypeInfo struct is initialized for a Tuple");
2040 arg->is_rowtype = 0;
2041 PLy_output_datum_func2(&(arg->out.d), typeTup);
2045 PLy_output_datum_func2(PLyObToDatum *arg, HeapTuple typeTup)
2047 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2050 perm_fmgr_info(typeStruct->typinput, &arg->typfunc);
2051 arg->typoid = HeapTupleGetOid(typeTup);
2053 arg->typioparam = getTypeIOParam(typeTup);
2054 arg->typbyval = typeStruct->typbyval;
2056 element_type = get_element_type(arg->typoid);
2059 * Select a conversion function to convert Python objects to PostgreSQL
2060 * datums. Most data types can go through the generic function.
2062 switch (getBaseType(element_type ? element_type : arg->typoid))
2065 arg->func = PLyObject_ToBool;
2068 arg->func = PLyObject_ToBytea;
2071 arg->func = PLyObject_ToDatum;
2075 /* Composite types need their own input routine, though */
2076 if (typeStruct->typtype == TYPTYPE_COMPOSITE)
2078 arg->func = PLyObject_ToComposite;
2086 if (type_is_rowtype(element_type))
2088 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2089 errmsg("PL/Python functions cannot return type %s",
2090 format_type_be(arg->typoid)),
2091 errdetail("PL/Python does not support conversion to arrays of row types.")));
2093 arg->elm = PLy_malloc0(sizeof(*arg->elm));
2094 arg->elm->func = arg->func;
2095 arg->func = PLySequence_ToArray;
2097 arg->elm->typoid = element_type;
2098 arg->elm->typmod = -1;
2099 get_type_io_data(element_type, IOFunc_input,
2100 &arg->elm->typlen, &arg->elm->typbyval, &arg->elm->typalign, &dummy_delim,
2101 &arg->elm->typioparam, &funcid);
2102 perm_fmgr_info(funcid, &arg->elm->typfunc);
2107 PLy_input_datum_func(PLyTypeInfo *arg, Oid typeOid, HeapTuple typeTup)
2109 if (arg->is_rowtype > 0)
2110 elog(ERROR, "PLyTypeInfo struct is initialized for Tuple");
2111 arg->is_rowtype = 0;
2112 PLy_input_datum_func2(&(arg->in.d), typeOid, typeTup);
2116 PLy_input_datum_func2(PLyDatumToOb *arg, Oid typeOid, HeapTuple typeTup)
2118 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2119 Oid element_type = get_element_type(typeOid);
2121 /* Get the type's conversion information */
2122 perm_fmgr_info(typeStruct->typoutput, &arg->typfunc);
2123 arg->typoid = HeapTupleGetOid(typeTup);
2125 arg->typioparam = getTypeIOParam(typeTup);
2126 arg->typbyval = typeStruct->typbyval;
2127 arg->typlen = typeStruct->typlen;
2128 arg->typalign = typeStruct->typalign;
2130 /* Determine which kind of Python object we will convert to */
2131 switch (getBaseType(element_type ? element_type : typeOid))
2134 arg->func = PLyBool_FromBool;
2137 arg->func = PLyFloat_FromFloat4;
2140 arg->func = PLyFloat_FromFloat8;
2143 arg->func = PLyFloat_FromNumeric;
2146 arg->func = PLyInt_FromInt16;
2149 arg->func = PLyInt_FromInt32;
2152 arg->func = PLyLong_FromInt64;
2155 arg->func = PLyBytes_FromBytea;
2158 arg->func = PLyString_FromDatum;
2167 arg->elm = PLy_malloc0(sizeof(*arg->elm));
2168 arg->elm->func = arg->func;
2169 arg->func = PLyList_FromArray;
2170 arg->elm->typoid = element_type;
2171 arg->elm->typmod = -1;
2172 get_type_io_data(element_type, IOFunc_output,
2173 &arg->elm->typlen, &arg->elm->typbyval, &arg->elm->typalign, &dummy_delim,
2174 &arg->elm->typioparam, &funcid);
2175 perm_fmgr_info(funcid, &arg->elm->typfunc);
2180 PLy_typeinfo_init(PLyTypeInfo *arg)
2182 arg->is_rowtype = -1;
2183 arg->in.r.natts = arg->out.r.natts = 0;
2184 arg->in.r.atts = NULL;
2185 arg->out.r.atts = NULL;
2186 arg->typ_relid = InvalidOid;
2187 arg->typrel_xmin = InvalidTransactionId;
2188 ItemPointerSetInvalid(&arg->typrel_tid);
2192 PLy_typeinfo_dealloc(PLyTypeInfo *arg)
2194 if (arg->is_rowtype == 1)
2197 PLy_free(arg->in.r.atts);
2198 if (arg->out.r.atts)
2199 PLy_free(arg->out.r.atts);
2204 PLyBool_FromBool(PLyDatumToOb *arg, Datum d)
2207 * We would like to use Py_RETURN_TRUE and Py_RETURN_FALSE here for
2208 * generating SQL from trigger functions, but those are only supported in
2209 * Python >= 2.3, and we support older versions.
2210 * http://docs.python.org/api/boolObjects.html
2212 if (DatumGetBool(d))
2213 return PyBool_FromLong(1);
2214 return PyBool_FromLong(0);
2218 PLyFloat_FromFloat4(PLyDatumToOb *arg, Datum d)
2220 return PyFloat_FromDouble(DatumGetFloat4(d));
2224 PLyFloat_FromFloat8(PLyDatumToOb *arg, Datum d)
2226 return PyFloat_FromDouble(DatumGetFloat8(d));
2230 PLyFloat_FromNumeric(PLyDatumToOb *arg, Datum d)
2233 * Numeric is cast to a PyFloat: This results in a loss of precision Would
2234 * it be better to cast to PyString?
2236 Datum f = DirectFunctionCall1(numeric_float8, d);
2237 double x = DatumGetFloat8(f);
2239 return PyFloat_FromDouble(x);
2243 PLyInt_FromInt16(PLyDatumToOb *arg, Datum d)
2245 return PyInt_FromLong(DatumGetInt16(d));
2249 PLyInt_FromInt32(PLyDatumToOb *arg, Datum d)
2251 return PyInt_FromLong(DatumGetInt32(d));
2255 PLyLong_FromInt64(PLyDatumToOb *arg, Datum d)
2257 /* on 32 bit platforms "long" may be too small */
2258 if (sizeof(int64) > sizeof(long))
2259 return PyLong_FromLongLong(DatumGetInt64(d));
2261 return PyLong_FromLong(DatumGetInt64(d));
2265 PLyBytes_FromBytea(PLyDatumToOb *arg, Datum d)
2267 text *txt = DatumGetByteaP(d);
2268 char *str = VARDATA(txt);
2269 size_t size = VARSIZE(txt) - VARHDRSZ;
2271 return PyBytes_FromStringAndSize(str, size);
2275 PLyString_FromDatum(PLyDatumToOb *arg, Datum d)
2277 char *x = OutputFunctionCall(&arg->typfunc, d);
2278 PyObject *r = PyString_FromString(x);
2285 PLyList_FromArray(PLyDatumToOb *arg, Datum d)
2287 ArrayType *array = DatumGetArrayTypeP(d);
2288 PLyDatumToOb *elm = arg->elm;
2294 if (ARR_NDIM(array) == 0)
2295 return PyList_New(0);
2297 if (ARR_NDIM(array) != 1)
2299 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2300 errmsg("cannot convert multidimensional array to Python list"),
2301 errdetail("PL/Python only supports one-dimensional arrays.")));
2303 length = ARR_DIMS(array)[0];
2304 lbound = ARR_LBOUND(array)[0];
2305 list = PyList_New(length);
2307 for (i = 0; i < length; i++)
2313 offset = lbound + i;
2314 elem = array_ref(array, 1, &offset, arg->typlen,
2315 elm->typlen, elm->typbyval, elm->typalign,
2320 PyList_SET_ITEM(list, i, Py_None);
2323 PyList_SET_ITEM(list, i, elm->func(elm, elem));
2330 PLyDict_FromTuple(PLyTypeInfo *info, HeapTuple tuple, TupleDesc desc)
2332 PyObject *volatile dict;
2335 if (info->is_rowtype != 1)
2336 elog(ERROR, "PLyTypeInfo structure describes a datum");
2338 dict = PyDict_New();
2340 PLy_elog(ERROR, "could not create new dictionary");
2344 for (i = 0; i < info->in.r.natts; i++)
2351 if (desc->attrs[i]->attisdropped)
2354 key = NameStr(desc->attrs[i]->attname);
2355 vattr = heap_getattr(tuple, (i + 1), desc, &is_null);
2357 if (is_null || info->in.r.atts[i].func == NULL)
2358 PyDict_SetItemString(dict, key, Py_None);
2361 value = (info->in.r.atts[i].func) (&info->in.r.atts[i], vattr);
2362 PyDict_SetItemString(dict, key, value);
2378 * Convert a Python object to a PostgreSQL tuple, using all supported
2379 * conversion methods: tuple as a sequence, as a mapping or as an object that
2380 * has __getattr__ support.
2383 PLyObject_ToTuple(PLyTypeInfo *info, TupleDesc desc, PyObject *plrv)
2387 if (PySequence_Check(plrv))
2388 /* composite type as sequence (tuple, list etc) */
2389 tuple = PLySequence_ToTuple(info, desc, plrv);
2390 else if (PyMapping_Check(plrv))
2391 /* composite type as mapping (currently only dict) */
2392 tuple = PLyMapping_ToTuple(info, desc, plrv);
2394 /* returned as smth, must provide method __getattr__(name) */
2395 tuple = PLyGenericObject_ToTuple(info, desc, plrv);
2401 * Convert a Python object to a PostgreSQL bool datum. This can't go
2402 * through the generic conversion function, because Python attaches a
2403 * Boolean value to everything, more things than the PostgreSQL bool
2407 PLyObject_ToBool(PLyObToDatum *arg, int32 typmod, PyObject *plrv)
2411 Assert(plrv != Py_None);
2412 rv = BoolGetDatum(PyObject_IsTrue(plrv));
2414 if (get_typtype(arg->typoid) == TYPTYPE_DOMAIN)
2415 domain_check(rv, false, arg->typoid, &arg->typfunc.fn_extra, arg->typfunc.fn_mcxt);
2421 * Convert a Python object to a PostgreSQL bytea datum. This doesn't
2422 * go through the generic conversion function to circumvent problems
2423 * with embedded nulls. And it's faster this way.
2426 PLyObject_ToBytea(PLyObToDatum *arg, int32 typmod, PyObject *plrv)
2428 PyObject *volatile plrv_so = NULL;
2431 Assert(plrv != Py_None);
2433 plrv_so = PyObject_Bytes(plrv);
2435 PLy_elog(ERROR, "could not create bytes representation of Python object");
2439 char *plrv_sc = PyBytes_AsString(plrv_so);
2440 size_t len = PyBytes_Size(plrv_so);
2441 size_t size = len + VARHDRSZ;
2442 bytea *result = palloc(size);
2444 SET_VARSIZE(result, size);
2445 memcpy(VARDATA(result), plrv_sc, len);
2446 rv = PointerGetDatum(result);
2450 Py_XDECREF(plrv_so);
2455 Py_XDECREF(plrv_so);
2457 if (get_typtype(arg->typoid) == TYPTYPE_DOMAIN)
2458 domain_check(rv, false, arg->typoid, &arg->typfunc.fn_extra, arg->typfunc.fn_mcxt);
2465 * Convert a Python object to a composite type. First look up the type's
2466 * description, then route the Python object through the conversion function
2467 * for obtaining PostgreSQL tuples.
2470 PLyObject_ToComposite(PLyObToDatum *arg, int32 typmod, PyObject *plrv)
2472 HeapTuple tuple = NULL;
2478 elog(ERROR, "received unnamed record type as input");
2480 /* Create a dummy PLyTypeInfo */
2481 MemSet(&info, 0, sizeof(PLyTypeInfo));
2482 PLy_typeinfo_init(&info);
2483 /* Mark it as needing output routines lookup */
2484 info.is_rowtype = 2;
2486 desc = lookup_rowtype_tupdesc(arg->typoid, arg->typmod);
2489 * This will set up the dummy PLyTypeInfo's output conversion routines,
2490 * since we left is_rowtype as 2. A future optimisation could be caching
2491 * that info instead of looking it up every time a tuple is returned from
2494 tuple = PLyObject_ToTuple(&info, desc, plrv);
2496 PLy_typeinfo_dealloc(&info);
2499 rv = HeapTupleGetDatum(tuple);
2508 * Generic conversion function: Convert PyObject to cstring and
2509 * cstring into PostgreSQL type.
2512 PLyObject_ToDatum(PLyObToDatum *arg, int32 typmod, PyObject *plrv)
2514 PyObject *volatile plrv_bo = NULL;
2517 Assert(plrv != Py_None);
2519 if (PyUnicode_Check(plrv))
2520 plrv_bo = PLyUnicode_Bytes(plrv);
2523 #if PY_MAJOR_VERSION >= 3
2524 PyObject *s = PyObject_Str(plrv);
2526 plrv_bo = PLyUnicode_Bytes(s);
2529 plrv_bo = PyObject_Str(plrv);
2533 PLy_elog(ERROR, "could not create string representation of Python object");
2537 char *plrv_sc = PyBytes_AsString(plrv_bo);
2538 size_t plen = PyBytes_Size(plrv_bo);
2539 size_t slen = strlen(plrv_sc);
2543 (errcode(ERRCODE_DATATYPE_MISMATCH),
2544 errmsg("could not convert Python object into cstring: Python string representation appears to contain null bytes")));
2545 else if (slen > plen)
2546 elog(ERROR, "could not convert Python object into cstring: Python string longer than reported length");
2547 pg_verifymbstr(plrv_sc, slen, false);
2548 rv = InputFunctionCall(&arg->typfunc,
2555 Py_XDECREF(plrv_bo);
2560 Py_XDECREF(plrv_bo);
2566 PLySequence_ToArray(PLyObToDatum *arg, int32 typmod, PyObject *plrv)
2575 Assert(plrv != Py_None);
2577 if (!PySequence_Check(plrv))
2578 PLy_elog(ERROR, "return value of function with array return type is not a Python sequence");
2580 len = PySequence_Length(plrv);
2581 elems = palloc(sizeof(*elems) * len);
2582 nulls = palloc(sizeof(*nulls) * len);
2584 for (i = 0; i < len; i++)
2586 PyObject *obj = PySequence_GetItem(plrv, i);
2595 * We don't support arrays of row types yet, so the first argument
2598 elems[i] = arg->elm->func(arg->elm, -1, obj);
2604 array = construct_md_array(elems, nulls, 1, &len, &lbs,
2605 get_element_type(arg->typoid), arg->elm->typlen, arg->elm->typbyval, arg->elm->typalign);
2606 return PointerGetDatum(array);
2610 PLyMapping_ToTuple(PLyTypeInfo *info, TupleDesc desc, PyObject *mapping)
2617 Assert(PyMapping_Check(mapping));
2619 if (info->is_rowtype == 2)
2620 PLy_output_tuple_funcs(info, desc);
2621 Assert(info->is_rowtype == 1);
2624 values = palloc(sizeof(Datum) * desc->natts);
2625 nulls = palloc(sizeof(bool) * desc->natts);
2626 for (i = 0; i < desc->natts; ++i)
2629 PyObject *volatile value;
2632 if (desc->attrs[i]->attisdropped)
2635 key = NameStr(desc->attrs[i]->attname);
2637 att = &info->out.r.atts[i];
2640 value = PyMapping_GetItemString(mapping, key);
2641 if (value == Py_None)
2643 values[i] = (Datum) NULL;
2648 values[i] = (att->func) (att, -1, value);
2653 (errcode(ERRCODE_UNDEFINED_COLUMN),
2654 errmsg("key \"%s\" not found in mapping", key),
2655 errhint("To return null in a column, "
2656 "add the value None to the mapping with the key named after the column.")));
2669 tuple = heap_form_tuple(desc, values, nulls);
2670 ReleaseTupleDesc(desc);
2679 PLySequence_ToTuple(PLyTypeInfo *info, TupleDesc desc, PyObject *sequence)
2687 Assert(PySequence_Check(sequence));
2690 * Check that sequence length is exactly same as PG tuple's. We actually
2691 * can ignore exceeding items or assume missing ones as null but to avoid
2692 * plpython developer's errors we are strict here
2695 for (i = 0; i < desc->natts; i++)
2697 if (!desc->attrs[i]->attisdropped)
2700 if (PySequence_Length(sequence) != idx)
2702 (errcode(ERRCODE_DATATYPE_MISMATCH),
2703 errmsg("length of returned sequence did not match number of columns in row")));
2705 if (info->is_rowtype == 2)
2706 PLy_output_tuple_funcs(info, desc);
2707 Assert(info->is_rowtype == 1);
2710 values = palloc(sizeof(Datum) * desc->natts);
2711 nulls = palloc(sizeof(bool) * desc->natts);
2713 for (i = 0; i < desc->natts; ++i)
2715 PyObject *volatile value;
2718 if (desc->attrs[i]->attisdropped)
2722 att = &info->out.r.atts[i];
2725 value = PySequence_GetItem(sequence, idx);
2727 if (value == Py_None)
2729 values[i] = (Datum) NULL;
2734 values[i] = (att->func) (att, -1, value);
2751 tuple = heap_form_tuple(desc, values, nulls);
2752 ReleaseTupleDesc(desc);
2761 PLyGenericObject_ToTuple(PLyTypeInfo *info, TupleDesc desc, PyObject *object)
2768 if (info->is_rowtype == 2)
2769 PLy_output_tuple_funcs(info, desc);
2770 Assert(info->is_rowtype == 1);
2773 values = palloc(sizeof(Datum) * desc->natts);
2774 nulls = palloc(sizeof(bool) * desc->natts);
2775 for (i = 0; i < desc->natts; ++i)
2778 PyObject *volatile value;
2781 if (desc->attrs[i]->attisdropped)
2784 key = NameStr(desc->attrs[i]->attname);
2786 att = &info->out.r.atts[i];
2789 value = PyObject_GetAttrString(object, key);
2790 if (value == Py_None)
2792 values[i] = (Datum) NULL;
2797 values[i] = (att->func) (att, -1, value);
2802 (errcode(ERRCODE_UNDEFINED_COLUMN),
2803 errmsg("attribute \"%s\" does not exist in Python object", key),
2804 errhint("To return null in a column, "
2805 "let the returned object have an attribute named "
2806 "after column with value None.")));
2819 tuple = heap_form_tuple(desc, values, nulls);
2820 ReleaseTupleDesc(desc);
2828 /* initialization, some python variables function declared here */
2830 /* interface to postgresql elog */
2831 static PyObject *PLy_debug(PyObject *, PyObject *);
2832 static PyObject *PLy_log(PyObject *, PyObject *);
2833 static PyObject *PLy_info(PyObject *, PyObject *);
2834 static PyObject *PLy_notice(PyObject *, PyObject *);
2835 static PyObject *PLy_warning(PyObject *, PyObject *);
2836 static PyObject *PLy_error(PyObject *, PyObject *);
2837 static PyObject *PLy_fatal(PyObject *, PyObject *);
2839 /* PLyPlanObject, PLyResultObject and SPI interface */
2840 #define is_PLyPlanObject(x) ((x)->ob_type == &PLy_PlanType)
2841 static PyObject *PLy_plan_new(void);
2842 static void PLy_plan_dealloc(PyObject *);
2843 static PyObject *PLy_plan_status(PyObject *, PyObject *);
2845 static PyObject *PLy_result_new(void);
2846 static void PLy_result_dealloc(PyObject *);
2847 static PyObject *PLy_result_nrows(PyObject *, PyObject *);
2848 static PyObject *PLy_result_status(PyObject *, PyObject *);
2849 static Py_ssize_t PLy_result_length(PyObject *);
2850 static PyObject *PLy_result_item(PyObject *, Py_ssize_t);
2851 static PyObject *PLy_result_slice(PyObject *, Py_ssize_t, Py_ssize_t);
2852 static int PLy_result_ass_item(PyObject *, Py_ssize_t, PyObject *);
2853 static int PLy_result_ass_slice(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
2856 static PyObject *PLy_spi_prepare(PyObject *, PyObject *);
2857 static PyObject *PLy_spi_execute(PyObject *, PyObject *);
2858 static PyObject *PLy_spi_execute_query(char *query, long limit);
2859 static PyObject *PLy_spi_execute_plan(PyObject *, PyObject *, long);
2860 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *, int, int);
2862 static PyObject *PLy_quote_literal(PyObject *self, PyObject *args);
2863 static PyObject *PLy_quote_nullable(PyObject *self, PyObject *args);
2864 static PyObject *PLy_quote_ident(PyObject *self, PyObject *args);
2866 static PyObject *PLy_subtransaction(PyObject *, PyObject *);
2867 static PyObject *PLy_subtransaction_new(void);
2868 static void PLy_subtransaction_dealloc(PyObject *);
2869 static PyObject *PLy_subtransaction_enter(PyObject *, PyObject *);
2870 static PyObject *PLy_subtransaction_exit(PyObject *, PyObject *);
2873 static PyMethodDef PLy_plan_methods[] = {
2874 {"status", PLy_plan_status, METH_VARARGS, NULL},
2875 {NULL, NULL, 0, NULL}
2878 static PyTypeObject PLy_PlanType = {
2879 PyVarObject_HEAD_INIT(NULL, 0)
2880 "PLyPlan", /* tp_name */
2881 sizeof(PLyPlanObject), /* tp_size */
2882 0, /* tp_itemsize */
2887 PLy_plan_dealloc, /* tp_dealloc */
2893 0, /* tp_as_number */
2894 0, /* tp_as_sequence */
2895 0, /* tp_as_mapping */
2899 0, /* tp_getattro */
2900 0, /* tp_setattro */
2901 0, /* tp_as_buffer */
2902 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2903 PLy_plan_doc, /* tp_doc */
2904 0, /* tp_traverse */
2906 0, /* tp_richcompare */
2907 0, /* tp_weaklistoffset */
2909 0, /* tp_iternext */
2910 PLy_plan_methods, /* tp_tpmethods */
2913 static PySequenceMethods PLy_result_as_sequence = {
2914 PLy_result_length, /* sq_length */
2915 NULL, /* sq_concat */
2916 NULL, /* sq_repeat */
2917 PLy_result_item, /* sq_item */
2918 PLy_result_slice, /* sq_slice */
2919 PLy_result_ass_item, /* sq_ass_item */
2920 PLy_result_ass_slice, /* sq_ass_slice */
2923 static PyMethodDef PLy_result_methods[] = {
2924 {"nrows", PLy_result_nrows, METH_VARARGS, NULL},
2925 {"status", PLy_result_status, METH_VARARGS, NULL},
2926 {NULL, NULL, 0, NULL}
2929 static PyTypeObject PLy_ResultType = {
2930 PyVarObject_HEAD_INIT(NULL, 0)
2931 "PLyResult", /* tp_name */
2932 sizeof(PLyResultObject), /* tp_size */
2933 0, /* tp_itemsize */
2938 PLy_result_dealloc, /* tp_dealloc */
2944 0, /* tp_as_number */
2945 &PLy_result_as_sequence, /* tp_as_sequence */
2946 0, /* tp_as_mapping */
2950 0, /* tp_getattro */
2951 0, /* tp_setattro */
2952 0, /* tp_as_buffer */
2953 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2954 PLy_result_doc, /* tp_doc */
2955 0, /* tp_traverse */
2957 0, /* tp_richcompare */
2958 0, /* tp_weaklistoffset */
2960 0, /* tp_iternext */
2961 PLy_result_methods, /* tp_tpmethods */
2964 static PyMethodDef PLy_subtransaction_methods[] = {
2965 {"__enter__", PLy_subtransaction_enter, METH_VARARGS, NULL},
2966 {"__exit__", PLy_subtransaction_exit, METH_VARARGS, NULL},
2967 /* user-friendly names for Python <2.6 */
2968 {"enter", PLy_subtransaction_enter, METH_VARARGS, NULL},
2969 {"exit", PLy_subtransaction_exit, METH_VARARGS, NULL},
2970 {NULL, NULL, 0, NULL}
2973 static PyTypeObject PLy_SubtransactionType = {
2974 PyVarObject_HEAD_INIT(NULL, 0)
2975 "PLySubtransaction", /* tp_name */
2976 sizeof(PLySubtransactionObject), /* tp_size */
2977 0, /* tp_itemsize */
2982 PLy_subtransaction_dealloc, /* tp_dealloc */
2988 0, /* tp_as_number */
2989 0, /* tp_as_sequence */
2990 0, /* tp_as_mapping */
2994 0, /* tp_getattro */
2995 0, /* tp_setattro */
2996 0, /* tp_as_buffer */
2997 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2998 PLy_subtransaction_doc, /* tp_doc */
2999 0, /* tp_traverse */
3001 0, /* tp_richcompare */
3002 0, /* tp_weaklistoffset */
3004 0, /* tp_iternext */
3005 PLy_subtransaction_methods, /* tp_tpmethods */
3008 static PyMethodDef PLy_methods[] = {
3012 {"debug", PLy_debug, METH_VARARGS, NULL},
3013 {"log", PLy_log, METH_VARARGS, NULL},
3014 {"info", PLy_info, METH_VARARGS, NULL},
3015 {"notice", PLy_notice, METH_VARARGS, NULL},
3016 {"warning", PLy_warning, METH_VARARGS, NULL},
3017 {"error", PLy_error, METH_VARARGS, NULL},
3018 {"fatal", PLy_fatal, METH_VARARGS, NULL},
3021 * create a stored plan
3023 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
3026 * execute a plan or query
3028 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
3033 {"quote_literal", PLy_quote_literal, METH_VARARGS, NULL},
3034 {"quote_nullable", PLy_quote_nullable, METH_VARARGS, NULL},
3035 {"quote_ident", PLy_quote_ident, METH_VARARGS, NULL},
3038 * create the subtransaction context manager
3040 {"subtransaction", PLy_subtransaction, METH_NOARGS, NULL},
3042 {NULL, NULL, 0, NULL}
3045 static PyMethodDef PLy_exc_methods[] = {
3046 {NULL, NULL, 0, NULL}
3049 #if PY_MAJOR_VERSION >= 3
3050 static PyModuleDef PLy_module = {
3051 PyModuleDef_HEAD_INIT, /* m_base */
3052 "plpy", /* m_name */
3055 PLy_methods, /* m_methods */
3058 static PyModuleDef PLy_exc_module = {
3059 PyModuleDef_HEAD_INIT, /* m_base */
3060 "spiexceptions", /* m_name */
3063 PLy_exc_methods, /* m_methods */
3064 NULL, /* m_reload */
3065 NULL, /* m_traverse */
3071 /* plan object methods */
3077 if ((ob = PyObject_New(PLyPlanObject, &PLy_PlanType)) == NULL)
3086 return (PyObject *) ob;
3091 PLy_plan_dealloc(PyObject *arg)
3093 PLyPlanObject *ob = (PLyPlanObject *) arg;
3096 SPI_freeplan(ob->plan);
3098 PLy_free(ob->types);
3100 PLy_free(ob->values);
3105 for (i = 0; i < ob->nargs; i++)
3106 PLy_typeinfo_dealloc(&ob->args[i]);
3110 arg->ob_type->tp_free(arg);
3115 PLy_plan_status(PyObject *self, PyObject *args)
3117 if (PyArg_ParseTuple(args, ""))
3121 /* return PyInt_FromLong(self->status); */
3123 PLy_exception_set(PLy_exc_error, "plan.status takes no arguments");
3129 /* result object methods */
3132 PLy_result_new(void)
3134 PLyResultObject *ob;
3136 if ((ob = PyObject_New(PLyResultObject, &PLy_ResultType)) == NULL)
3139 /* ob->tuples = NULL; */
3142 ob->status = Py_None;
3143 ob->nrows = PyInt_FromLong(-1);
3144 ob->rows = PyList_New(0);
3146 return (PyObject *) ob;
3150 PLy_result_dealloc(PyObject *arg)
3152 PLyResultObject *ob = (PLyResultObject *) arg;
3154 Py_XDECREF(ob->nrows);
3155 Py_XDECREF(ob->rows);
3156 Py_XDECREF(ob->status);
3158 arg->ob_type->tp_free(arg);
3162 PLy_result_nrows(PyObject *self, PyObject *args)
3164 PLyResultObject *ob = (PLyResultObject *) self;
3166 Py_INCREF(ob->nrows);
3171 PLy_result_status(PyObject *self, PyObject *args)
3173 PLyResultObject *ob = (PLyResultObject *) self;
3175 Py_INCREF(ob->status);
3180 PLy_result_length(PyObject *arg)
3182 PLyResultObject *ob = (PLyResultObject *) arg;
3184 return PyList_Size(ob->rows);
3188 PLy_result_item(PyObject *arg, Py_ssize_t idx)
3191 PLyResultObject *ob = (PLyResultObject *) arg;
3193 rv = PyList_GetItem(ob->rows, idx);
3200 PLy_result_ass_item(PyObject *arg, Py_ssize_t idx, PyObject *item)
3203 PLyResultObject *ob = (PLyResultObject *) arg;
3206 rv = PyList_SetItem(ob->rows, idx, item);
3211 PLy_result_slice(PyObject *arg, Py_ssize_t lidx, Py_ssize_t hidx)
3213 PLyResultObject *ob = (PLyResultObject *) arg;
3215 return PyList_GetSlice(ob->rows, lidx, hidx);
3219 PLy_result_ass_slice(PyObject *arg, Py_ssize_t lidx, Py_ssize_t hidx, PyObject *slice)
3222 PLyResultObject *ob = (PLyResultObject *) arg;
3224 rv = PyList_SetSlice(ob->rows, lidx, hidx, slice);
3230 PLy_spi_prepare(PyObject *self, PyObject *args)
3232 PLyPlanObject *plan;
3233 PyObject *list = NULL;
3234 PyObject *volatile optr = NULL;
3237 volatile MemoryContext oldcontext;
3238 volatile ResourceOwner oldowner;
3241 if (!PyArg_ParseTuple(args, "s|O", &query, &list))
3244 if (list && (!PySequence_Check(list)))
3246 PLy_exception_set(PyExc_TypeError,
3247 "second argument of plpy.prepare must be a sequence");
3251 if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
3254 nargs = list ? PySequence_Length(list) : 0;
3256 plan->nargs = nargs;
3257 plan->types = nargs ? PLy_malloc(sizeof(Oid) * nargs) : NULL;
3258 plan->values = nargs ? PLy_malloc(sizeof(Datum) * nargs) : NULL;
3259 plan->args = nargs ? PLy_malloc(sizeof(PLyTypeInfo) * nargs) : NULL;
3261 oldcontext = CurrentMemoryContext;
3262 oldowner = CurrentResourceOwner;
3264 BeginInternalSubTransaction(NULL);
3265 MemoryContextSwitchTo(oldcontext);
3272 * the other loop might throw an exception, if PLyTypeInfo member
3273 * isn't properly initialized the Py_DECREF(plan) will go boom
3275 for (i = 0; i < nargs; i++)
3277 PLy_typeinfo_init(&plan->args[i]);
3278 plan->values[i] = PointerGetDatum(NULL);
3281 for (i = 0; i < nargs; i++)
3287 Form_pg_type typeStruct;
3289 optr = PySequence_GetItem(list, i);
3290 if (PyString_Check(optr))
3291 sptr = PyString_AsString(optr);
3292 else if (PyUnicode_Check(optr))
3293 sptr = PLyUnicode_AsString(optr);
3297 (errmsg("plpy.prepare: type name at ordinal position %d is not a string", i)));
3298 sptr = NULL; /* keep compiler quiet */
3301 /********************************************************
3302 * Resolve argument type names and then look them up by
3303 * oid in the system cache, and remember the required
3304 *information for input conversion.
3305 ********************************************************/
3307 parseTypeString(sptr, &typeId, &typmod);
3309 typeTup = SearchSysCache1(TYPEOID,
3310 ObjectIdGetDatum(typeId));
3311 if (!HeapTupleIsValid(typeTup))
3312 elog(ERROR, "cache lookup failed for type %u", typeId);
3317 * set optr to NULL, so we won't try to unref it again in case of
3322 plan->types[i] = typeId;
3323 typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
3324 if (typeStruct->typtype != TYPTYPE_COMPOSITE)
3325 PLy_output_datum_func(&plan->args[i], typeTup);
3328 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3329 errmsg("plpy.prepare does not support composite types")));
3330 ReleaseSysCache(typeTup);
3333 pg_verifymbstr(query, strlen(query), false);
3334 plan->plan = SPI_prepare(query, plan->nargs, plan->types);
3335 if (plan->plan == NULL)
3336 elog(ERROR, "SPI_prepare failed: %s",
3337 SPI_result_code_string(SPI_result));
3339 /* transfer plan from procCxt to topCxt */
3340 tmpplan = plan->plan;
3341 plan->plan = SPI_saveplan(tmpplan);
3342 SPI_freeplan(tmpplan);
3343 if (plan->plan == NULL)
3344 elog(ERROR, "SPI_saveplan failed: %s",
3345 SPI_result_code_string(SPI_result));
3347 /* Commit the inner transaction, return to outer xact context */
3348 ReleaseCurrentSubTransaction();
3349 MemoryContextSwitchTo(oldcontext);
3350 CurrentResourceOwner = oldowner;
3353 * AtEOSubXact_SPI() should not have popped any SPI context, but just
3354 * in case it did, make sure we remain connected.
3356 SPI_restore_connection();
3361 PLyExceptionEntry *entry;
3364 /* Save error info */
3365 MemoryContextSwitchTo(oldcontext);
3366 edata = CopyErrorData();
3371 /* Abort the inner transaction */
3372 RollbackAndReleaseCurrentSubTransaction();
3373 MemoryContextSwitchTo(oldcontext);
3374 CurrentResourceOwner = oldowner;
3377 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
3378 * have left us in a disconnected state. We need this hack to return
3379 * to connected state.
3381 SPI_restore_connection();
3383 /* Look up the correct exception */
3384 entry = hash_search(PLy_spi_exceptions, &(edata->sqlerrcode),
3386 /* We really should find it, but just in case have a fallback */
3387 Assert(entry != NULL);
3388 exc = entry ? entry->exc : PLy_exc_spi_error;
3389 /* Make Python raise the exception */
3390 PLy_spi_exception_set(exc, edata);
3395 Assert(plan->plan != NULL);
3396 return (PyObject *) plan;
3399 /* execute(query="select * from foo", limit=5)
3400 * execute(plan=plan, values=(foo, bar), limit=5)
3403 PLy_spi_execute(PyObject *self, PyObject *args)
3407 PyObject *list = NULL;
3410 if (PyArg_ParseTuple(args, "s|l", &query, &limit))
3411 return PLy_spi_execute_query(query, limit);
3415 if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
3416 is_PLyPlanObject(plan))
3417 return PLy_spi_execute_plan(plan, list, limit);
3419 PLy_exception_set(PLy_exc_error, "plpy.execute expected a query or a plan");
3424 PLy_spi_execute_plan(PyObject *ob, PyObject *list, long limit)
3429 PLyPlanObject *plan;
3430 volatile MemoryContext oldcontext;
3431 volatile ResourceOwner oldowner;
3436 if (!PySequence_Check(list) || PyString_Check(list) || PyUnicode_Check(list))
3438 PLy_exception_set(PyExc_TypeError, "plpy.execute takes a sequence as its second argument");
3441 nargs = PySequence_Length(list);
3446 plan = (PLyPlanObject *) ob;
3448 if (nargs != plan->nargs)
3451 PyObject *so = PyObject_Str(list);
3454 PLy_elog(ERROR, "could not execute plan");
3455 sv = PyString_AsString(so);
3456 PLy_exception_set_plural(PyExc_TypeError,
3457 "Expected sequence of %d argument, got %d: %s",
3458 "Expected sequence of %d arguments, got %d: %s",
3460 plan->nargs, nargs, sv);
3466 oldcontext = CurrentMemoryContext;
3467 oldowner = CurrentResourceOwner;
3469 BeginInternalSubTransaction(NULL);
3470 /* Want to run inside function's memory context */
3471 MemoryContextSwitchTo(oldcontext);
3475 char *volatile nulls;
3479 nulls = palloc(nargs * sizeof(char));
3483 for (j = 0; j < nargs; j++)
3487 elem = PySequence_GetItem(list, j);
3488 if (elem != Py_None)
3493 plan->args[j].out.d.func(&(plan->args[j].out.d),
3511 InputFunctionCall(&(plan->args[j].out.d.typfunc),
3513 plan->args[j].out.d.typioparam,
3519 rv = SPI_execute_plan(plan->plan, plan->values, nulls,
3520 PLy_curr_procedure->fn_readonly, limit);
3521 ret = PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
3526 /* Commit the inner transaction, return to outer xact context */
3527 ReleaseCurrentSubTransaction();
3528 MemoryContextSwitchTo(oldcontext);
3529 CurrentResourceOwner = oldowner;
3532 * AtEOSubXact_SPI() should not have popped any SPI context, but just
3533 * in case it did, make sure we remain connected.
3535 SPI_restore_connection();
3541 PLyExceptionEntry *entry;
3544 /* Save error info */
3545 MemoryContextSwitchTo(oldcontext);
3546 edata = CopyErrorData();
3550 * cleanup plan->values array
3552 for (k = 0; k < nargs; k++)
3554 if (!plan->args[k].out.d.typbyval &&
3555 (plan->values[k] != PointerGetDatum(NULL)))
3557 pfree(DatumGetPointer(plan->values[k]));
3558 plan->values[k] = PointerGetDatum(NULL);
3562 /* Abort the inner transaction */
3563 RollbackAndReleaseCurrentSubTransaction();
3564 MemoryContextSwitchTo(oldcontext);
3565 CurrentResourceOwner = oldowner;
3568 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
3569 * have left us in a disconnected state. We need this hack to return
3570 * to connected state.
3572 SPI_restore_connection();
3574 /* Look up the correct exception */
3575 entry = hash_search(PLy_spi_exceptions, &(edata->sqlerrcode),
3577 /* We really should find it, but just in case have a fallback */
3578 Assert(entry != NULL);
3579 exc = entry ? entry->exc : PLy_exc_spi_error;
3580 /* Make Python raise the exception */
3581 PLy_spi_exception_set(exc, edata);
3586 for (i = 0; i < nargs; i++)
3588 if (!plan->args[i].out.d.typbyval &&
3589 (plan->values[i] != PointerGetDatum(NULL)))
3591 pfree(DatumGetPointer(plan->values[i]));
3592 plan->values[i] = PointerGetDatum(NULL);
3598 PLy_exception_set(PLy_exc_spi_error,
3599 "SPI_execute_plan failed: %s",
3600 SPI_result_code_string(rv));
3608 PLy_spi_execute_query(char *query, long limit)
3611 volatile MemoryContext oldcontext;
3612 volatile ResourceOwner oldowner;
3615 oldcontext = CurrentMemoryContext;
3616 oldowner = CurrentResourceOwner;
3618 BeginInternalSubTransaction(NULL);
3619 /* Want to run inside function's memory context */
3620 MemoryContextSwitchTo(oldcontext);
3624 pg_verifymbstr(query, strlen(query), false);
3625 rv = SPI_execute(query, PLy_curr_procedure->fn_readonly, limit);
3626 ret = PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
3628 /* Commit the inner transaction, return to outer xact context */
3629 ReleaseCurrentSubTransaction();
3630 MemoryContextSwitchTo(oldcontext);
3631 CurrentResourceOwner = oldowner;
3634 * AtEOSubXact_SPI() should not have popped any SPI context, but just
3635 * in case it did, make sure we remain connected.
3637 SPI_restore_connection();
3642 PLyExceptionEntry *entry;
3645 /* Save error info */
3646 MemoryContextSwitchTo(oldcontext);
3647 edata = CopyErrorData();
3650 /* Abort the inner transaction */
3651 RollbackAndReleaseCurrentSubTransaction();
3652 MemoryContextSwitchTo(oldcontext);
3653 CurrentResourceOwner = oldowner;
3656 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
3657 * have left us in a disconnected state. We need this hack to return
3658 * to connected state.
3660 SPI_restore_connection();
3662 /* Look up the correct exception */
3663 entry = hash_search(PLy_spi_exceptions, &edata->sqlerrcode,
3665 /* We really should find it, but just in case have a fallback */
3666 Assert(entry != NULL);
3667 exc = entry ? entry->exc : PLy_exc_spi_error;
3668 /* Make Python raise the exception */
3669 PLy_spi_exception_set(exc, edata);
3676 PLy_exception_set(PLy_exc_spi_error,
3677 "SPI_execute failed: %s",
3678 SPI_result_code_string(rv));
3686 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status)
3688 PLyResultObject *result;
3689 volatile MemoryContext oldcontext;
3691 result = (PLyResultObject *) PLy_result_new();
3692 Py_DECREF(result->status);
3693 result->status = PyInt_FromLong(status);
3695 if (status > 0 && tuptable == NULL)
3697 Py_DECREF(result->nrows);
3698 result->nrows = PyInt_FromLong(rows);
3700 else if (status > 0 && tuptable != NULL)
3705 Py_DECREF(result->nrows);
3706 result->nrows = PyInt_FromLong(rows);
3707 PLy_typeinfo_init(&args);
3709 oldcontext = CurrentMemoryContext;
3714 Py_DECREF(result->rows);
3715 result->rows = PyList_New(rows);
3717 PLy_input_tuple_funcs(&args, tuptable->tupdesc);
3718 for (i = 0; i < rows; i++)
3720 PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i],
3723 PyList_SetItem(result->rows, i, row);
3729 MemoryContextSwitchTo(oldcontext);
3730 if (!PyErr_Occurred())
3731 PLy_exception_set(PLy_exc_error,
3732 "unrecognized error in PLy_spi_execute_fetch_result");
3733 PLy_typeinfo_dealloc(&args);
3734 SPI_freetuptable(tuptable);
3740 PLy_typeinfo_dealloc(&args);
3741 SPI_freetuptable(tuptable);
3744 return (PyObject *) result;
3747 /* s = plpy.subtransaction() */
3749 PLy_subtransaction(PyObject *self, PyObject *unused)
3751 return PLy_subtransaction_new();
3754 /* Allocate and initialize a PLySubtransactionObject */
3756 PLy_subtransaction_new(void)
3758 PLySubtransactionObject *ob;
3760 ob = PyObject_New(PLySubtransactionObject, &PLy_SubtransactionType);
3765 ob->started = false;
3768 return (PyObject *) ob;
3771 /* Python requires a dealloc function to be defined */
3773 PLy_subtransaction_dealloc(PyObject *subxact)
3778 * subxact.__enter__() or subxact.enter()
3780 * Start an explicit subtransaction. SPI calls within an explicit
3781 * subtransaction will not start another one, so you can atomically
3782 * execute many SPI calls and still get a controllable exception if
3783 * one of them fails.
3786 PLy_subtransaction_enter(PyObject *self, PyObject *unused)
3788 PLySubtransactionData *subxactdata;
3789 MemoryContext oldcontext;
3790 PLySubtransactionObject *subxact = (PLySubtransactionObject *) self;
3792 if (subxact->started)
3794 PLy_exception_set(PyExc_ValueError, "this subtransaction has already been entered");
3798 if (subxact->exited)
3800 PLy_exception_set(PyExc_ValueError, "this subtransaction has already been exited");
3804 subxact->started = true;
3805 oldcontext = CurrentMemoryContext;
3807 subxactdata = PLy_malloc(sizeof(*subxactdata));
3808 subxactdata->oldcontext = oldcontext;
3809 subxactdata->oldowner = CurrentResourceOwner;
3811 BeginInternalSubTransaction(NULL);
3812 /* Do not want to leave the previous memory context */
3813 MemoryContextSwitchTo(oldcontext);
3815 explicit_subtransactions = lcons(subxactdata, explicit_subtransactions);
3822 * subxact.__exit__(exc_type, exc, tb) or subxact.exit(exc_type, exc, tb)
3824 * Exit an explicit subtransaction. exc_type is an exception type, exc
3825 * is the exception object, tb is the traceback. If exc_type is None,
3826 * commit the subtransactiony, if not abort it.
3828 * The method signature is chosen to allow subtransaction objects to
3829 * be used as context managers as described in
3830 * <http://www.python.org/dev/peps/pep-0343/>.
3833 PLy_subtransaction_exit(PyObject *self, PyObject *args)
3837 PyObject *traceback;
3838 PLySubtransactionData *subxactdata;
3839 PLySubtransactionObject *subxact = (PLySubtransactionObject *) self;
3841 if (!PyArg_ParseTuple(args, "OOO", &type, &value, &traceback))
3844 if (!subxact->started)
3846 PLy_exception_set(PyExc_ValueError, "this subtransaction has not been entered");
3850 if (subxact->exited)
3852 PLy_exception_set(PyExc_ValueError, "this subtransaction has already been exited");
3856 if (explicit_subtransactions == NIL)
3858 PLy_exception_set(PyExc_ValueError, "there is no subtransaction to exit from");
3862 subxact->exited = true;
3864 if (type != Py_None)
3866 /* Abort the inner transaction */
3867 RollbackAndReleaseCurrentSubTransaction();
3871 ReleaseCurrentSubTransaction();
3874 subxactdata = (PLySubtransactionData *) linitial(explicit_subtransactions);
3875 explicit_subtransactions = list_delete_first(explicit_subtransactions);
3877 MemoryContextSwitchTo(subxactdata->oldcontext);
3878 CurrentResourceOwner = subxactdata->oldowner;
3879 PLy_free(subxactdata);
3882 * AtEOSubXact_SPI() should not have popped any SPI context, but just in
3883 * case it did, make sure we remain connected.
3885 SPI_restore_connection();
3893 * language handler and interpreter initialization
3897 * Add exceptions to the plpy module
3901 * Add all the autogenerated exceptions as subclasses of SPIError
3904 PLy_generate_spi_exceptions(PyObject *mod, PyObject *base)
3908 for (i = 0; exception_map[i].name != NULL; i++)
3912 PLyExceptionEntry *entry;
3914 PyObject *dict = PyDict_New();
3916 sqlstate = PyString_FromString(unpack_sql_state(exception_map[i].sqlstate));
3917 PyDict_SetItemString(dict, "sqlstate", sqlstate);
3918 Py_DECREF(sqlstate);
3919 exc = PyErr_NewException(exception_map[i].name, base, dict);
3920 PyModule_AddObject(mod, exception_map[i].classname, exc);
3921 entry = hash_search(PLy_spi_exceptions, &exception_map[i].sqlstate,
3922 HASH_ENTER, &found);
3929 PLy_add_exceptions(PyObject *plpy)
3934 #if PY_MAJOR_VERSION < 3
3935 excmod = Py_InitModule("spiexceptions", PLy_exc_methods);
3937 excmod = PyModule_Create(&PLy_exc_module);
3939 if (PyModule_AddObject(plpy, "spiexceptions", excmod) < 0)
3940 PLy_elog(ERROR, "could not add the spiexceptions module");
3943 * XXX it appears that in some circumstances the reference count of the
3944 * spiexceptions module drops to zero causing a Python assert failure when
3945 * the garbage collector visits the module. This has been observed on the
3946 * buildfarm. To fix this, add an additional ref for the module here.
3948 * This shouldn't cause a memory leak - we don't want this garbage collected,
3949 * and this function shouldn't be called more than once per backend.
3953 PLy_exc_error = PyErr_NewException("plpy.Error", NULL, NULL);
3954 PLy_exc_fatal = PyErr_NewException("plpy.Fatal", NULL, NULL);
3955 PLy_exc_spi_error = PyErr_NewException("plpy.SPIError", NULL, NULL);
3957 Py_INCREF(PLy_exc_error);
3958 PyModule_AddObject(plpy, "Error", PLy_exc_error);
3959 Py_INCREF(PLy_exc_fatal);
3960 PyModule_AddObject(plpy, "Fatal", PLy_exc_fatal);
3961 Py_INCREF(PLy_exc_spi_error);
3962 PyModule_AddObject(plpy, "SPIError", PLy_exc_spi_error);
3964 memset(&hash_ctl, 0, sizeof(hash_ctl));
3965 hash_ctl.keysize = sizeof(int);
3966 hash_ctl.entrysize = sizeof(PLyExceptionEntry);
3967 hash_ctl.hash = tag_hash;
3968 PLy_spi_exceptions = hash_create("SPI exceptions", 256,
3969 &hash_ctl, HASH_ELEM | HASH_FUNCTION);
3971 PLy_generate_spi_exceptions(excmod, PLy_exc_spi_error);
3974 #if PY_MAJOR_VERSION >= 3
3975 static PyMODINIT_FUNC
3980 m = PyModule_Create(&PLy_module);
3984 PLy_add_exceptions(m);
3991 static const int plpython_python_version = PY_MAJOR_VERSION;
3994 * _PG_init() - library load-time initialization
3996 * DO NOT make this static nor change its name!
4001 /* Be sure we do initialization only once (should be redundant now) */
4002 static bool inited = false;
4003 const int **version_ptr;
4009 /* Be sure we don't run Python 2 and 3 in the same session (might crash) */
4010 version_ptr = (const int **) find_rendezvous_variable("plpython_python_version");
4011 if (!(*version_ptr))
4012 *version_ptr = &plpython_python_version;
4015 if (**version_ptr != plpython_python_version)
4017 (errmsg("Python major version mismatch in session"),
4018 errdetail("This session has previously used Python major version %d, and it is now attempting to use Python major version %d.",
4019 **version_ptr, plpython_python_version),
4020 errhint("Start a new session to use a different Python major version.")));
4023 pg_bindtextdomain(TEXTDOMAIN);
4025 #if PY_MAJOR_VERSION >= 3
4026 PyImport_AppendInittab("plpy", PyInit_plpy);
4029 #if PY_MAJOR_VERSION >= 3
4030 PyImport_ImportModule("plpy");
4034 if (PyErr_Occurred())
4035 PLy_elog(FATAL, "untrapped error in initialization");
4037 memset(&hash_ctl, 0, sizeof(hash_ctl));
4038 hash_ctl.keysize = sizeof(Oid);
4039 hash_ctl.entrysize = sizeof(PLyProcedureEntry);
4040 hash_ctl.hash = oid_hash;
4041 PLy_procedure_cache = hash_create("PL/Python procedures", 32, &hash_ctl,
4042 HASH_ELEM | HASH_FUNCTION);
4044 memset(&hash_ctl, 0, sizeof(hash_ctl));
4045 hash_ctl.keysize = sizeof(Oid);
4046 hash_ctl.entrysize = sizeof(PLyProcedureEntry);
4047 hash_ctl.hash = oid_hash;
4048 PLy_trigger_cache = hash_create("PL/Python triggers", 32, &hash_ctl,
4049 HASH_ELEM | HASH_FUNCTION);
4051 explicit_subtransactions = NIL;
4057 PLy_init_interp(void)
4061 mainmod = PyImport_AddModule("__main__");
4062 if (mainmod == NULL || PyErr_Occurred())
4063 PLy_elog(ERROR, "could not import \"__main__\" module");
4065 PLy_interp_globals = PyModule_GetDict(mainmod);
4066 PLy_interp_safe_globals = PyDict_New();
4067 PyDict_SetItemString(PLy_interp_globals, "GD", PLy_interp_safe_globals);
4069 if (PLy_interp_globals == NULL || PyErr_Occurred())
4070 PLy_elog(ERROR, "could not initialize globals");
4082 * initialize plpy module
4084 if (PyType_Ready(&PLy_PlanType) < 0)
4085 elog(ERROR, "could not initialize PLy_PlanType");
4086 if (PyType_Ready(&PLy_ResultType) < 0)
4087 elog(ERROR, "could not initialize PLy_ResultType");
4088 if (PyType_Ready(&PLy_SubtransactionType) < 0)
4089 elog(ERROR, "could not initialize PLy_SubtransactionType");
4091 #if PY_MAJOR_VERSION >= 3
4092 plpy = PyModule_Create(&PLy_module);
4093 /* for Python 3 we initialized the exceptions in PyInit_plpy */
4095 plpy = Py_InitModule("plpy", PLy_methods);
4096 PLy_add_exceptions(plpy);
4099 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
4102 * initialize main module, and add plpy
4104 main_mod = PyImport_AddModule("__main__");
4105 main_dict = PyModule_GetDict(main_mod);
4106 plpy_mod = PyImport_AddModule("plpy");
4107 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
4108 if (PyErr_Occurred())
4109 elog(ERROR, "could not initialize plpy");
4112 /* the python interface to the elog function
4113 * don't confuse these with PLy_elog
4115 static PyObject *PLy_output(volatile int, PyObject *, PyObject *);
4118 PLy_debug(PyObject *self, PyObject *args)
4120 return PLy_output(DEBUG2, self, args);
4124 PLy_log(PyObject *self, PyObject *args)
4126 return PLy_output(LOG, self, args);
4130 PLy_info(PyObject *self, PyObject *args)
4132 return PLy_output(INFO, self, args);
4136 PLy_notice(PyObject *self, PyObject *args)
4138 return PLy_output(NOTICE, self, args);
4142 PLy_warning(PyObject *self, PyObject *args)
4144 return PLy_output(WARNING, self, args);
4148 PLy_error(PyObject *self, PyObject *args)
4150 return PLy_output(ERROR, self, args);
4154 PLy_fatal(PyObject *self, PyObject *args)
4156 return PLy_output(FATAL, self, args);
4161 PLy_output(volatile int level, PyObject *self, PyObject *args)
4163 PyObject *volatile so;
4165 volatile MemoryContext oldcontext;
4167 if (PyTuple_Size(args) == 1)
4170 * Treat single argument specially to avoid undesirable ('tuple',)
4175 PyArg_UnpackTuple(args, "plpy.elog", 1, 1, &o);
4176 so = PyObject_Str(o);
4179 so = PyObject_Str(args);
4180 if (so == NULL || ((sv = PyString_AsString(so)) == NULL))
4183 sv = dgettext(TEXTDOMAIN, "could not parse error message in plpy.elog");
4186 oldcontext = CurrentMemoryContext;
4189 pg_verifymbstr(sv, strlen(sv), false);
4190 elog(level, "%s", sv);
4196 MemoryContextSwitchTo(oldcontext);
4197 edata = CopyErrorData();
4201 * Note: If sv came from PyString_AsString(), it points into storage
4202 * owned by so. So free so after using sv.
4206 /* Make Python raise the exception */
4207 PLy_exception_set(PLy_exc_error, "%s", edata->message);
4215 * return a legal object so the interpreter will continue on its merry way
4223 PLy_quote_literal(PyObject *self, PyObject *args)
4229 if (!PyArg_ParseTuple(args, "s", &str))
4232 quoted = quote_literal_cstr(str);
4233 ret = PyString_FromString(quoted);
4240 PLy_quote_nullable(PyObject *self, PyObject *args)
4246 if (!PyArg_ParseTuple(args, "z", &str))
4250 return PyString_FromString("NULL");
4252 quoted = quote_literal_cstr(str);
4253 ret = PyString_FromString(quoted);
4260 PLy_quote_ident(PyObject *self, PyObject *args)
4266 if (!PyArg_ParseTuple(args, "s", &str))
4269 quoted = quote_identifier(str);
4270 ret = PyString_FromString(quoted);
4277 * Get the name of the last procedure called by the backend (the
4278 * innermost, if a plpython procedure call calls the backend and the
4279 * backend calls another plpython procedure).
4281 * NB: this returns the SQL name, not the internal Python procedure name
4284 PLy_procedure_name(PLyProcedure *proc)
4287 return "<unknown procedure>";
4288 return proc->proname;
4292 * Call PyErr_SetString with a vprint interface and translation support
4295 PLy_exception_set(PyObject *exc, const char *fmt,...)
4301 vsnprintf(buf, sizeof(buf), dgettext(TEXTDOMAIN, fmt), ap);
4304 PyErr_SetString(exc, buf);
4308 * The same, pluralized.
4311 PLy_exception_set_plural(PyObject *exc,
4312 const char *fmt_singular, const char *fmt_plural,
4313 unsigned long n,...)
4319 vsnprintf(buf, sizeof(buf),
4320 dngettext(TEXTDOMAIN, fmt_singular, fmt_plural, n),
4324 PyErr_SetString(exc, buf);
4328 * Raise a SPIError, passing in it more error details, like the
4329 * internal query and error position.
4332 PLy_spi_exception_set(PyObject *excclass, ErrorData *edata)
4334 PyObject *args = NULL;
4335 PyObject *spierror = NULL;
4336 PyObject *spidata = NULL;
4338 args = Py_BuildValue("(s)", edata->message);
4342 /* create a new SPI exception with the error message as the parameter */
4343 spierror = PyObject_CallObject(excclass, args);
4347 spidata = Py_BuildValue("(zzzi)", edata->detail, edata->hint,
4348 edata->internalquery, edata->internalpos);
4352 if (PyObject_SetAttrString(spierror, "spidata", spidata) == -1)
4355 PyErr_SetObject(excclass, spierror);
4358 Py_DECREF(spierror);
4364 Py_XDECREF(spierror);
4365 Py_XDECREF(spidata);
4366 elog(ERROR, "could not convert SPI error to Python exception");
4369 /* Emit a PG error or notice, together with any available info about
4370 * the current Python error, previously set by PLy_exception_set().
4371 * This should be used to propagate Python errors into PG. If fmt is
4372 * NULL, the Python error becomes the primary error message, otherwise
4373 * it becomes the detail. If there is a Python traceback, it is put
4377 PLy_elog(int elevel, const char *fmt,...)
4382 StringInfoData emsg;
4386 const char *primary = NULL;
4387 char *detail = NULL;
4392 PyErr_Fetch(&exc, &val, &tb);
4395 if (PyErr_GivenExceptionMatches(val, PLy_exc_spi_error))
4396 PLy_get_spi_error_data(val, &detail, &hint, &query, &position);
4397 else if (PyErr_GivenExceptionMatches(val, PLy_exc_fatal))
4400 PyErr_Restore(exc, val, tb);
4402 PLy_traceback(&xmsg, &tbmsg, &tb_depth);
4406 initStringInfo(&emsg);
4413 success = appendStringInfoVA(&emsg, dgettext(TEXTDOMAIN, fmt), ap);
4417 enlargeStringInfo(&emsg, emsg.maxlen);
4419 primary = emsg.data;
4421 /* Since we have a format string, we cannot have a SPI detail. */
4422 Assert(detail == NULL);
4424 /* If there's an exception message, it goes in the detail. */
4437 (errmsg("%s", primary ? primary : "no exception data"),
4438 (detail) ? errdetail("%s", detail) : 0,
4439 (tb_depth > 0 && tbmsg) ? errcontext("%s", tbmsg) : 0,
4440 (hint) ? errhint("%s", hint) : 0,
4441 (query) ? internalerrquery(query) : 0,
4442 (position) ? internalerrposition(position) : 0));
4465 * Extract the error data from a SPIError
4468 PLy_get_spi_error_data(PyObject *exc, char **detail, char **hint, char **query, int *position)
4470 PyObject *spidata = NULL;
4472 spidata = PyObject_GetAttrString(exc, "spidata");
4476 if (!PyArg_ParseTuple(spidata, "zzzi", detail, hint, query, position))
4481 /* no elog here, we simply won't report the errhint, errposition etc */
4482 Py_XDECREF(spidata);
4486 * Get the given source line as a palloc'd string
4489 get_source_line(const char *src, int lineno)
4491 const char *s = NULL;
4492 const char *next = src;
4495 while (current < lineno)
4498 next = strchr(s + 1, '\n');
4504 if (current != lineno)
4507 while (*s && isspace((unsigned char) *s))
4514 * Sanity check, next < s if the line was all-whitespace, which should
4515 * never happen if Python reported a frame created on that line, but check
4521 return pnstrdup(s, next - s);
4525 * Extract a Python traceback from the current exception.
4527 * The exception error message is returned in xmsg, the traceback in
4528 * tbmsg (both as palloc'd strings) and the traceback depth in
4532 PLy_traceback(char **xmsg, char **tbmsg, int *tb_depth)
4538 PyObject *e_module_o;
4539 char *e_type_s = NULL;
4540 char *e_module_s = NULL;
4541 PyObject *vob = NULL;
4543 StringInfoData xstr;
4544 StringInfoData tbstr;
4547 * get the current exception
4549 PyErr_Fetch(&e, &v, &tb);
4552 * oops, no exception, return
4563 PyErr_NormalizeException(&e, &v, &tb);
4566 * Format the exception and its value and put it in xmsg.
4569 e_type_o = PyObject_GetAttrString(e, "__name__");
4570 e_module_o = PyObject_GetAttrString(e, "__module__");
4572 e_type_s = PyString_AsString(e_type_o);
4574 e_module_s = PyString_AsString(e_module_o);
4576 if (v && ((vob = PyObject_Str(v)) != NULL))
4577 vstr = PyString_AsString(vob);
4581 initStringInfo(&xstr);
4582 if (!e_type_s || !e_module_s)
4584 if (PyString_Check(e))
4585 /* deprecated string exceptions */
4586 appendStringInfoString(&xstr, PyString_AsString(e));
4588 /* shouldn't happen */
4589 appendStringInfoString(&xstr, "unrecognized exception");
4591 /* mimics behavior of traceback.format_exception_only */
4592 else if (strcmp(e_module_s, "builtins") == 0
4593 || strcmp(e_module_s, "__main__") == 0
4594 || strcmp(e_module_s, "exceptions") == 0)
4595 appendStringInfo(&xstr, "%s", e_type_s);
4597 appendStringInfo(&xstr, "%s.%s", e_module_s, e_type_s);
4598 appendStringInfo(&xstr, ": %s", vstr);
4603 * Now format the traceback and put it in tbmsg.
4607 initStringInfo(&tbstr);
4608 /* Mimick Python traceback reporting as close as possible. */
4609 appendStringInfoString(&tbstr, "Traceback (most recent call last):");
4610 while (tb != NULL && tb != Py_None)
4612 PyObject *volatile tb_prev = NULL;
4613 PyObject *volatile frame = NULL;
4614 PyObject *volatile code = NULL;
4615 PyObject *volatile name = NULL;
4616 PyObject *volatile lineno = NULL;
4617 PyObject *volatile filename = NULL;
4621 lineno = PyObject_GetAttrString(tb, "tb_lineno");
4623 elog(ERROR, "could not get line number from Python traceback");
4625 frame = PyObject_GetAttrString(tb, "tb_frame");
4627 elog(ERROR, "could not get frame from Python traceback");
4629 code = PyObject_GetAttrString(frame, "f_code");
4631 elog(ERROR, "could not get code object from Python frame");
4633 name = PyObject_GetAttrString(code, "co_name");
4635 elog(ERROR, "could not get function name from Python code object");
4637 filename = PyObject_GetAttrString(code, "co_filename");
4638 if (filename == NULL)
4639 elog(ERROR, "could not get file name from Python code object");
4647 Py_XDECREF(filename);
4652 /* The first frame always points at <module>, skip it. */
4658 char *plain_filename;
4662 * The second frame points at the internal function, but to mimick
4663 * Python error reporting we want to say <module>.
4668 fname = PyString_AsString(name);
4670 proname = PLy_procedure_name(PLy_curr_procedure);
4671 plain_filename = PyString_AsString(filename);
4672 plain_lineno = PyInt_AsLong(lineno);
4674 if (proname == NULL)
4676 &tbstr, "\n PL/Python anonymous code block, line %ld, in %s",
4677 plain_lineno - 1, fname);
4680 &tbstr, "\n PL/Python function \"%s\", line %ld, in %s",
4681 proname, plain_lineno - 1, fname);
4684 * function code object was compiled with "<string>" as the
4687 if (PLy_curr_procedure && plain_filename != NULL &&
4688 strcmp(plain_filename, "<string>") == 0)
4691 * If we know the current procedure, append the exact line
4692 * from the source, again mimicking Python's traceback.py
4693 * module behavior. We could store the already line-split
4694 * source to avoid splitting it every time, but producing a
4695 * traceback is not the most important scenario to optimize
4696 * for. But we do not go as far as traceback.py in reading
4697 * the source of imported modules.
4699 line = get_source_line(PLy_curr_procedure->src, plain_lineno);
4702 appendStringInfo(&tbstr, "\n %s", line);
4712 Py_DECREF(filename);
4714 /* Release the current frame and go to the next one. */
4716 tb = PyObject_GetAttrString(tb, "tb_next");
4717 Assert(tb_prev != Py_None);
4720 elog(ERROR, "could not traverse Python traceback");
4724 /* Return the traceback. */
4725 *tbmsg = tbstr.data;
4727 Py_XDECREF(e_type_o);
4728 Py_XDECREF(e_module_o);
4734 /* python module code */
4736 /* some dumb utility functions */
4738 PLy_malloc(size_t bytes)
4740 /* We need our allocations to be long-lived, so use TopMemoryContext */
4741 return MemoryContextAlloc(TopMemoryContext, bytes);
4745 PLy_malloc0(size_t bytes)
4747 void *ptr = PLy_malloc(bytes);
4749 MemSet(ptr, 0, bytes);
4754 PLy_strdup(const char *str)
4759 len = strlen(str) + 1;
4760 result = PLy_malloc(len);
4761 memcpy(result, str, len);
4766 /* define this away */
4774 * Convert a Python unicode object to a Python string/bytes object in
4775 * PostgreSQL server encoding. Reference ownership is passed to the
4779 PLyUnicode_Bytes(PyObject *unicode)
4782 const char *serverenc;
4785 * Python understands almost all PostgreSQL encoding names, but it doesn't
4788 if (GetDatabaseEncoding() == PG_SQL_ASCII)
4789 serverenc = "ascii";
4791 serverenc = GetDatabaseEncodingName();
4792 rv = PyUnicode_AsEncodedString(unicode, serverenc, "strict");
4794 PLy_elog(ERROR, "could not convert Python Unicode object to PostgreSQL server encoding");
4799 * Convert a Python unicode object to a C string in PostgreSQL server
4800 * encoding. No Python object reference is passed out of this
4801 * function. The result is palloc'ed.
4803 * Note that this function is disguised as PyString_AsString() when
4804 * using Python 3. That function retuns a pointer into the internal
4805 * memory of the argument, which isn't exactly the interface of this
4806 * function. But in either case you get a rather short-lived
4807 * reference that you ought to better leave alone.
4810 PLyUnicode_AsString(PyObject *unicode)
4812 PyObject *o = PLyUnicode_Bytes(unicode);
4813 char *rv = pstrdup(PyBytes_AsString(o));
4819 #if PY_MAJOR_VERSION >= 3
4821 * Convert a C string in the PostgreSQL server encoding to a Python
4822 * unicode object. Reference ownership is passed to the caller.
4825 PLyUnicode_FromString(const char *s)
4830 utf8string = (char *) pg_do_encoding_conversion((unsigned char *) s,
4832 GetDatabaseEncoding(),
4835 o = PyUnicode_FromString(utf8string);
4837 if (utf8string != s)
4842 #endif /* PY_MAJOR_VERSION >= 3 */
4844 #if PY_MAJOR_VERSION < 3
4846 /* Define aliases plpython2_call_handler etc */
4847 Datum plpython2_call_handler(PG_FUNCTION_ARGS);
4848 Datum plpython2_inline_handler(PG_FUNCTION_ARGS);
4849 Datum plpython2_validator(PG_FUNCTION_ARGS);
4851 PG_FUNCTION_INFO_V1(plpython2_call_handler);
4854 plpython2_call_handler(PG_FUNCTION_ARGS)
4856 return plpython_call_handler(fcinfo);
4859 PG_FUNCTION_INFO_V1(plpython2_inline_handler);
4862 plpython2_inline_handler(PG_FUNCTION_ARGS)
4864 return plpython_inline_handler(fcinfo);
4867 PG_FUNCTION_INFO_V1(plpython2_validator);
4870 plpython2_validator(PG_FUNCTION_ARGS)
4872 return plpython_validator(fcinfo);
4875 #endif /* PY_MAJOR_VERSION < 3 */