blob: bfaf730e0ccfe5c24a5d234fa0b09a7380de033f [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;
Gerhard Häringf8052762008-10-08 08:45:16 +0000131 int rc;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000132
133 if (!PyArg_ParseTuple(args, "OO", &type, &caster)) {
134 return NULL;
135 }
136
Gerhard Häringf8052762008-10-08 08:45:16 +0000137 rc = microprotocols_add(type, (PyObject*)&SQLitePrepareProtocolType, caster);
138 if (rc == -1)
139 return NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000140
141 Py_INCREF(Py_None);
142 return Py_None;
143}
144
145static PyObject* module_register_converter(PyObject* self, PyObject* args, PyObject* kwargs)
146{
Gerhard Häring1541ef02006-06-13 22:24:47 +0000147 char* orig_name;
148 char* name = NULL;
149 char* c;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000150 PyObject* callable;
Gerhard Häring1541ef02006-06-13 22:24:47 +0000151 PyObject* retval = NULL;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000152
Gerhard Häring1541ef02006-06-13 22:24:47 +0000153 if (!PyArg_ParseTuple(args, "sO", &orig_name, &callable)) {
Anthony Baxterc51ee692006-04-01 00:57:31 +0000154 return NULL;
155 }
156
Gerhard Häring1541ef02006-06-13 22:24:47 +0000157 /* convert the name to lowercase */
158 name = PyMem_Malloc(strlen(orig_name) + 2);
159 if (!name) {
160 goto error;
161 }
162 strcpy(name, orig_name);
163 for (c = name; *c != (char)0; c++) {
164 *c = (*c) & 0xDF;
165 }
166
167 if (PyDict_SetItemString(converters, name, callable) != 0) {
168 goto error;
169 }
170
171 Py_INCREF(Py_None);
172 retval = Py_None;
173error:
174 if (name) {
175 PyMem_Free(name);
176 }
177 return retval;
178}
179
180static PyObject* enable_callback_tracebacks(PyObject* self, PyObject* args, PyObject* kwargs)
181{
182 if (!PyArg_ParseTuple(args, "i", &_enable_callback_tracebacks)) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000183 return NULL;
184 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000185
186 Py_INCREF(Py_None);
187 return Py_None;
188}
189
190void converters_init(PyObject* dict)
191{
192 converters = PyDict_New();
Anthony Baxter72289a62006-04-04 06:29:05 +0000193 if (!converters) {
194 return;
195 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000196
197 PyDict_SetItemString(dict, "converters", converters);
198}
199
200static PyMethodDef module_methods[] = {
201 {"connect", (PyCFunction)module_connect, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("Creates a connection.")},
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000202 {"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 +0000203#ifdef HAVE_SHARED_CACHE
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000204 {"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 +0000205#endif
Gerhard Häring3e99c0a2006-04-23 15:24:26 +0000206 {"register_adapter", (PyCFunction)module_register_adapter, METH_VARARGS, PyDoc_STR("Registers an adapter with pysqlite's adapter registry. Non-standard.")},
207 {"register_converter", (PyCFunction)module_register_converter, METH_VARARGS, PyDoc_STR("Registers a converter with pysqlite. Non-standard.")},
Anthony Baxterc51ee692006-04-01 00:57:31 +0000208 {"adapt", (PyCFunction)psyco_microprotocols_adapt, METH_VARARGS, psyco_microprotocols_adapt_doc},
Gerhard Häring1541ef02006-06-13 22:24:47 +0000209 {"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 +0000210 {NULL, NULL}
211};
212
Gerhard Häring1541ef02006-06-13 22:24:47 +0000213struct _IntConstantPair {
214 char* constant_name;
215 int constant_value;
216};
217
218typedef struct _IntConstantPair IntConstantPair;
219
220static IntConstantPair _int_constants[] = {
221 {"PARSE_DECLTYPES", PARSE_DECLTYPES},
222 {"PARSE_COLNAMES", PARSE_COLNAMES},
223
224 {"SQLITE_OK", SQLITE_OK},
225 {"SQLITE_DENY", SQLITE_DENY},
226 {"SQLITE_IGNORE", SQLITE_IGNORE},
227 {"SQLITE_CREATE_INDEX", SQLITE_CREATE_INDEX},
228 {"SQLITE_CREATE_TABLE", SQLITE_CREATE_TABLE},
229 {"SQLITE_CREATE_TEMP_INDEX", SQLITE_CREATE_TEMP_INDEX},
230 {"SQLITE_CREATE_TEMP_TABLE", SQLITE_CREATE_TEMP_TABLE},
231 {"SQLITE_CREATE_TEMP_TRIGGER", SQLITE_CREATE_TEMP_TRIGGER},
232 {"SQLITE_CREATE_TEMP_VIEW", SQLITE_CREATE_TEMP_VIEW},
233 {"SQLITE_CREATE_TRIGGER", SQLITE_CREATE_TRIGGER},
234 {"SQLITE_CREATE_VIEW", SQLITE_CREATE_VIEW},
235 {"SQLITE_DELETE", SQLITE_DELETE},
236 {"SQLITE_DROP_INDEX", SQLITE_DROP_INDEX},
237 {"SQLITE_DROP_TABLE", SQLITE_DROP_TABLE},
238 {"SQLITE_DROP_TEMP_INDEX", SQLITE_DROP_TEMP_INDEX},
239 {"SQLITE_DROP_TEMP_TABLE", SQLITE_DROP_TEMP_TABLE},
240 {"SQLITE_DROP_TEMP_TRIGGER", SQLITE_DROP_TEMP_TRIGGER},
241 {"SQLITE_DROP_TEMP_VIEW", SQLITE_DROP_TEMP_VIEW},
242 {"SQLITE_DROP_TRIGGER", SQLITE_DROP_TRIGGER},
243 {"SQLITE_DROP_VIEW", SQLITE_DROP_VIEW},
244 {"SQLITE_INSERT", SQLITE_INSERT},
245 {"SQLITE_PRAGMA", SQLITE_PRAGMA},
246 {"SQLITE_READ", SQLITE_READ},
247 {"SQLITE_SELECT", SQLITE_SELECT},
248 {"SQLITE_TRANSACTION", SQLITE_TRANSACTION},
249 {"SQLITE_UPDATE", SQLITE_UPDATE},
250 {"SQLITE_ATTACH", SQLITE_ATTACH},
251 {"SQLITE_DETACH", SQLITE_DETACH},
252#if SQLITE_VERSION_NUMBER >= 3002001
253 {"SQLITE_ALTER_TABLE", SQLITE_ALTER_TABLE},
254 {"SQLITE_REINDEX", SQLITE_REINDEX},
255#endif
256#if SQLITE_VERSION_NUMBER >= 3003000
257 {"SQLITE_ANALYZE", SQLITE_ANALYZE},
258#endif
259 {(char*)NULL, 0}
260};
261
Anthony Baxterc51ee692006-04-01 00:57:31 +0000262PyMODINIT_FUNC init_sqlite3(void)
263{
264 PyObject *module, *dict;
Anthony Baxter72289a62006-04-04 06:29:05 +0000265 PyObject *tmp_obj;
Gerhard Häring1541ef02006-06-13 22:24:47 +0000266 int i;
Anthony Baxterc51ee692006-04-01 00:57:31 +0000267
268 module = Py_InitModule("_sqlite3", module_methods);
269
Anthony Baxter72289a62006-04-04 06:29:05 +0000270 if (!module ||
Anthony Baxterc51ee692006-04-01 00:57:31 +0000271 (row_setup_types() < 0) ||
272 (cursor_setup_types() < 0) ||
273 (connection_setup_types() < 0) ||
274 (cache_setup_types() < 0) ||
275 (statement_setup_types() < 0) ||
276 (prepare_protocol_setup_types() < 0)
277 ) {
278 return;
279 }
280
281 Py_INCREF(&ConnectionType);
282 PyModule_AddObject(module, "Connection", (PyObject*) &ConnectionType);
283 Py_INCREF(&CursorType);
284 PyModule_AddObject(module, "Cursor", (PyObject*) &CursorType);
285 Py_INCREF(&CacheType);
286 PyModule_AddObject(module, "Statement", (PyObject*)&StatementType);
287 Py_INCREF(&StatementType);
288 PyModule_AddObject(module, "Cache", (PyObject*) &CacheType);
289 Py_INCREF(&SQLitePrepareProtocolType);
290 PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &SQLitePrepareProtocolType);
291 Py_INCREF(&RowType);
292 PyModule_AddObject(module, "Row", (PyObject*) &RowType);
293
Anthony Baxter72289a62006-04-04 06:29:05 +0000294 if (!(dict = PyModule_GetDict(module))) {
Anthony Baxterc51ee692006-04-01 00:57:31 +0000295 goto error;
296 }
297
298 /*** Create DB-API Exception hierarchy */
299
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000300 if (!(Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_StandardError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000301 goto error;
302 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000303 PyDict_SetItemString(dict, "Error", Error);
304
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000305 if (!(Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_StandardError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000306 goto error;
307 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000308 PyDict_SetItemString(dict, "Warning", Warning);
309
310 /* Error subclasses */
311
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000312 if (!(InterfaceError = PyErr_NewException(MODULE_NAME ".InterfaceError", Error, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000313 goto error;
314 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000315 PyDict_SetItemString(dict, "InterfaceError", InterfaceError);
316
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000317 if (!(DatabaseError = PyErr_NewException(MODULE_NAME ".DatabaseError", Error, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000318 goto error;
319 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000320 PyDict_SetItemString(dict, "DatabaseError", DatabaseError);
321
322 /* DatabaseError subclasses */
323
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000324 if (!(InternalError = PyErr_NewException(MODULE_NAME ".InternalError", DatabaseError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000325 goto error;
326 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000327 PyDict_SetItemString(dict, "InternalError", InternalError);
328
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000329 if (!(OperationalError = PyErr_NewException(MODULE_NAME ".OperationalError", DatabaseError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000330 goto error;
331 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000332 PyDict_SetItemString(dict, "OperationalError", OperationalError);
333
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000334 if (!(ProgrammingError = PyErr_NewException(MODULE_NAME ".ProgrammingError", DatabaseError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000335 goto error;
336 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000337 PyDict_SetItemString(dict, "ProgrammingError", ProgrammingError);
338
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000339 if (!(IntegrityError = PyErr_NewException(MODULE_NAME ".IntegrityError", DatabaseError,NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000340 goto error;
341 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000342 PyDict_SetItemString(dict, "IntegrityError", IntegrityError);
343
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000344 if (!(DataError = PyErr_NewException(MODULE_NAME ".DataError", DatabaseError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000345 goto error;
346 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000347 PyDict_SetItemString(dict, "DataError", DataError);
348
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000349 if (!(NotSupportedError = PyErr_NewException(MODULE_NAME ".NotSupportedError", DatabaseError, NULL))) {
Anthony Baxter72289a62006-04-04 06:29:05 +0000350 goto error;
351 }
Anthony Baxterc51ee692006-04-01 00:57:31 +0000352 PyDict_SetItemString(dict, "NotSupportedError", NotSupportedError);
353
Anthony Baxter72289a62006-04-04 06:29:05 +0000354 /* We just need "something" unique for OptimizedUnicode. It does not really
355 * need to be a string subclass. Just anything that can act as a special
356 * marker for us. So I pulled PyCell_Type out of my magic hat.
357 */
Anthony Baxterc51ee692006-04-01 00:57:31 +0000358 Py_INCREF((PyObject*)&PyCell_Type);
359 OptimizedUnicode = (PyObject*)&PyCell_Type;
360 PyDict_SetItemString(dict, "OptimizedUnicode", OptimizedUnicode);
361
Gerhard Häring1541ef02006-06-13 22:24:47 +0000362 /* Set integer constants */
363 for (i = 0; _int_constants[i].constant_name != 0; i++) {
364 tmp_obj = PyInt_FromLong(_int_constants[i].constant_value);
365 if (!tmp_obj) {
366 goto error;
367 }
368 PyDict_SetItemString(dict, _int_constants[i].constant_name, tmp_obj);
369 Py_DECREF(tmp_obj);
Anthony Baxter72289a62006-04-04 06:29:05 +0000370 }
Anthony Baxter72289a62006-04-04 06:29:05 +0000371
372 if (!(tmp_obj = PyString_FromString(PYSQLITE_VERSION))) {
373 goto error;
374 }
375 PyDict_SetItemString(dict, "version", tmp_obj);
Neal Norwitz752968e2006-06-02 04:54:52 +0000376 Py_DECREF(tmp_obj);
Anthony Baxter72289a62006-04-04 06:29:05 +0000377
378 if (!(tmp_obj = PyString_FromString(sqlite3_libversion()))) {
379 goto error;
380 }
381 PyDict_SetItemString(dict, "sqlite_version", tmp_obj);
Neal Norwitz752968e2006-06-02 04:54:52 +0000382 Py_DECREF(tmp_obj);
Anthony Baxterc51ee692006-04-01 00:57:31 +0000383
384 /* initialize microprotocols layer */
385 microprotocols_init(dict);
386
387 /* initialize the default converters */
388 converters_init(dict);
389
Gerhard Häring1541ef02006-06-13 22:24:47 +0000390 _enable_callback_tracebacks = 0;
391
Anthony Baxterc51ee692006-04-01 00:57:31 +0000392 /* Original comment form _bsddb.c in the Python core. This is also still
393 * needed nowadays for Python 2.3/2.4.
394 *
395 * PyEval_InitThreads is called here due to a quirk in python 1.5
396 * - 2.2.1 (at least) according to Russell Williamson <merel@wt.net>:
397 * The global interepreter lock is not initialized until the first
398 * thread is created using thread.start_new_thread() or fork() is
399 * called. that would cause the ALLOW_THREADS here to segfault due
400 * to a null pointer reference if no threads or child processes
401 * have been created. This works around that and is a no-op if
402 * threads have already been initialized.
403 * (see pybsddb-users mailing list post on 2002-08-07)
404 */
405 PyEval_InitThreads();
406
407error:
408 if (PyErr_Occurred())
409 {
Anthony Baxter8e7b4902006-04-05 18:25:33 +0000410 PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed");
Anthony Baxterc51ee692006-04-01 00:57:31 +0000411 }
412}