blob: 606454ca1f8b769469fc6b6dbeeb8872443607db [file] [log] [blame]
Gerhard Häring1541ef02006-06-13 22:24:47 +00001 /* module.c - the module itself
2 *
3 * Copyright (C) 2004-2006 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 */
Anthony Baxterc51ee692006-04-01 00:57:31 +000023
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
38PyObject* Error, *Warning, *InterfaceError, *DatabaseError, *InternalError,
39 *OperationalError, *ProgrammingError, *IntegrityError, *DataError,
40 *NotSupportedError, *OptimizedUnicode;
41
Anthony Baxterc51ee692006-04-01 00:57:31 +000042PyObject* converters;
Gerhard Häring1541ef02006-06-13 22:24:47 +000043int _enable_callback_tracebacks;
Anthony Baxterc51ee692006-04-01 00:57:31 +000044
45static PyObject* module_connect(PyObject* self, PyObject* args, PyObject*
46 kwargs)
47{
48 /* Python seems to have no way of extracting a single keyword-arg at
49 * C-level, so this code is redundant with the one in connection_init in
50 * connection.c and must always be copied from there ... */
51
52 static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL};
53 char* database;
54 int detect_types = 0;
55 PyObject* isolation_level;
56 PyObject* factory = NULL;
57 int check_same_thread = 1;
58 int cached_statements;
59 double timeout = 5.0;
60
61 PyObject* result;
62
63 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist,
64 &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
65 {
66 return NULL;
67 }
68
69 if (factory == NULL) {
70 factory = (PyObject*)&ConnectionType;
71 }
72
73 result = PyObject_Call(factory, args, kwargs);
74
75 return result;
76}
77
78static PyObject* module_complete(PyObject* self, PyObject* args, PyObject*
79 kwargs)
80{
81 static char *kwlist[] = {"statement", NULL, NULL};
82 char* statement;
83
84 PyObject* result;
85
86 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement))
87 {
88 return NULL;
89 }
90
91 if (sqlite3_complete(statement)) {
92 result = Py_True;
93 } else {
94 result = Py_False;
95 }
96
97 Py_INCREF(result);
98
99 return result;
100}
101
102#ifdef HAVE_SHARED_CACHE
103static PyObject* module_enable_shared_cache(PyObject* self, PyObject* args, PyObject*
104 kwargs)
105{
106 static char *kwlist[] = {"do_enable", NULL, NULL};
107 int do_enable;
108 int rc;
109
110 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist, &do_enable))
111 {
112 return NULL;
113 }
114
115 rc = sqlite3_enable_shared_cache(do_enable);
116
117 if (rc != SQLITE_OK) {
118 PyErr_SetString(OperationalError, "Changing the shared_cache flag failed");
119 return NULL;
120 } else {
121 Py_INCREF(Py_None);
122 return Py_None;
123 }
124}
125#endif /* HAVE_SHARED_CACHE */
126
127static PyObject* module_register_adapter(PyObject* self, PyObject* args, PyObject* kwargs)
128{
129 PyTypeObject* type;
130 PyObject* caster;
131
132 if (!PyArg_ParseTuple(args, "OO", &type, &caster)) {
133 return NULL;
134 }
135
136 microprotocols_add(type, (PyObject*)&SQLitePrepareProtocolType, caster);
137
138 Py_INCREF(Py_None);
139 return Py_None;
140}
141
142static PyObject* module_register_converter(PyObject* self, PyObject* args, PyObject* kwargs)
143{
Gerhard Häring1541ef02006-06-13 22:24:47 +0000144 char* orig_name;
145 char* name = NULL;
146 char* c;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000147 PyObject* callable;
Gerhard Häring1541ef02006-06-13 22:24:47 +0000148 PyObject* retval = NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000149
Gerhard Häring1541ef02006-06-13 22:24:47 +0000150 if (!PyArg_ParseTuple(args, "sO", &orig_name, &callable)) {
Anthony Baxterc51ee692006-04-01 00:57:31 +0000151 return NULL;
152 }
153
Gerhard Häring1541ef02006-06-13 22:24:47 +0000154 /* convert the name to lowercase */
155 name = PyMem_Malloc(strlen(orig_name) + 2);
156 if (!name) {
157 goto error;
158 }
159 strcpy(name, orig_name);
160 for (c = name; *c != (char)0; c++) {
161 *c = (*c) & 0xDF;
162 }
163
164 if (PyDict_SetItemString(converters, name, callable) != 0) {
165 goto error;
166 }
167
168 Py_INCREF(Py_None);
169 retval = Py_None;
170error:
171 if (name) {
172 PyMem_Free(name);
173 }
174 return retval;
175}
176
177static PyObject* enable_callback_tracebacks(PyObject* self, PyObject* args, PyObject* kwargs)
178{
179 if (!PyArg_ParseTuple(args, "i", &_enable_callback_tracebacks)) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000180 return NULL;
181 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000182
183 Py_INCREF(Py_None);
184 return Py_None;
185}
186
187void converters_init(PyObject* dict)
188{
189 converters = PyDict_New();
Anthony Baxter72289a62006-04-04 06:29:05 +0000190 if (!converters) {
191 return;
192 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000193
194 PyDict_SetItemString(dict, "converters", converters);
195}
196
197static PyMethodDef module_methods[] = {
198 {"connect", (PyCFunction)module_connect, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Creates a connection.")},
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000199 {"complete_statement", (PyCFunction)module_complete, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Checks if a string contains a complete SQL statement. Non-standard.")},
Anthony Baxterc51ee692006-04-01 00:57:31 +0000200#ifdef HAVE_SHARED_CACHE
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000201 {"enable_shared_cache", (PyCFunction)module_enable_shared_cache, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Enable or disable shared cache mode for the calling thread. Experimental/Non-standard.")},
Anthony Baxterc51ee692006-04-01 00:57:31 +0000202#endif
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000203 {"register_adapter", (PyCFunction)module_register_adapter, METH_VARARGS, PyDoc_STR("Registers an adapter with pysqlite's adapter registry. Non-standard.")},
204 {"register_converter", (PyCFunction)module_register_converter, METH_VARARGS, PyDoc_STR("Registers a converter with pysqlite. Non-standard.")},
Anthony Baxterc51ee692006-04-01 00:57:31 +0000205 {"adapt", (PyCFunction)psyco_microprotocols_adapt, METH_VARARGS, psyco_microprotocols_adapt_doc},
Gerhard Häring1541ef02006-06-13 22:24:47 +0000206 {"enable_callback_tracebacks", (PyCFunction)enable_callback_tracebacks, METH_VARARGS, PyDoc_STR("Enable or disable callback functions throwing errors to stderr.")},
Anthony Baxterc51ee692006-04-01 00:57:31 +0000207 {NULL, NULL}
208};
209
Gerhard Häring1541ef02006-06-13 22:24:47 +0000210struct _IntConstantPair {
211 char* constant_name;
212 int constant_value;
213};
214
215typedef struct _IntConstantPair IntConstantPair;
216
217static IntConstantPair _int_constants[] = {
218 {"PARSE_DECLTYPES", PARSE_DECLTYPES},
219 {"PARSE_COLNAMES", PARSE_COLNAMES},
220
221 {"SQLITE_OK", SQLITE_OK},
222 {"SQLITE_DENY", SQLITE_DENY},
223 {"SQLITE_IGNORE", SQLITE_IGNORE},
224 {"SQLITE_CREATE_INDEX", SQLITE_CREATE_INDEX},
225 {"SQLITE_CREATE_TABLE", SQLITE_CREATE_TABLE},
226 {"SQLITE_CREATE_TEMP_INDEX", SQLITE_CREATE_TEMP_INDEX},
227 {"SQLITE_CREATE_TEMP_TABLE", SQLITE_CREATE_TEMP_TABLE},
228 {"SQLITE_CREATE_TEMP_TRIGGER", SQLITE_CREATE_TEMP_TRIGGER},
229 {"SQLITE_CREATE_TEMP_VIEW", SQLITE_CREATE_TEMP_VIEW},
230 {"SQLITE_CREATE_TRIGGER", SQLITE_CREATE_TRIGGER},
231 {"SQLITE_CREATE_VIEW", SQLITE_CREATE_VIEW},
232 {"SQLITE_DELETE", SQLITE_DELETE},
233 {"SQLITE_DROP_INDEX", SQLITE_DROP_INDEX},
234 {"SQLITE_DROP_TABLE", SQLITE_DROP_TABLE},
235 {"SQLITE_DROP_TEMP_INDEX", SQLITE_DROP_TEMP_INDEX},
236 {"SQLITE_DROP_TEMP_TABLE", SQLITE_DROP_TEMP_TABLE},
237 {"SQLITE_DROP_TEMP_TRIGGER", SQLITE_DROP_TEMP_TRIGGER},
238 {"SQLITE_DROP_TEMP_VIEW", SQLITE_DROP_TEMP_VIEW},
239 {"SQLITE_DROP_TRIGGER", SQLITE_DROP_TRIGGER},
240 {"SQLITE_DROP_VIEW", SQLITE_DROP_VIEW},
241 {"SQLITE_INSERT", SQLITE_INSERT},
242 {"SQLITE_PRAGMA", SQLITE_PRAGMA},
243 {"SQLITE_READ", SQLITE_READ},
244 {"SQLITE_SELECT", SQLITE_SELECT},
245 {"SQLITE_TRANSACTION", SQLITE_TRANSACTION},
246 {"SQLITE_UPDATE", SQLITE_UPDATE},
247 {"SQLITE_ATTACH", SQLITE_ATTACH},
248 {"SQLITE_DETACH", SQLITE_DETACH},
249#if SQLITE_VERSION_NUMBER >= 3002001
250 {"SQLITE_ALTER_TABLE", SQLITE_ALTER_TABLE},
251 {"SQLITE_REINDEX", SQLITE_REINDEX},
252#endif
253#if SQLITE_VERSION_NUMBER >= 3003000
254 {"SQLITE_ANALYZE", SQLITE_ANALYZE},
255#endif
256 {(char*)NULL, 0}
257};
258
Anthony Baxterc51ee692006-04-01 00:57:31 +0000259PyMODINIT_FUNC init_sqlite3(void)
260{
261 PyObject *module, *dict;
Anthony Baxter72289a62006-04-04 06:29:05 +0000262 PyObject *tmp_obj;
Gerhard Häring1541ef02006-06-13 22:24:47 +0000263 int i;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000264
265 module = Py_InitModule("_sqlite3", module_methods);
266
Anthony Baxter72289a62006-04-04 06:29:05 +0000267 if (!module ||
Anthony Baxterc51ee692006-04-01 00:57:31 +0000268 (row_setup_types() < 0) ||
269 (cursor_setup_types() < 0) ||
270 (connection_setup_types() < 0) ||
271 (cache_setup_types() < 0) ||
272 (statement_setup_types() < 0) ||
273 (prepare_protocol_setup_types() < 0)
274 ) {
275 return;
276 }
277
278 Py_INCREF(&ConnectionType);
279 PyModule_AddObject(module, "Connection", (PyObject*) &ConnectionType);
280 Py_INCREF(&CursorType);
281 PyModule_AddObject(module, "Cursor", (PyObject*) &CursorType);
282 Py_INCREF(&CacheType);
283 PyModule_AddObject(module, "Statement", (PyObject*)&StatementType);
284 Py_INCREF(&StatementType);
285 PyModule_AddObject(module, "Cache", (PyObject*) &CacheType);
286 Py_INCREF(&SQLitePrepareProtocolType);
287 PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &SQLitePrepareProtocolType);
288 Py_INCREF(&RowType);
289 PyModule_AddObject(module, "Row", (PyObject*) &RowType);
290
Anthony Baxter72289a62006-04-04 06:29:05 +0000291 if (!(dict = PyModule_GetDict(module))) {
Anthony Baxterc51ee692006-04-01 00:57:31 +0000292 goto error;
293 }
294
295 /*** Create DB-API Exception hierarchy */
296
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000297 if (!(Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_StandardError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000298 goto error;
299 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000300 PyDict_SetItemString(dict, "Error", Error);
301
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000302 if (!(Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_StandardError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000303 goto error;
304 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000305 PyDict_SetItemString(dict, "Warning", Warning);
306
307 /* Error subclasses */
308
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000309 if (!(InterfaceError = PyErr_NewException(MODULE_NAME ".InterfaceError", Error, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000310 goto error;
311 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000312 PyDict_SetItemString(dict, "InterfaceError", InterfaceError);
313
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000314 if (!(DatabaseError = PyErr_NewException(MODULE_NAME ".DatabaseError", Error, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000315 goto error;
316 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000317 PyDict_SetItemString(dict, "DatabaseError", DatabaseError);
318
319 /* DatabaseError subclasses */
320
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000321 if (!(InternalError = PyErr_NewException(MODULE_NAME ".InternalError", DatabaseError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000322 goto error;
323 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000324 PyDict_SetItemString(dict, "InternalError", InternalError);
325
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000326 if (!(OperationalError = PyErr_NewException(MODULE_NAME ".OperationalError", DatabaseError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000327 goto error;
328 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000329 PyDict_SetItemString(dict, "OperationalError", OperationalError);
330
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000331 if (!(ProgrammingError = PyErr_NewException(MODULE_NAME ".ProgrammingError", DatabaseError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000332 goto error;
333 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000334 PyDict_SetItemString(dict, "ProgrammingError", ProgrammingError);
335
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000336 if (!(IntegrityError = PyErr_NewException(MODULE_NAME ".IntegrityError", DatabaseError,NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000337 goto error;
338 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000339 PyDict_SetItemString(dict, "IntegrityError", IntegrityError);
340
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000341 if (!(DataError = PyErr_NewException(MODULE_NAME ".DataError", DatabaseError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000342 goto error;
343 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000344 PyDict_SetItemString(dict, "DataError", DataError);
345
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000346 if (!(NotSupportedError = PyErr_NewException(MODULE_NAME ".NotSupportedError", DatabaseError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000347 goto error;
348 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000349 PyDict_SetItemString(dict, "NotSupportedError", NotSupportedError);
350
Anthony Baxter72289a62006-04-04 06:29:05 +0000351 /* We just need "something" unique for OptimizedUnicode. It does not really
352 * need to be a string subclass. Just anything that can act as a special
353 * marker for us. So I pulled PyCell_Type out of my magic hat.
354 */
Anthony Baxterc51ee692006-04-01 00:57:31 +0000355 Py_INCREF((PyObject*)&PyCell_Type);
356 OptimizedUnicode = (PyObject*)&PyCell_Type;
357 PyDict_SetItemString(dict, "OptimizedUnicode", OptimizedUnicode);
358
Gerhard Häring1541ef02006-06-13 22:24:47 +0000359 /* Set integer constants */
360 for (i = 0; _int_constants[i].constant_name != 0; i++) {
361 tmp_obj = PyInt_FromLong(_int_constants[i].constant_value);
362 if (!tmp_obj) {
363 goto error;
364 }
365 PyDict_SetItemString(dict, _int_constants[i].constant_name, tmp_obj);
366 Py_DECREF(tmp_obj);
Anthony Baxter72289a62006-04-04 06:29:05 +0000367 }
Anthony Baxter72289a62006-04-04 06:29:05 +0000368
369 if (!(tmp_obj = PyString_FromString(PYSQLITE_VERSION))) {
370 goto error;
371 }
372 PyDict_SetItemString(dict, "version", tmp_obj);
Neal Norwitz752968e2006-06-02 04:54:52 +0000373 Py_DECREF(tmp_obj);
Anthony Baxter72289a62006-04-04 06:29:05 +0000374
375 if (!(tmp_obj = PyString_FromString(sqlite3_libversion()))) {
376 goto error;
377 }
378 PyDict_SetItemString(dict, "sqlite_version", tmp_obj);
Neal Norwitz752968e2006-06-02 04:54:52 +0000379 Py_DECREF(tmp_obj);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000380
381 /* initialize microprotocols layer */
382 microprotocols_init(dict);
383
384 /* initialize the default converters */
385 converters_init(dict);
386
Gerhard Häring1541ef02006-06-13 22:24:47 +0000387 _enable_callback_tracebacks = 0;
388
Anthony Baxterc51ee692006-04-01 00:57:31 +0000389 /* Original comment form _bsddb.c in the Python core. This is also still
390 * needed nowadays for Python 2.3/2.4.
391 *
392 * PyEval_InitThreads is called here due to a quirk in python 1.5
393 * - 2.2.1 (at least) according to Russell Williamson <merel@wt.net>:
394 * The global interepreter lock is not initialized until the first
395 * thread is created using thread.start_new_thread() or fork() is
396 * called. that would cause the ALLOW_THREADS here to segfault due
397 * to a null pointer reference if no threads or child processes
398 * have been created. This works around that and is a no-op if
399 * threads have already been initialized.
400 * (see pybsddb-users mailing list post on 2002-08-07)
401 */
402 PyEval_InitThreads();
403
404error:
405 if (PyErr_Occurred())
406 {
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000407 PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed");
Anthony Baxterc51ee692006-04-01 00:57:31 +0000408 }
409}