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