blob: fb6eb065001eea23d3fff6b9aa6ca33a7bfe32ac [file] [log] [blame]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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 */
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
38PyObject* Error, *Warning, *InterfaceError, *DatabaseError, *InternalError,
39 *OperationalError, *ProgrammingError, *IntegrityError, *DataError,
40 *NotSupportedError, *OptimizedUnicode;
41
42PyObject* converters;
43
44static PyObject* module_connect(PyObject* self, PyObject* args, PyObject*
45 kwargs)
46{
47 /* Python seems to have no way of extracting a single keyword-arg at
48 * C-level, so this code is redundant with the one in connection_init in
49 * connection.c and must always be copied from there ... */
50
51 static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL};
52 char* database;
53 int detect_types = 0;
54 PyObject* isolation_level;
55 PyObject* factory = NULL;
56 int check_same_thread = 1;
57 int cached_statements;
58 double timeout = 5.0;
59
60 PyObject* result;
61
62 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist,
63 &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
64 {
65 return NULL;
66 }
67
68 if (factory == NULL) {
69 factory = (PyObject*)&ConnectionType;
70 }
71
72 result = PyObject_Call(factory, args, kwargs);
73
74 return result;
75}
76
77static PyObject* module_complete(PyObject* self, PyObject* args, PyObject*
78 kwargs)
79{
80 static char *kwlist[] = {"statement", NULL, NULL};
81 char* statement;
82
83 PyObject* result;
84
85 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement))
86 {
87 return NULL;
88 }
89
90 if (sqlite3_complete(statement)) {
91 result = Py_True;
92 } else {
93 result = Py_False;
94 }
95
96 Py_INCREF(result);
97
98 return result;
99}
100
101#ifdef HAVE_SHARED_CACHE
102static PyObject* module_enable_shared_cache(PyObject* self, PyObject* args, PyObject*
103 kwargs)
104{
105 static char *kwlist[] = {"do_enable", NULL, NULL};
106 int do_enable;
107 int rc;
108
109 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist, &do_enable))
110 {
111 return NULL;
112 }
113
114 rc = sqlite3_enable_shared_cache(do_enable);
115
116 if (rc != SQLITE_OK) {
117 PyErr_SetString(OperationalError, "Changing the shared_cache flag failed");
118 return NULL;
119 } else {
120 Py_INCREF(Py_None);
121 return Py_None;
122 }
123}
124#endif /* HAVE_SHARED_CACHE */
125
126static PyObject* module_register_adapter(PyObject* self, PyObject* args, PyObject* kwargs)
127{
128 PyTypeObject* type;
129 PyObject* caster;
130
131 if (!PyArg_ParseTuple(args, "OO", &type, &caster)) {
132 return NULL;
133 }
134
135 microprotocols_add(type, (PyObject*)&SQLitePrepareProtocolType, caster);
136
137 Py_INCREF(Py_None);
138 return Py_None;
139}
140
141static PyObject* module_register_converter(PyObject* self, PyObject* args, PyObject* kwargs)
142{
143 PyObject* name;
144 PyObject* callable;
145
146 if (!PyArg_ParseTuple(args, "OO", &name, &callable)) {
147 return NULL;
148 }
149
150 if (PyDict_SetItem(converters, name, callable) != 0) {
151 return NULL;
152 }
153
154 Py_INCREF(Py_None);
155 return Py_None;
156}
157
158void converters_init(PyObject* dict)
159{
160 converters = PyDict_New();
161 if (!converters) {
162 return;
163 }
164
165 PyDict_SetItemString(dict, "converters", converters);
166}
167
168static PyMethodDef module_methods[] = {
169 {"connect", (PyCFunction)module_connect, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Creates a connection.")},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000170 {"complete_statement", (PyCFunction)module_complete, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Checks if a string contains a complete SQL statement. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000171#ifdef HAVE_SHARED_CACHE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000172 {"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.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000173#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +0000174 {"register_adapter", (PyCFunction)module_register_adapter, METH_VARARGS, PyDoc_STR("Registers an adapter with pysqlite's adapter registry. Non-standard.")},
175 {"register_converter", (PyCFunction)module_register_converter, METH_VARARGS, PyDoc_STR("Registers a converter with pysqlite. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000176 {"adapt", (PyCFunction)psyco_microprotocols_adapt, METH_VARARGS, psyco_microprotocols_adapt_doc},
177 {NULL, NULL}
178};
179
180PyMODINIT_FUNC init_sqlite3(void)
181{
182 PyObject *module, *dict;
183 PyObject *tmp_obj;
184
185 module = Py_InitModule("_sqlite3", module_methods);
186
187 if (!module ||
188 (row_setup_types() < 0) ||
189 (cursor_setup_types() < 0) ||
190 (connection_setup_types() < 0) ||
191 (cache_setup_types() < 0) ||
192 (statement_setup_types() < 0) ||
193 (prepare_protocol_setup_types() < 0)
194 ) {
195 return;
196 }
197
198 Py_INCREF(&ConnectionType);
199 PyModule_AddObject(module, "Connection", (PyObject*) &ConnectionType);
200 Py_INCREF(&CursorType);
201 PyModule_AddObject(module, "Cursor", (PyObject*) &CursorType);
202 Py_INCREF(&CacheType);
203 PyModule_AddObject(module, "Statement", (PyObject*)&StatementType);
204 Py_INCREF(&StatementType);
205 PyModule_AddObject(module, "Cache", (PyObject*) &CacheType);
206 Py_INCREF(&SQLitePrepareProtocolType);
207 PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &SQLitePrepareProtocolType);
208 Py_INCREF(&RowType);
209 PyModule_AddObject(module, "Row", (PyObject*) &RowType);
210
211 if (!(dict = PyModule_GetDict(module))) {
212 goto error;
213 }
214
215 /*** Create DB-API Exception hierarchy */
216
217 if (!(Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_StandardError, NULL))) {
218 goto error;
219 }
220 PyDict_SetItemString(dict, "Error", Error);
221
222 if (!(Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_StandardError, NULL))) {
223 goto error;
224 }
225 PyDict_SetItemString(dict, "Warning", Warning);
226
227 /* Error subclasses */
228
229 if (!(InterfaceError = PyErr_NewException(MODULE_NAME ".InterfaceError", Error, NULL))) {
230 goto error;
231 }
232 PyDict_SetItemString(dict, "InterfaceError", InterfaceError);
233
234 if (!(DatabaseError = PyErr_NewException(MODULE_NAME ".DatabaseError", Error, NULL))) {
235 goto error;
236 }
237 PyDict_SetItemString(dict, "DatabaseError", DatabaseError);
238
239 /* DatabaseError subclasses */
240
241 if (!(InternalError = PyErr_NewException(MODULE_NAME ".InternalError", DatabaseError, NULL))) {
242 goto error;
243 }
244 PyDict_SetItemString(dict, "InternalError", InternalError);
245
246 if (!(OperationalError = PyErr_NewException(MODULE_NAME ".OperationalError", DatabaseError, NULL))) {
247 goto error;
248 }
249 PyDict_SetItemString(dict, "OperationalError", OperationalError);
250
251 if (!(ProgrammingError = PyErr_NewException(MODULE_NAME ".ProgrammingError", DatabaseError, NULL))) {
252 goto error;
253 }
254 PyDict_SetItemString(dict, "ProgrammingError", ProgrammingError);
255
256 if (!(IntegrityError = PyErr_NewException(MODULE_NAME ".IntegrityError", DatabaseError,NULL))) {
257 goto error;
258 }
259 PyDict_SetItemString(dict, "IntegrityError", IntegrityError);
260
261 if (!(DataError = PyErr_NewException(MODULE_NAME ".DataError", DatabaseError, NULL))) {
262 goto error;
263 }
264 PyDict_SetItemString(dict, "DataError", DataError);
265
266 if (!(NotSupportedError = PyErr_NewException(MODULE_NAME ".NotSupportedError", DatabaseError, NULL))) {
267 goto error;
268 }
269 PyDict_SetItemString(dict, "NotSupportedError", NotSupportedError);
270
271 /* We just need "something" unique for OptimizedUnicode. It does not really
272 * need to be a string subclass. Just anything that can act as a special
273 * marker for us. So I pulled PyCell_Type out of my magic hat.
274 */
275 Py_INCREF((PyObject*)&PyCell_Type);
276 OptimizedUnicode = (PyObject*)&PyCell_Type;
277 PyDict_SetItemString(dict, "OptimizedUnicode", OptimizedUnicode);
278
279 if (!(tmp_obj = PyInt_FromLong(PARSE_DECLTYPES))) {
280 goto error;
281 }
282 PyDict_SetItemString(dict, "PARSE_DECLTYPES", tmp_obj);
283
284 if (!(tmp_obj = PyInt_FromLong(PARSE_COLNAMES))) {
285 goto error;
286 }
287 PyDict_SetItemString(dict, "PARSE_COLNAMES", tmp_obj);
288
289 if (!(tmp_obj = PyString_FromString(PYSQLITE_VERSION))) {
290 goto error;
291 }
292 PyDict_SetItemString(dict, "version", tmp_obj);
293
294 if (!(tmp_obj = PyString_FromString(sqlite3_libversion()))) {
295 goto error;
296 }
297 PyDict_SetItemString(dict, "sqlite_version", tmp_obj);
298
299 /* initialize microprotocols layer */
300 microprotocols_init(dict);
301
302 /* initialize the default converters */
303 converters_init(dict);
304
305 /* Original comment form _bsddb.c in the Python core. This is also still
306 * needed nowadays for Python 2.3/2.4.
307 *
308 * PyEval_InitThreads is called here due to a quirk in python 1.5
309 * - 2.2.1 (at least) according to Russell Williamson <merel@wt.net>:
310 * The global interepreter lock is not initialized until the first
311 * thread is created using thread.start_new_thread() or fork() is
312 * called. that would cause the ALLOW_THREADS here to segfault due
313 * to a null pointer reference if no threads or child processes
314 * have been created. This works around that and is a no-op if
315 * threads have already been initialized.
316 * (see pybsddb-users mailing list post on 2002-08-07)
317 */
318 PyEval_InitThreads();
319
320error:
321 if (PyErr_Occurred())
322 {
323 PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed");
324 }
325}