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