Line data Source code
1 : /* module.c - the module itself
2 : *
3 : * Copyright (C) 2004-2010 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 :
24 : #include "connection.h"
25 : #include "statement.h"
26 : #include "cursor.h"
27 : #include "cache.h"
28 : #include "prepare_protocol.h"
29 : #include "microprotocols.h"
30 : #include "row.h"
31 :
32 : #if SQLITE_VERSION_NUMBER >= 3003003
33 : #define HAVE_SHARED_CACHE
34 : #endif
35 :
36 : /* static objects at module-level */
37 :
38 : PyObject* pysqlite_Error, *pysqlite_Warning, *pysqlite_InterfaceError, *pysqlite_DatabaseError,
39 : *pysqlite_InternalError, *pysqlite_OperationalError, *pysqlite_ProgrammingError,
40 : *pysqlite_IntegrityError, *pysqlite_DataError, *pysqlite_NotSupportedError;
41 :
42 : PyObject* converters;
43 : int _enable_callback_tracebacks;
44 : int pysqlite_BaseTypeAdapted;
45 :
46 0 : static PyObject* module_connect(PyObject* self, PyObject* args, PyObject*
47 : kwargs)
48 : {
49 : /* Python seems to have no way of extracting a single keyword-arg at
50 : * C-level, so this code is redundant with the one in connection_init in
51 : * connection.c and must always be copied from there ... */
52 :
53 : static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL};
54 : char* database;
55 0 : int detect_types = 0;
56 : PyObject* isolation_level;
57 0 : PyObject* factory = NULL;
58 0 : int check_same_thread = 1;
59 : int cached_statements;
60 0 : double timeout = 5.0;
61 :
62 : PyObject* result;
63 :
64 0 : if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist,
65 : &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
66 : {
67 0 : return NULL;
68 : }
69 :
70 0 : if (factory == NULL) {
71 0 : factory = (PyObject*)&pysqlite_ConnectionType;
72 : }
73 :
74 0 : result = PyObject_Call(factory, args, kwargs);
75 :
76 0 : return result;
77 : }
78 :
79 : PyDoc_STRVAR(module_connect_doc,
80 : "connect(database[, timeout, isolation_level, detect_types, factory])\n\
81 : \n\
82 : Opens a connection to the SQLite database file *database*. You can use\n\
83 : \":memory:\" to open a database connection to a database that resides in\n\
84 : RAM instead of on disk.");
85 :
86 0 : static PyObject* module_complete(PyObject* self, PyObject* args, PyObject*
87 : kwargs)
88 : {
89 : static char *kwlist[] = {"statement", NULL, NULL};
90 : char* statement;
91 :
92 : PyObject* result;
93 :
94 0 : if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement))
95 : {
96 0 : return NULL;
97 : }
98 :
99 0 : if (sqlite3_complete(statement)) {
100 0 : result = Py_True;
101 : } else {
102 0 : result = Py_False;
103 : }
104 :
105 0 : Py_INCREF(result);
106 :
107 0 : return result;
108 : }
109 :
110 : PyDoc_STRVAR(module_complete_doc,
111 : "complete_statement(sql)\n\
112 : \n\
113 : Checks if a string contains a complete SQL statement. Non-standard.");
114 :
115 : #ifdef HAVE_SHARED_CACHE
116 0 : static PyObject* module_enable_shared_cache(PyObject* self, PyObject* args, PyObject*
117 : kwargs)
118 : {
119 : static char *kwlist[] = {"do_enable", NULL, NULL};
120 : int do_enable;
121 : int rc;
122 :
123 0 : if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist, &do_enable))
124 : {
125 0 : return NULL;
126 : }
127 :
128 0 : rc = sqlite3_enable_shared_cache(do_enable);
129 :
130 0 : if (rc != SQLITE_OK) {
131 0 : PyErr_SetString(pysqlite_OperationalError, "Changing the shared_cache flag failed");
132 0 : return NULL;
133 : } else {
134 0 : Py_INCREF(Py_None);
135 0 : return Py_None;
136 : }
137 : }
138 :
139 : PyDoc_STRVAR(module_enable_shared_cache_doc,
140 : "enable_shared_cache(do_enable)\n\
141 : \n\
142 : Enable or disable shared cache mode for the calling thread.\n\
143 : Experimental/Non-standard.");
144 : #endif /* HAVE_SHARED_CACHE */
145 :
146 0 : static PyObject* module_register_adapter(PyObject* self, PyObject* args)
147 : {
148 : PyTypeObject* type;
149 : PyObject* caster;
150 : int rc;
151 :
152 0 : if (!PyArg_ParseTuple(args, "OO", &type, &caster)) {
153 0 : return NULL;
154 : }
155 :
156 : /* a basic type is adapted; there's a performance optimization if that's not the case
157 : * (99 % of all usages) */
158 0 : if (type == &PyLong_Type || type == &PyFloat_Type
159 0 : || type == &PyUnicode_Type || type == &PyByteArray_Type) {
160 0 : pysqlite_BaseTypeAdapted = 1;
161 : }
162 :
163 0 : rc = pysqlite_microprotocols_add(type, (PyObject*)&pysqlite_PrepareProtocolType, caster);
164 0 : if (rc == -1)
165 0 : return NULL;
166 :
167 0 : Py_INCREF(Py_None);
168 0 : return Py_None;
169 : }
170 :
171 : PyDoc_STRVAR(module_register_adapter_doc,
172 : "register_adapter(type, callable)\n\
173 : \n\
174 : Registers an adapter with pysqlite's adapter registry. Non-standard.");
175 :
176 0 : static PyObject* module_register_converter(PyObject* self, PyObject* args)
177 : {
178 : PyObject* orig_name;
179 0 : PyObject* name = NULL;
180 : PyObject* callable;
181 0 : PyObject* retval = NULL;
182 : _Py_IDENTIFIER(upper);
183 :
184 0 : if (!PyArg_ParseTuple(args, "UO", &orig_name, &callable)) {
185 0 : return NULL;
186 : }
187 :
188 : /* convert the name to upper case */
189 0 : name = _PyObject_CallMethodId(orig_name, &PyId_upper, "");
190 0 : if (!name) {
191 0 : goto error;
192 : }
193 :
194 0 : if (PyDict_SetItem(converters, name, callable) != 0) {
195 0 : goto error;
196 : }
197 :
198 0 : Py_INCREF(Py_None);
199 0 : retval = Py_None;
200 : error:
201 0 : Py_XDECREF(name);
202 0 : return retval;
203 : }
204 :
205 : PyDoc_STRVAR(module_register_converter_doc,
206 : "register_converter(typename, callable)\n\
207 : \n\
208 : Registers a converter with pysqlite. Non-standard.");
209 :
210 0 : static PyObject* enable_callback_tracebacks(PyObject* self, PyObject* args)
211 : {
212 0 : if (!PyArg_ParseTuple(args, "i", &_enable_callback_tracebacks)) {
213 0 : return NULL;
214 : }
215 :
216 0 : Py_INCREF(Py_None);
217 0 : return Py_None;
218 : }
219 :
220 : PyDoc_STRVAR(enable_callback_tracebacks_doc,
221 : "enable_callback_tracebacks(flag)\n\
222 : \n\
223 : Enable or disable callback functions throwing errors to stderr.");
224 :
225 0 : static void converters_init(PyObject* dict)
226 : {
227 0 : converters = PyDict_New();
228 0 : if (!converters) {
229 0 : return;
230 : }
231 :
232 0 : PyDict_SetItemString(dict, "converters", converters);
233 : }
234 :
235 : static PyMethodDef module_methods[] = {
236 : {"connect", (PyCFunction)module_connect,
237 : METH_VARARGS | METH_KEYWORDS, module_connect_doc},
238 : {"complete_statement", (PyCFunction)module_complete,
239 : METH_VARARGS | METH_KEYWORDS, module_complete_doc},
240 : #ifdef HAVE_SHARED_CACHE
241 : {"enable_shared_cache", (PyCFunction)module_enable_shared_cache,
242 : METH_VARARGS | METH_KEYWORDS, module_enable_shared_cache_doc},
243 : #endif
244 : {"register_adapter", (PyCFunction)module_register_adapter,
245 : METH_VARARGS, module_register_adapter_doc},
246 : {"register_converter", (PyCFunction)module_register_converter,
247 : METH_VARARGS, module_register_converter_doc},
248 : {"adapt", (PyCFunction)pysqlite_adapt, METH_VARARGS,
249 : pysqlite_adapt_doc},
250 : {"enable_callback_tracebacks", (PyCFunction)enable_callback_tracebacks,
251 : METH_VARARGS, enable_callback_tracebacks_doc},
252 : {NULL, NULL}
253 : };
254 :
255 : struct _IntConstantPair {
256 : char* constant_name;
257 : int constant_value;
258 : };
259 :
260 : typedef struct _IntConstantPair IntConstantPair;
261 :
262 : static IntConstantPair _int_constants[] = {
263 : {"PARSE_DECLTYPES", PARSE_DECLTYPES},
264 : {"PARSE_COLNAMES", PARSE_COLNAMES},
265 :
266 : {"SQLITE_OK", SQLITE_OK},
267 : {"SQLITE_DENY", SQLITE_DENY},
268 : {"SQLITE_IGNORE", SQLITE_IGNORE},
269 : {"SQLITE_CREATE_INDEX", SQLITE_CREATE_INDEX},
270 : {"SQLITE_CREATE_TABLE", SQLITE_CREATE_TABLE},
271 : {"SQLITE_CREATE_TEMP_INDEX", SQLITE_CREATE_TEMP_INDEX},
272 : {"SQLITE_CREATE_TEMP_TABLE", SQLITE_CREATE_TEMP_TABLE},
273 : {"SQLITE_CREATE_TEMP_TRIGGER", SQLITE_CREATE_TEMP_TRIGGER},
274 : {"SQLITE_CREATE_TEMP_VIEW", SQLITE_CREATE_TEMP_VIEW},
275 : {"SQLITE_CREATE_TRIGGER", SQLITE_CREATE_TRIGGER},
276 : {"SQLITE_CREATE_VIEW", SQLITE_CREATE_VIEW},
277 : {"SQLITE_DELETE", SQLITE_DELETE},
278 : {"SQLITE_DROP_INDEX", SQLITE_DROP_INDEX},
279 : {"SQLITE_DROP_TABLE", SQLITE_DROP_TABLE},
280 : {"SQLITE_DROP_TEMP_INDEX", SQLITE_DROP_TEMP_INDEX},
281 : {"SQLITE_DROP_TEMP_TABLE", SQLITE_DROP_TEMP_TABLE},
282 : {"SQLITE_DROP_TEMP_TRIGGER", SQLITE_DROP_TEMP_TRIGGER},
283 : {"SQLITE_DROP_TEMP_VIEW", SQLITE_DROP_TEMP_VIEW},
284 : {"SQLITE_DROP_TRIGGER", SQLITE_DROP_TRIGGER},
285 : {"SQLITE_DROP_VIEW", SQLITE_DROP_VIEW},
286 : {"SQLITE_INSERT", SQLITE_INSERT},
287 : {"SQLITE_PRAGMA", SQLITE_PRAGMA},
288 : {"SQLITE_READ", SQLITE_READ},
289 : {"SQLITE_SELECT", SQLITE_SELECT},
290 : {"SQLITE_TRANSACTION", SQLITE_TRANSACTION},
291 : {"SQLITE_UPDATE", SQLITE_UPDATE},
292 : {"SQLITE_ATTACH", SQLITE_ATTACH},
293 : {"SQLITE_DETACH", SQLITE_DETACH},
294 : #if SQLITE_VERSION_NUMBER >= 3002001
295 : {"SQLITE_ALTER_TABLE", SQLITE_ALTER_TABLE},
296 : {"SQLITE_REINDEX", SQLITE_REINDEX},
297 : #endif
298 : #if SQLITE_VERSION_NUMBER >= 3003000
299 : {"SQLITE_ANALYZE", SQLITE_ANALYZE},
300 : #endif
301 : {(char*)NULL, 0}
302 : };
303 :
304 :
305 : static struct PyModuleDef _sqlite3module = {
306 : PyModuleDef_HEAD_INIT,
307 : "_sqlite3",
308 : NULL,
309 : -1,
310 : module_methods,
311 : NULL,
312 : NULL,
313 : NULL,
314 : NULL
315 : };
316 :
317 0 : PyMODINIT_FUNC PyInit__sqlite3(void)
318 : {
319 : PyObject *module, *dict;
320 : PyObject *tmp_obj;
321 : int i;
322 :
323 0 : module = PyModule_Create(&_sqlite3module);
324 :
325 0 : if (!module ||
326 0 : (pysqlite_row_setup_types() < 0) ||
327 0 : (pysqlite_cursor_setup_types() < 0) ||
328 0 : (pysqlite_connection_setup_types() < 0) ||
329 0 : (pysqlite_cache_setup_types() < 0) ||
330 0 : (pysqlite_statement_setup_types() < 0) ||
331 0 : (pysqlite_prepare_protocol_setup_types() < 0)
332 : ) {
333 0 : Py_XDECREF(module);
334 0 : return NULL;
335 : }
336 :
337 0 : Py_INCREF(&pysqlite_ConnectionType);
338 0 : PyModule_AddObject(module, "Connection", (PyObject*) &pysqlite_ConnectionType);
339 0 : Py_INCREF(&pysqlite_CursorType);
340 0 : PyModule_AddObject(module, "Cursor", (PyObject*) &pysqlite_CursorType);
341 0 : Py_INCREF(&pysqlite_CacheType);
342 0 : PyModule_AddObject(module, "Statement", (PyObject*)&pysqlite_StatementType);
343 0 : Py_INCREF(&pysqlite_StatementType);
344 0 : PyModule_AddObject(module, "Cache", (PyObject*) &pysqlite_CacheType);
345 0 : Py_INCREF(&pysqlite_PrepareProtocolType);
346 0 : PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &pysqlite_PrepareProtocolType);
347 0 : Py_INCREF(&pysqlite_RowType);
348 0 : PyModule_AddObject(module, "Row", (PyObject*) &pysqlite_RowType);
349 :
350 0 : if (!(dict = PyModule_GetDict(module))) {
351 0 : goto error;
352 : }
353 :
354 : /*** Create DB-API Exception hierarchy */
355 :
356 0 : if (!(pysqlite_Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_Exception, NULL))) {
357 0 : goto error;
358 : }
359 0 : PyDict_SetItemString(dict, "Error", pysqlite_Error);
360 :
361 0 : if (!(pysqlite_Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_Exception, NULL))) {
362 0 : goto error;
363 : }
364 0 : PyDict_SetItemString(dict, "Warning", pysqlite_Warning);
365 :
366 : /* Error subclasses */
367 :
368 0 : if (!(pysqlite_InterfaceError = PyErr_NewException(MODULE_NAME ".InterfaceError", pysqlite_Error, NULL))) {
369 0 : goto error;
370 : }
371 0 : PyDict_SetItemString(dict, "InterfaceError", pysqlite_InterfaceError);
372 :
373 0 : if (!(pysqlite_DatabaseError = PyErr_NewException(MODULE_NAME ".DatabaseError", pysqlite_Error, NULL))) {
374 0 : goto error;
375 : }
376 0 : PyDict_SetItemString(dict, "DatabaseError", pysqlite_DatabaseError);
377 :
378 : /* pysqlite_DatabaseError subclasses */
379 :
380 0 : if (!(pysqlite_InternalError = PyErr_NewException(MODULE_NAME ".InternalError", pysqlite_DatabaseError, NULL))) {
381 0 : goto error;
382 : }
383 0 : PyDict_SetItemString(dict, "InternalError", pysqlite_InternalError);
384 :
385 0 : if (!(pysqlite_OperationalError = PyErr_NewException(MODULE_NAME ".OperationalError", pysqlite_DatabaseError, NULL))) {
386 0 : goto error;
387 : }
388 0 : PyDict_SetItemString(dict, "OperationalError", pysqlite_OperationalError);
389 :
390 0 : if (!(pysqlite_ProgrammingError = PyErr_NewException(MODULE_NAME ".ProgrammingError", pysqlite_DatabaseError, NULL))) {
391 0 : goto error;
392 : }
393 0 : PyDict_SetItemString(dict, "ProgrammingError", pysqlite_ProgrammingError);
394 :
395 0 : if (!(pysqlite_IntegrityError = PyErr_NewException(MODULE_NAME ".IntegrityError", pysqlite_DatabaseError,NULL))) {
396 0 : goto error;
397 : }
398 0 : PyDict_SetItemString(dict, "IntegrityError", pysqlite_IntegrityError);
399 :
400 0 : if (!(pysqlite_DataError = PyErr_NewException(MODULE_NAME ".DataError", pysqlite_DatabaseError, NULL))) {
401 0 : goto error;
402 : }
403 0 : PyDict_SetItemString(dict, "DataError", pysqlite_DataError);
404 :
405 0 : if (!(pysqlite_NotSupportedError = PyErr_NewException(MODULE_NAME ".NotSupportedError", pysqlite_DatabaseError, NULL))) {
406 0 : goto error;
407 : }
408 0 : PyDict_SetItemString(dict, "NotSupportedError", pysqlite_NotSupportedError);
409 :
410 : /* In Python 2.x, setting Connection.text_factory to
411 : OptimizedUnicode caused Unicode objects to be returned for
412 : non-ASCII data and bytestrings to be returned for ASCII data.
413 : Now OptimizedUnicode is an alias for str, so it has no
414 : effect. */
415 0 : Py_INCREF((PyObject*)&PyUnicode_Type);
416 0 : PyDict_SetItemString(dict, "OptimizedUnicode", (PyObject*)&PyUnicode_Type);
417 :
418 : /* Set integer constants */
419 0 : for (i = 0; _int_constants[i].constant_name != 0; i++) {
420 0 : tmp_obj = PyLong_FromLong(_int_constants[i].constant_value);
421 0 : if (!tmp_obj) {
422 0 : goto error;
423 : }
424 0 : PyDict_SetItemString(dict, _int_constants[i].constant_name, tmp_obj);
425 0 : Py_DECREF(tmp_obj);
426 : }
427 :
428 0 : if (!(tmp_obj = PyUnicode_FromString(PYSQLITE_VERSION))) {
429 0 : goto error;
430 : }
431 0 : PyDict_SetItemString(dict, "version", tmp_obj);
432 0 : Py_DECREF(tmp_obj);
433 :
434 0 : if (!(tmp_obj = PyUnicode_FromString(sqlite3_libversion()))) {
435 0 : goto error;
436 : }
437 0 : PyDict_SetItemString(dict, "sqlite_version", tmp_obj);
438 0 : Py_DECREF(tmp_obj);
439 :
440 : /* initialize microprotocols layer */
441 0 : pysqlite_microprotocols_init(dict);
442 :
443 : /* initialize the default converters */
444 0 : converters_init(dict);
445 :
446 0 : _enable_callback_tracebacks = 0;
447 :
448 0 : pysqlite_BaseTypeAdapted = 0;
449 :
450 : /* Original comment from _bsddb.c in the Python core. This is also still
451 : * needed nowadays for Python 2.3/2.4.
452 : *
453 : * PyEval_InitThreads is called here due to a quirk in python 1.5
454 : * - 2.2.1 (at least) according to Russell Williamson <merel@wt.net>:
455 : * The global interpreter lock is not initialized until the first
456 : * thread is created using thread.start_new_thread() or fork() is
457 : * called. that would cause the ALLOW_THREADS here to segfault due
458 : * to a null pointer reference if no threads or child processes
459 : * have been created. This works around that and is a no-op if
460 : * threads have already been initialized.
461 : * (see pybsddb-users mailing list post on 2002-08-07)
462 : */
463 : #ifdef WITH_THREAD
464 0 : PyEval_InitThreads();
465 : #endif
466 :
467 : error:
468 0 : if (PyErr_Occurred())
469 : {
470 0 : PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed");
471 0 : Py_DECREF(module);
472 0 : module = NULL;
473 : }
474 0 : return module;
475 : }
|