4 * src/pl/plpython/plpy_plpymodule.c
9 #include "mb/pg_wchar.h"
10 #include "utils/builtins.h"
14 #include "plpy_plpymodule.h"
16 #include "plpy_cursorobject.h"
17 #include "plpy_elog.h"
18 #include "plpy_planobject.h"
19 #include "plpy_resultobject.h"
21 #include "plpy_subxactobject.h"
24 HTAB *PLy_spi_exceptions = NULL;
27 static void PLy_add_exceptions(PyObject *plpy);
28 static PyObject *PLy_create_exception(char *name,
29 PyObject *base, PyObject *dict,
30 const char *modname, PyObject *mod);
31 static void PLy_generate_spi_exceptions(PyObject *mod, PyObject *base);
33 /* module functions */
34 static PyObject *PLy_debug(PyObject *self, PyObject *args, PyObject *kw);
35 static PyObject *PLy_log(PyObject *self, PyObject *args, PyObject *kw);
36 static PyObject *PLy_info(PyObject *self, PyObject *args, PyObject *kw);
37 static PyObject *PLy_notice(PyObject *self, PyObject *args, PyObject *kw);
38 static PyObject *PLy_warning(PyObject *self, PyObject *args, PyObject *kw);
39 static PyObject *PLy_error(PyObject *self, PyObject *args, PyObject *kw);
40 static PyObject *PLy_fatal(PyObject *self, PyObject *args, PyObject *kw);
41 static PyObject *PLy_quote_literal(PyObject *self, PyObject *args);
42 static PyObject *PLy_quote_nullable(PyObject *self, PyObject *args);
43 static PyObject *PLy_quote_ident(PyObject *self, PyObject *args);
46 /* A list of all known exceptions, generated from backend/utils/errcodes.txt */
47 typedef struct ExceptionMap
54 static const ExceptionMap exception_map[] = {
55 #include "spiexceptions.h"
59 static PyMethodDef PLy_methods[] = {
63 {"debug", (PyCFunction) PLy_debug, METH_VARARGS | METH_KEYWORDS, NULL},
64 {"log", (PyCFunction) PLy_log, METH_VARARGS | METH_KEYWORDS, NULL},
65 {"info", (PyCFunction) PLy_info, METH_VARARGS | METH_KEYWORDS, NULL},
66 {"notice", (PyCFunction) PLy_notice, METH_VARARGS | METH_KEYWORDS, NULL},
67 {"warning", (PyCFunction) PLy_warning, METH_VARARGS | METH_KEYWORDS, NULL},
68 {"error", (PyCFunction) PLy_error, METH_VARARGS | METH_KEYWORDS, NULL},
69 {"fatal", (PyCFunction) PLy_fatal, METH_VARARGS | METH_KEYWORDS, NULL},
72 * create a stored plan
74 {"prepare", PLy_spi_prepare, METH_VARARGS, NULL},
77 * execute a plan or query
79 {"execute", PLy_spi_execute, METH_VARARGS, NULL},
84 {"quote_literal", PLy_quote_literal, METH_VARARGS, NULL},
85 {"quote_nullable", PLy_quote_nullable, METH_VARARGS, NULL},
86 {"quote_ident", PLy_quote_ident, METH_VARARGS, NULL},
89 * create the subtransaction context manager
91 {"subtransaction", PLy_subtransaction_new, METH_NOARGS, NULL},
96 {"cursor", PLy_cursor, METH_VARARGS, NULL},
101 static PyMethodDef PLy_exc_methods[] = {
102 {NULL, NULL, 0, NULL}
105 #if PY_MAJOR_VERSION >= 3
106 static PyModuleDef PLy_module = {
107 PyModuleDef_HEAD_INIT, /* m_base */
111 PLy_methods, /* m_methods */
114 static PyModuleDef PLy_exc_module = {
115 PyModuleDef_HEAD_INIT, /* m_base */
116 "spiexceptions", /* m_name */
119 PLy_exc_methods, /* m_methods */
121 NULL, /* m_traverse */
127 * Must have external linkage, because PyMODINIT_FUNC does dllexport on
128 * Windows-like platforms.
135 m = PyModule_Create(&PLy_module);
139 PLy_add_exceptions(m);
143 #endif /* PY_MAJOR_VERSION >= 3 */
152 #if PY_MAJOR_VERSION < 3
157 * initialize plpy module
159 PLy_plan_init_type();
160 PLy_result_init_type();
161 PLy_subtransaction_init_type();
162 PLy_cursor_init_type();
164 #if PY_MAJOR_VERSION >= 3
165 PyModule_Create(&PLy_module);
166 /* for Python 3 we initialized the exceptions in PyInit_plpy */
168 plpy = Py_InitModule("plpy", PLy_methods);
169 PLy_add_exceptions(plpy);
172 /* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */
175 * initialize main module, and add plpy
177 main_mod = PyImport_AddModule("__main__");
178 main_dict = PyModule_GetDict(main_mod);
179 plpy_mod = PyImport_AddModule("plpy");
180 if (plpy_mod == NULL)
181 PLy_elog(ERROR, "could not import \"plpy\" module");
182 PyDict_SetItemString(main_dict, "plpy", plpy_mod);
183 if (PyErr_Occurred())
184 PLy_elog(ERROR, "could not import \"plpy\" module");
188 PLy_add_exceptions(PyObject *plpy)
193 #if PY_MAJOR_VERSION < 3
194 excmod = Py_InitModule("spiexceptions", PLy_exc_methods);
196 excmod = PyModule_Create(&PLy_exc_module);
199 PLy_elog(ERROR, "could not create the spiexceptions module");
202 * PyModule_AddObject does not add a refcount to the object, for some odd
203 * reason; we must do that.
206 if (PyModule_AddObject(plpy, "spiexceptions", excmod) < 0)
207 PLy_elog(ERROR, "could not add the spiexceptions module");
209 PLy_exc_error = PLy_create_exception("plpy.Error", NULL, NULL,
211 PLy_exc_fatal = PLy_create_exception("plpy.Fatal", NULL, NULL,
213 PLy_exc_spi_error = PLy_create_exception("plpy.SPIError", NULL, NULL,
216 memset(&hash_ctl, 0, sizeof(hash_ctl));
217 hash_ctl.keysize = sizeof(int);
218 hash_ctl.entrysize = sizeof(PLyExceptionEntry);
219 PLy_spi_exceptions = hash_create("PL/Python SPI exceptions", 256,
220 &hash_ctl, HASH_ELEM | HASH_BLOBS);
222 PLy_generate_spi_exceptions(excmod, PLy_exc_spi_error);
226 * Create an exception object and add it to the module
229 PLy_create_exception(char *name, PyObject *base, PyObject *dict,
230 const char *modname, PyObject *mod)
234 exc = PyErr_NewException(name, base, dict);
236 PLy_elog(ERROR, "could not create exception \"%s\"", name);
239 * PyModule_AddObject does not add a refcount to the object, for some odd
240 * reason; we must do that.
243 PyModule_AddObject(mod, modname, exc);
246 * The caller will also store a pointer to the exception object in some
247 * permanent variable, so add another ref to account for that. This is
248 * probably excessively paranoid, but let's be sure.
255 * Add all the autogenerated exceptions as subclasses of SPIError
258 PLy_generate_spi_exceptions(PyObject *mod, PyObject *base)
262 for (i = 0; exception_map[i].name != NULL; i++)
266 PLyExceptionEntry *entry;
268 PyObject *dict = PyDict_New();
271 PLy_elog(ERROR, "could not generate SPI exceptions");
273 sqlstate = PyString_FromString(unpack_sql_state(exception_map[i].sqlstate));
274 if (sqlstate == NULL)
275 PLy_elog(ERROR, "could not generate SPI exceptions");
277 PyDict_SetItemString(dict, "sqlstate", sqlstate);
280 exc = PLy_create_exception(exception_map[i].name, base, dict,
281 exception_map[i].classname, mod);
283 entry = hash_search(PLy_spi_exceptions, &exception_map[i].sqlstate,
292 * the python interface to the elog function
293 * don't confuse these with PLy_elog
295 static PyObject *PLy_output(volatile int level, PyObject *self,
296 PyObject *args, PyObject *kw);
299 PLy_debug(PyObject *self, PyObject *args, PyObject *kw)
301 return PLy_output(DEBUG2, self, args, kw);
305 PLy_log(PyObject *self, PyObject *args, PyObject *kw)
307 return PLy_output(LOG, self, args, kw);
311 PLy_info(PyObject *self, PyObject *args, PyObject *kw)
313 return PLy_output(INFO, self, args, kw);
317 PLy_notice(PyObject *self, PyObject *args, PyObject *kw)
319 return PLy_output(NOTICE, self, args, kw);
323 PLy_warning(PyObject *self, PyObject *args, PyObject *kw)
325 return PLy_output(WARNING, self, args, kw);
329 PLy_error(PyObject *self, PyObject *args, PyObject *kw)
331 return PLy_output(ERROR, self, args, kw);
335 PLy_fatal(PyObject *self, PyObject *args, PyObject *kw)
337 return PLy_output(FATAL, self, args, kw);
341 PLy_quote_literal(PyObject *self, PyObject *args)
347 if (!PyArg_ParseTuple(args, "s:quote_literal", &str))
350 quoted = quote_literal_cstr(str);
351 ret = PyString_FromString(quoted);
358 PLy_quote_nullable(PyObject *self, PyObject *args)
364 if (!PyArg_ParseTuple(args, "z:quote_nullable", &str))
368 return PyString_FromString("NULL");
370 quoted = quote_literal_cstr(str);
371 ret = PyString_FromString(quoted);
378 PLy_quote_ident(PyObject *self, PyObject *args)
384 if (!PyArg_ParseTuple(args, "s:quote_ident", &str))
387 quoted = quote_identifier(str);
388 ret = PyString_FromString(quoted);
393 /* enforce cast of object to string */
395 object_to_string(PyObject *obj)
399 PyObject *so = PyObject_Str(obj);
405 str = pstrdup(PyString_AsString(so));
416 PLy_output(volatile int level, PyObject *self, PyObject *args, PyObject *kw)
419 char *volatile sqlstatestr = NULL;
420 char *volatile message = NULL;
421 char *volatile detail = NULL;
422 char *volatile hint = NULL;
423 char *volatile column_name = NULL;
424 char *volatile constraint_name = NULL;
425 char *volatile datatype_name = NULL;
426 char *volatile table_name = NULL;
427 char *volatile schema_name = NULL;
428 volatile MemoryContext oldcontext;
431 PyObject *volatile so;
434 if (PyTuple_Size(args) == 1)
437 * Treat single argument specially to avoid undesirable ('tuple',)
442 if (!PyArg_UnpackTuple(args, "plpy.elog", 1, 1, &o))
443 PLy_elog(ERROR, "could not unpack arguments in plpy.elog");
444 so = PyObject_Str(o);
447 so = PyObject_Str(args);
449 if (so == NULL || ((message = PyString_AsString(so)) == NULL))
452 message = dgettext(TEXTDOMAIN, "could not parse error message in plpy.elog");
454 message = pstrdup(message);
460 while (PyDict_Next(kw, &pos, &key, &value))
462 char *keyword = PyString_AsString(key);
464 if (strcmp(keyword, "message") == 0)
466 /* the message should not be overwriten */
467 if (PyTuple_Size(args) != 0)
469 PLy_exception_set(PyExc_TypeError, "Argument 'message' given by name and position");
475 message = object_to_string(value);
477 else if (strcmp(keyword, "detail") == 0)
478 detail = object_to_string(value);
479 else if (strcmp(keyword, "hint") == 0)
480 hint = object_to_string(value);
481 else if (strcmp(keyword, "sqlstate") == 0)
482 sqlstatestr = object_to_string(value);
483 else if (strcmp(keyword, "schema_name") == 0)
484 schema_name = object_to_string(value);
485 else if (strcmp(keyword, "table_name") == 0)
486 table_name = object_to_string(value);
487 else if (strcmp(keyword, "column_name") == 0)
488 column_name = object_to_string(value);
489 else if (strcmp(keyword, "datatype_name") == 0)
490 datatype_name = object_to_string(value);
491 else if (strcmp(keyword, "constraint_name") == 0)
492 constraint_name = object_to_string(value);
495 PLy_exception_set(PyExc_TypeError,
496 "'%s' is an invalid keyword argument for this function",
503 if (sqlstatestr != NULL)
505 if (strlen(sqlstatestr) != 5)
507 PLy_exception_set(PyExc_ValueError, "invalid SQLSTATE code");
511 if (strspn(sqlstatestr, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") != 5)
513 PLy_exception_set(PyExc_ValueError, "invalid SQLSTATE code");
517 sqlstate = MAKE_SQLSTATE(sqlstatestr[0],
524 oldcontext = CurrentMemoryContext;
528 pg_verifymbstr(message, strlen(message), false);
530 pg_verifymbstr(detail, strlen(detail), false);
532 pg_verifymbstr(hint, strlen(hint), false);
533 if (schema_name != NULL)
534 pg_verifymbstr(schema_name, strlen(schema_name), false);
535 if (table_name != NULL)
536 pg_verifymbstr(table_name, strlen(table_name), false);
537 if (column_name != NULL)
538 pg_verifymbstr(column_name, strlen(column_name), false);
539 if (datatype_name != NULL)
540 pg_verifymbstr(datatype_name, strlen(datatype_name), false);
541 if (constraint_name != NULL)
542 pg_verifymbstr(constraint_name, strlen(constraint_name), false);
545 ((sqlstate != 0) ? errcode(sqlstate) : 0,
546 (message != NULL) ? errmsg_internal("%s", message) : 0,
547 (detail != NULL) ? errdetail_internal("%s", detail) : 0,
548 (hint != NULL) ? errhint("%s", hint) : 0,
549 (column_name != NULL) ?
550 err_generic_string(PG_DIAG_COLUMN_NAME, column_name) : 0,
551 (constraint_name != NULL) ?
552 err_generic_string(PG_DIAG_CONSTRAINT_NAME, constraint_name) : 0,
553 (datatype_name != NULL) ?
554 err_generic_string(PG_DIAG_DATATYPE_NAME, datatype_name) : 0,
555 (table_name != NULL) ?
556 err_generic_string(PG_DIAG_TABLE_NAME, table_name) : 0,
557 (schema_name != NULL) ?
558 err_generic_string(PG_DIAG_SCHEMA_NAME, schema_name) : 0));
564 MemoryContextSwitchTo(oldcontext);
565 edata = CopyErrorData();
568 PLy_exception_set_with_details(PLy_exc_error, edata);
569 FreeErrorData(edata);
576 * return a legal object so the interpreter will continue on its merry way