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