/Modules/_sqlite/module.c

http://unladen-swallow.googlecode.com/ · C · 457 lines · 330 code · 75 blank · 52 comment · 49 complexity · aeaa8e28eef299f063703d3b41f3ed7a MD5 · raw file

  1. /* module.c - the module itself
  2. *
  3. * Copyright (C) 2004-2007 Gerhard Häring <gh@ghaering.de>
  4. *
  5. * This file is part of pysqlite.
  6. *
  7. * This software is provided 'as-is', without any express or implied
  8. * warranty. In no event will the authors be held liable for any damages
  9. * arising from the use of this software.
  10. *
  11. * Permission is granted to anyone to use this software for any purpose,
  12. * including commercial applications, and to alter it and redistribute it
  13. * freely, subject to the following restrictions:
  14. *
  15. * 1. The origin of this software must not be misrepresented; you must not
  16. * claim that you wrote the original software. If you use this software
  17. * in a product, an acknowledgment in the product documentation would be
  18. * appreciated but is not required.
  19. * 2. Altered source versions must be plainly marked as such, and must not be
  20. * misrepresented as being the original software.
  21. * 3. This notice may not be removed or altered from any source distribution.
  22. */
  23. #include "connection.h"
  24. #include "statement.h"
  25. #include "cursor.h"
  26. #include "cache.h"
  27. #include "prepare_protocol.h"
  28. #include "microprotocols.h"
  29. #include "row.h"
  30. #if SQLITE_VERSION_NUMBER >= 3003003
  31. #define HAVE_SHARED_CACHE
  32. #endif
  33. /* static objects at module-level */
  34. PyObject* pysqlite_Error, *pysqlite_Warning, *pysqlite_InterfaceError, *pysqlite_DatabaseError,
  35. *pysqlite_InternalError, *pysqlite_OperationalError, *pysqlite_ProgrammingError,
  36. *pysqlite_IntegrityError, *pysqlite_DataError, *pysqlite_NotSupportedError, *pysqlite_OptimizedUnicode;
  37. PyObject* converters;
  38. int _enable_callback_tracebacks;
  39. int pysqlite_BaseTypeAdapted;
  40. static PyObject* module_connect(PyObject* self, PyObject* args, PyObject*
  41. kwargs)
  42. {
  43. /* Python seems to have no way of extracting a single keyword-arg at
  44. * C-level, so this code is redundant with the one in connection_init in
  45. * connection.c and must always be copied from there ... */
  46. static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL};
  47. PyObject* database;
  48. int detect_types = 0;
  49. PyObject* isolation_level;
  50. PyObject* factory = NULL;
  51. int check_same_thread = 1;
  52. int cached_statements;
  53. double timeout = 5.0;
  54. PyObject* result;
  55. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|diOiOi", kwlist,
  56. &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
  57. {
  58. return NULL;
  59. }
  60. if (factory == NULL) {
  61. factory = (PyObject*)&pysqlite_ConnectionType;
  62. }
  63. result = PyObject_Call(factory, args, kwargs);
  64. return result;
  65. }
  66. PyDoc_STRVAR(module_connect_doc,
  67. "connect(database[, timeout, isolation_level, detect_types, factory])\n\
  68. \n\
  69. Opens a connection to the SQLite database file *database*. You can use\n\
  70. \":memory:\" to open a database connection to a database that resides in\n\
  71. RAM instead of on disk.");
  72. static PyObject* module_complete(PyObject* self, PyObject* args, PyObject*
  73. kwargs)
  74. {
  75. static char *kwlist[] = {"statement", NULL, NULL};
  76. char* statement;
  77. PyObject* result;
  78. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement))
  79. {
  80. return NULL;
  81. }
  82. if (sqlite3_complete(statement)) {
  83. result = Py_True;
  84. } else {
  85. result = Py_False;
  86. }
  87. Py_INCREF(result);
  88. return result;
  89. }
  90. PyDoc_STRVAR(module_complete_doc,
  91. "complete_statement(sql)\n\
  92. \n\
  93. Checks if a string contains a complete SQL statement. Non-standard.");
  94. #ifdef HAVE_SHARED_CACHE
  95. static PyObject* module_enable_shared_cache(PyObject* self, PyObject* args, PyObject*
  96. kwargs)
  97. {
  98. static char *kwlist[] = {"do_enable", NULL, NULL};
  99. int do_enable;
  100. int rc;
  101. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist, &do_enable))
  102. {
  103. return NULL;
  104. }
  105. rc = sqlite3_enable_shared_cache(do_enable);
  106. if (rc != SQLITE_OK) {
  107. PyErr_SetString(pysqlite_OperationalError, "Changing the shared_cache flag failed");
  108. return NULL;
  109. } else {
  110. Py_INCREF(Py_None);
  111. return Py_None;
  112. }
  113. }
  114. PyDoc_STRVAR(module_enable_shared_cache_doc,
  115. "enable_shared_cache(do_enable)\n\
  116. \n\
  117. Enable or disable shared cache mode for the calling thread.\n\
  118. Experimental/Non-standard.");
  119. #endif /* HAVE_SHARED_CACHE */
  120. static PyObject* module_register_adapter(PyObject* self, PyObject* args)
  121. {
  122. PyTypeObject* type;
  123. PyObject* caster;
  124. int rc;
  125. if (!PyArg_ParseTuple(args, "OO", &type, &caster)) {
  126. return NULL;
  127. }
  128. /* a basic type is adapted; there's a performance optimization if that's not the case
  129. * (99 % of all usages) */
  130. if (type == &PyInt_Type || type == &PyLong_Type || type == &PyFloat_Type
  131. || type == &PyString_Type || type == &PyUnicode_Type || type == &PyBuffer_Type) {
  132. pysqlite_BaseTypeAdapted = 1;
  133. }
  134. rc = pysqlite_microprotocols_add(type, (PyObject*)&pysqlite_PrepareProtocolType, caster);
  135. if (rc == -1)
  136. return NULL;
  137. Py_INCREF(Py_None);
  138. return Py_None;
  139. }
  140. PyDoc_STRVAR(module_register_adapter_doc,
  141. "register_adapter(type, callable)\n\
  142. \n\
  143. Registers an adapter with pysqlite's adapter registry. Non-standard.");
  144. static PyObject* module_register_converter(PyObject* self, PyObject* args)
  145. {
  146. PyObject* orig_name;
  147. PyObject* name = NULL;
  148. PyObject* callable;
  149. PyObject* retval = NULL;
  150. if (!PyArg_ParseTuple(args, "SO", &orig_name, &callable)) {
  151. return NULL;
  152. }
  153. /* convert the name to upper case */
  154. name = PyObject_CallMethod(orig_name, "upper", "");
  155. if (!name) {
  156. goto error;
  157. }
  158. if (PyDict_SetItem(converters, name, callable) != 0) {
  159. goto error;
  160. }
  161. Py_INCREF(Py_None);
  162. retval = Py_None;
  163. error:
  164. Py_XDECREF(name);
  165. return retval;
  166. }
  167. PyDoc_STRVAR(module_register_converter_doc,
  168. "register_converter(typename, callable)\n\
  169. \n\
  170. Registers a converter with pysqlite. Non-standard.");
  171. static PyObject* enable_callback_tracebacks(PyObject* self, PyObject* args)
  172. {
  173. if (!PyArg_ParseTuple(args, "i", &_enable_callback_tracebacks)) {
  174. return NULL;
  175. }
  176. Py_INCREF(Py_None);
  177. return Py_None;
  178. }
  179. PyDoc_STRVAR(enable_callback_tracebacks_doc,
  180. "enable_callback_tracebacks(flag)\n\
  181. \n\
  182. Enable or disable callback functions throwing errors to stderr.");
  183. static void converters_init(PyObject* dict)
  184. {
  185. converters = PyDict_New();
  186. if (!converters) {
  187. return;
  188. }
  189. PyDict_SetItemString(dict, "converters", converters);
  190. }
  191. static PyMethodDef module_methods[] = {
  192. {"connect", (PyCFunction)module_connect,
  193. METH_VARARGS | METH_KEYWORDS, module_connect_doc},
  194. {"complete_statement", (PyCFunction)module_complete,
  195. METH_VARARGS | METH_KEYWORDS, module_complete_doc},
  196. #ifdef HAVE_SHARED_CACHE
  197. {"enable_shared_cache", (PyCFunction)module_enable_shared_cache,
  198. METH_VARARGS | METH_KEYWORDS, module_enable_shared_cache_doc},
  199. #endif
  200. {"register_adapter", (PyCFunction)module_register_adapter,
  201. METH_VARARGS, module_register_adapter_doc},
  202. {"register_converter", (PyCFunction)module_register_converter,
  203. METH_VARARGS, module_register_converter_doc},
  204. {"adapt", (PyCFunction)pysqlite_adapt, METH_VARARGS,
  205. pysqlite_adapt_doc},
  206. {"enable_callback_tracebacks", (PyCFunction)enable_callback_tracebacks,
  207. METH_VARARGS, enable_callback_tracebacks_doc},
  208. {NULL, NULL}
  209. };
  210. struct _IntConstantPair {
  211. char* constant_name;
  212. int constant_value;
  213. };
  214. typedef struct _IntConstantPair IntConstantPair;
  215. static IntConstantPair _int_constants[] = {
  216. {"PARSE_DECLTYPES", PARSE_DECLTYPES},
  217. {"PARSE_COLNAMES", PARSE_COLNAMES},
  218. {"SQLITE_OK", SQLITE_OK},
  219. {"SQLITE_DENY", SQLITE_DENY},
  220. {"SQLITE_IGNORE", SQLITE_IGNORE},
  221. {"SQLITE_CREATE_INDEX", SQLITE_CREATE_INDEX},
  222. {"SQLITE_CREATE_TABLE", SQLITE_CREATE_TABLE},
  223. {"SQLITE_CREATE_TEMP_INDEX", SQLITE_CREATE_TEMP_INDEX},
  224. {"SQLITE_CREATE_TEMP_TABLE", SQLITE_CREATE_TEMP_TABLE},
  225. {"SQLITE_CREATE_TEMP_TRIGGER", SQLITE_CREATE_TEMP_TRIGGER},
  226. {"SQLITE_CREATE_TEMP_VIEW", SQLITE_CREATE_TEMP_VIEW},
  227. {"SQLITE_CREATE_TRIGGER", SQLITE_CREATE_TRIGGER},
  228. {"SQLITE_CREATE_VIEW", SQLITE_CREATE_VIEW},
  229. {"SQLITE_DELETE", SQLITE_DELETE},
  230. {"SQLITE_DROP_INDEX", SQLITE_DROP_INDEX},
  231. {"SQLITE_DROP_TABLE", SQLITE_DROP_TABLE},
  232. {"SQLITE_DROP_TEMP_INDEX", SQLITE_DROP_TEMP_INDEX},
  233. {"SQLITE_DROP_TEMP_TABLE", SQLITE_DROP_TEMP_TABLE},
  234. {"SQLITE_DROP_TEMP_TRIGGER", SQLITE_DROP_TEMP_TRIGGER},
  235. {"SQLITE_DROP_TEMP_VIEW", SQLITE_DROP_TEMP_VIEW},
  236. {"SQLITE_DROP_TRIGGER", SQLITE_DROP_TRIGGER},
  237. {"SQLITE_DROP_VIEW", SQLITE_DROP_VIEW},
  238. {"SQLITE_INSERT", SQLITE_INSERT},
  239. {"SQLITE_PRAGMA", SQLITE_PRAGMA},
  240. {"SQLITE_READ", SQLITE_READ},
  241. {"SQLITE_SELECT", SQLITE_SELECT},
  242. {"SQLITE_TRANSACTION", SQLITE_TRANSACTION},
  243. {"SQLITE_UPDATE", SQLITE_UPDATE},
  244. {"SQLITE_ATTACH", SQLITE_ATTACH},
  245. {"SQLITE_DETACH", SQLITE_DETACH},
  246. #if SQLITE_VERSION_NUMBER >= 3002001
  247. {"SQLITE_ALTER_TABLE", SQLITE_ALTER_TABLE},
  248. {"SQLITE_REINDEX", SQLITE_REINDEX},
  249. #endif
  250. #if SQLITE_VERSION_NUMBER >= 3003000
  251. {"SQLITE_ANALYZE", SQLITE_ANALYZE},
  252. #endif
  253. {(char*)NULL, 0}
  254. };
  255. PyMODINIT_FUNC init_sqlite3(void)
  256. {
  257. PyObject *module, *dict;
  258. PyObject *tmp_obj;
  259. int i;
  260. module = Py_InitModule("_sqlite3", module_methods);
  261. if (!module ||
  262. (pysqlite_row_setup_types() < 0) ||
  263. (pysqlite_cursor_setup_types() < 0) ||
  264. (pysqlite_connection_setup_types() < 0) ||
  265. (pysqlite_cache_setup_types() < 0) ||
  266. (pysqlite_statement_setup_types() < 0) ||
  267. (pysqlite_prepare_protocol_setup_types() < 0)
  268. ) {
  269. return;
  270. }
  271. Py_INCREF(&pysqlite_ConnectionType);
  272. PyModule_AddObject(module, "Connection", (PyObject*) &pysqlite_ConnectionType);
  273. Py_INCREF(&pysqlite_CursorType);
  274. PyModule_AddObject(module, "Cursor", (PyObject*) &pysqlite_CursorType);
  275. Py_INCREF(&pysqlite_CacheType);
  276. PyModule_AddObject(module, "Statement", (PyObject*)&pysqlite_StatementType);
  277. Py_INCREF(&pysqlite_StatementType);
  278. PyModule_AddObject(module, "Cache", (PyObject*) &pysqlite_CacheType);
  279. Py_INCREF(&pysqlite_PrepareProtocolType);
  280. PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &pysqlite_PrepareProtocolType);
  281. Py_INCREF(&pysqlite_RowType);
  282. PyModule_AddObject(module, "Row", (PyObject*) &pysqlite_RowType);
  283. if (!(dict = PyModule_GetDict(module))) {
  284. goto error;
  285. }
  286. /*** Create DB-API Exception hierarchy */
  287. if (!(pysqlite_Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_StandardError, NULL))) {
  288. goto error;
  289. }
  290. PyDict_SetItemString(dict, "Error", pysqlite_Error);
  291. if (!(pysqlite_Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_StandardError, NULL))) {
  292. goto error;
  293. }
  294. PyDict_SetItemString(dict, "Warning", pysqlite_Warning);
  295. /* Error subclasses */
  296. if (!(pysqlite_InterfaceError = PyErr_NewException(MODULE_NAME ".InterfaceError", pysqlite_Error, NULL))) {
  297. goto error;
  298. }
  299. PyDict_SetItemString(dict, "InterfaceError", pysqlite_InterfaceError);
  300. if (!(pysqlite_DatabaseError = PyErr_NewException(MODULE_NAME ".DatabaseError", pysqlite_Error, NULL))) {
  301. goto error;
  302. }
  303. PyDict_SetItemString(dict, "DatabaseError", pysqlite_DatabaseError);
  304. /* pysqlite_DatabaseError subclasses */
  305. if (!(pysqlite_InternalError = PyErr_NewException(MODULE_NAME ".InternalError", pysqlite_DatabaseError, NULL))) {
  306. goto error;
  307. }
  308. PyDict_SetItemString(dict, "InternalError", pysqlite_InternalError);
  309. if (!(pysqlite_OperationalError = PyErr_NewException(MODULE_NAME ".OperationalError", pysqlite_DatabaseError, NULL))) {
  310. goto error;
  311. }
  312. PyDict_SetItemString(dict, "OperationalError", pysqlite_OperationalError);
  313. if (!(pysqlite_ProgrammingError = PyErr_NewException(MODULE_NAME ".ProgrammingError", pysqlite_DatabaseError, NULL))) {
  314. goto error;
  315. }
  316. PyDict_SetItemString(dict, "ProgrammingError", pysqlite_ProgrammingError);
  317. if (!(pysqlite_IntegrityError = PyErr_NewException(MODULE_NAME ".IntegrityError", pysqlite_DatabaseError,NULL))) {
  318. goto error;
  319. }
  320. PyDict_SetItemString(dict, "IntegrityError", pysqlite_IntegrityError);
  321. if (!(pysqlite_DataError = PyErr_NewException(MODULE_NAME ".DataError", pysqlite_DatabaseError, NULL))) {
  322. goto error;
  323. }
  324. PyDict_SetItemString(dict, "DataError", pysqlite_DataError);
  325. if (!(pysqlite_NotSupportedError = PyErr_NewException(MODULE_NAME ".NotSupportedError", pysqlite_DatabaseError, NULL))) {
  326. goto error;
  327. }
  328. PyDict_SetItemString(dict, "NotSupportedError", pysqlite_NotSupportedError);
  329. /* We just need "something" unique for pysqlite_OptimizedUnicode. It does not really
  330. * need to be a string subclass. Just anything that can act as a special
  331. * marker for us. So I pulled PyCell_Type out of my magic hat.
  332. */
  333. Py_INCREF((PyObject*)&PyCell_Type);
  334. pysqlite_OptimizedUnicode = (PyObject*)&PyCell_Type;
  335. PyDict_SetItemString(dict, "OptimizedUnicode", pysqlite_OptimizedUnicode);
  336. /* Set integer constants */
  337. for (i = 0; _int_constants[i].constant_name != 0; i++) {
  338. tmp_obj = PyInt_FromLong(_int_constants[i].constant_value);
  339. if (!tmp_obj) {
  340. goto error;
  341. }
  342. PyDict_SetItemString(dict, _int_constants[i].constant_name, tmp_obj);
  343. Py_DECREF(tmp_obj);
  344. }
  345. if (!(tmp_obj = PyString_FromString(PYSQLITE_VERSION))) {
  346. goto error;
  347. }
  348. PyDict_SetItemString(dict, "version", tmp_obj);
  349. Py_DECREF(tmp_obj);
  350. if (!(tmp_obj = PyString_FromString(sqlite3_libversion()))) {
  351. goto error;
  352. }
  353. PyDict_SetItemString(dict, "sqlite_version", tmp_obj);
  354. Py_DECREF(tmp_obj);
  355. /* initialize microprotocols layer */
  356. pysqlite_microprotocols_init(dict);
  357. /* initialize the default converters */
  358. converters_init(dict);
  359. _enable_callback_tracebacks = 0;
  360. pysqlite_BaseTypeAdapted = 0;
  361. /* Original comment from _bsddb.c in the Python core. This is also still
  362. * needed nowadays for Python 2.3/2.4.
  363. *
  364. * PyEval_InitThreads is called here due to a quirk in python 1.5
  365. * - 2.2.1 (at least) according to Russell Williamson <merel@wt.net>:
  366. * The global interpreter lock is not initialized until the first
  367. * thread is created using thread.start_new_thread() or fork() is
  368. * called. that would cause the ALLOW_THREADS here to segfault due
  369. * to a null pointer reference if no threads or child processes
  370. * have been created. This works around that and is a no-op if
  371. * threads have already been initialized.
  372. * (see pybsddb-users mailing list post on 2002-08-07)
  373. */
  374. #ifdef WITH_THREAD
  375. PyEval_InitThreads();
  376. #endif
  377. error:
  378. if (PyErr_Occurred())
  379. {
  380. PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed");
  381. }
  382. }