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