blob: 667c3f00a3429d831f1518b6c64ee3ce1f7fe125 [file] [log] [blame]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001/* connection.c - the connection type
2 *
Gerhard Häringe7ea7452008-03-29 00:45:29 +00003 * Copyright (C) 2004-2007 Gerhard Häring <gh@ghaering.de>
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004 *
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 "cache.h"
25#include "module.h"
26#include "connection.h"
27#include "statement.h"
28#include "cursor.h"
29#include "prepare_protocol.h"
30#include "util.h"
31#include "sqlitecompat.h"
32
33#include "pythread.h"
34
Gerhard Häringe7ea7452008-03-29 00:45:29 +000035#define ACTION_FINALIZE 1
36#define ACTION_RESET 2
37
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000038static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039
Thomas Wouters0e3f5912006-08-11 14:57:12 +000040
41void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
42{
43 /* in older SQLite versions, calling sqlite3_result_error in callbacks
44 * triggers a bug in SQLite that leads either to irritating results or
45 * segfaults, depending on the SQLite version */
46#if SQLITE_VERSION_NUMBER >= 3003003
47 sqlite3_result_error(ctx, errmsg, len);
48#else
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000049 PyErr_SetString(pysqlite_OperationalError, errmsg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050#endif
51}
52
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000053int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054{
55 static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL};
56
57 char* database;
58 int detect_types = 0;
59 PyObject* isolation_level = NULL;
60 PyObject* factory = NULL;
61 int check_same_thread = 1;
62 int cached_statements = 100;
63 double timeout = 5.0;
64 int rc;
65
66 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist,
67 &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
68 {
Gerhard Häringe7ea7452008-03-29 00:45:29 +000069 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000070 }
71
72 self->begin_statement = NULL;
73
74 self->statement_cache = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000075 self->statements = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000076
77 Py_INCREF(Py_None);
78 self->row_factory = Py_None;
79
80 Py_INCREF(&PyUnicode_Type);
81 self->text_factory = (PyObject*)&PyUnicode_Type;
82
83 Py_BEGIN_ALLOW_THREADS
84 rc = sqlite3_open(database, &self->db);
85 Py_END_ALLOW_THREADS
86
87 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +000088 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089 return -1;
90 }
91
92 if (!isolation_level) {
Neal Norwitzefee9f52007-10-27 02:50:52 +000093 isolation_level = PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +000094 if (!isolation_level) {
95 return -1;
96 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000097 } else {
98 Py_INCREF(isolation_level);
99 }
100 self->isolation_level = NULL;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000101 pysqlite_connection_set_isolation_level(self, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000102 Py_DECREF(isolation_level);
103
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000104 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000105 if (PyErr_Occurred()) {
106 return -1;
107 }
108
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109 self->statements = PyList_New(0);
110 if (!self->statements) {
111 return -1;
112 }
113 self->created_statements = 0;
114
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000115 /* By default, the Cache class INCREFs the factory in its initializer, and
116 * decrefs it in its deallocator method. Since this would create a circular
117 * reference here, we're breaking it by decrementing self, and telling the
118 * cache class to not decref the factory (self) in its deallocator.
119 */
120 self->statement_cache->decref_factory = 0;
121 Py_DECREF(self);
122
123 self->inTransaction = 0;
124 self->detect_types = detect_types;
125 self->timeout = timeout;
126 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
127
128 self->thread_ident = PyThread_get_thread_ident();
129 self->check_same_thread = check_same_thread;
130
131 self->function_pinboard = PyDict_New();
132 if (!self->function_pinboard) {
133 return -1;
134 }
135
136 self->collations = PyDict_New();
137 if (!self->collations) {
138 return -1;
139 }
140
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000141 self->Warning = pysqlite_Warning;
142 self->Error = pysqlite_Error;
143 self->InterfaceError = pysqlite_InterfaceError;
144 self->DatabaseError = pysqlite_DatabaseError;
145 self->DataError = pysqlite_DataError;
146 self->OperationalError = pysqlite_OperationalError;
147 self->IntegrityError = pysqlite_IntegrityError;
148 self->InternalError = pysqlite_InternalError;
149 self->ProgrammingError = pysqlite_ProgrammingError;
150 self->NotSupportedError = pysqlite_NotSupportedError;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000151
152 return 0;
153}
154
Thomas Wouters477c8d52006-05-27 19:21:47 +0000155/* Empty the entire statement cache of this connection */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000156void pysqlite_flush_statement_cache(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000157{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000158 pysqlite_Node* node;
159 pysqlite_Statement* statement;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000160
161 node = self->statement_cache->first;
162
163 while (node) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000164 statement = (pysqlite_Statement*)(node->data);
165 (void)pysqlite_statement_finalize(statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000166 node = node->next;
167 }
168
169 Py_DECREF(self->statement_cache);
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000170 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000171 Py_DECREF(self);
172 self->statement_cache->decref_factory = 0;
173}
174
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000175/* action in (ACTION_RESET, ACTION_FINALIZE) */
176void pysqlite_do_all_statements(pysqlite_Connection* self, int action)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000177{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178 int i;
179 PyObject* weakref;
180 PyObject* statement;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000181
Thomas Wouters477c8d52006-05-27 19:21:47 +0000182 for (i = 0; i < PyList_Size(self->statements); i++) {
183 weakref = PyList_GetItem(self->statements, i);
184 statement = PyWeakref_GetObject(weakref);
185 if (statement != Py_None) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000186 if (action == ACTION_RESET) {
187 (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
188 } else {
189 (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
190 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000191 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000192 }
193}
194
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000195void pysqlite_connection_dealloc(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000196{
197 Py_XDECREF(self->statement_cache);
198
199 /* Clean up if user has not called .close() explicitly. */
200 if (self->db) {
201 Py_BEGIN_ALLOW_THREADS
202 sqlite3_close(self->db);
203 Py_END_ALLOW_THREADS
204 }
205
206 if (self->begin_statement) {
207 PyMem_Free(self->begin_statement);
208 }
209 Py_XDECREF(self->isolation_level);
210 Py_XDECREF(self->function_pinboard);
211 Py_XDECREF(self->row_factory);
212 Py_XDECREF(self->text_factory);
213 Py_XDECREF(self->collations);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000214 Py_XDECREF(self->statements);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000215
Christian Heimes90aa7642007-12-19 02:45:37 +0000216 Py_TYPE(self)->tp_free((PyObject*)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000217}
218
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000219PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220{
221 static char *kwlist[] = {"factory", NULL, NULL};
222 PyObject* factory = NULL;
223 PyObject* cursor;
224
225
226 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
227 &factory)) {
228 return NULL;
229 }
230
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000231 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000232 return NULL;
233 }
234
235 if (factory == NULL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000236 factory = (PyObject*)&pysqlite_CursorType;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000237 }
238
239 cursor = PyObject_CallFunction(factory, "O", self);
240
241 if (cursor && self->row_factory != Py_None) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000242 Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000243 Py_INCREF(self->row_factory);
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000244 ((pysqlite_Cursor*)cursor)->row_factory = self->row_factory;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000245 }
246
247 return cursor;
248}
249
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000250PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000251{
252 int rc;
253
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000254 if (!pysqlite_check_thread(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000255 return NULL;
256 }
257
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000258 pysqlite_do_all_statements(self, ACTION_FINALIZE);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000259
260 if (self->db) {
261 Py_BEGIN_ALLOW_THREADS
262 rc = sqlite3_close(self->db);
263 Py_END_ALLOW_THREADS
264
265 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000266 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000267 return NULL;
268 } else {
269 self->db = NULL;
270 }
271 }
272
273 Py_INCREF(Py_None);
274 return Py_None;
275}
276
277/*
278 * Checks if a connection object is usable (i. e. not closed).
279 *
280 * 0 => error; 1 => ok
281 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000282int pysqlite_check_connection(pysqlite_Connection* con)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000283{
284 if (!con->db) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000285 PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286 return 0;
287 } else {
288 return 1;
289 }
290}
291
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000292PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000293{
294 int rc;
295 const char* tail;
296 sqlite3_stmt* statement;
297
298 Py_BEGIN_ALLOW_THREADS
299 rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
300 Py_END_ALLOW_THREADS
301
302 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000303 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000304 goto error;
305 }
306
307 rc = _sqlite_step_with_busyhandler(statement, self);
308 if (rc == SQLITE_DONE) {
309 self->inTransaction = 1;
310 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000311 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000312 }
313
314 Py_BEGIN_ALLOW_THREADS
315 rc = sqlite3_finalize(statement);
316 Py_END_ALLOW_THREADS
317
318 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000319 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 }
321
322error:
323 if (PyErr_Occurred()) {
324 return NULL;
325 } else {
326 Py_INCREF(Py_None);
327 return Py_None;
328 }
329}
330
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000331PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000332{
333 int rc;
334 const char* tail;
335 sqlite3_stmt* statement;
336
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000337 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000338 return NULL;
339 }
340
341 if (self->inTransaction) {
342 Py_BEGIN_ALLOW_THREADS
343 rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
344 Py_END_ALLOW_THREADS
345 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000346 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000347 goto error;
348 }
349
350 rc = _sqlite_step_with_busyhandler(statement, self);
351 if (rc == SQLITE_DONE) {
352 self->inTransaction = 0;
353 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000354 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000355 }
356
357 Py_BEGIN_ALLOW_THREADS
358 rc = sqlite3_finalize(statement);
359 Py_END_ALLOW_THREADS
360 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000361 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000362 }
363
364 }
365
366error:
367 if (PyErr_Occurred()) {
368 return NULL;
369 } else {
370 Py_INCREF(Py_None);
371 return Py_None;
372 }
373}
374
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000375PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000376{
377 int rc;
378 const char* tail;
379 sqlite3_stmt* statement;
380
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000381 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000382 return NULL;
383 }
384
385 if (self->inTransaction) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000386 pysqlite_do_all_statements(self, ACTION_RESET);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000387
388 Py_BEGIN_ALLOW_THREADS
Georg Brandl0eaa9402007-08-11 15:39:18 +0000389 rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000390 Py_END_ALLOW_THREADS
391 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000392 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000393 goto error;
394 }
395
396 rc = _sqlite_step_with_busyhandler(statement, self);
397 if (rc == SQLITE_DONE) {
398 self->inTransaction = 0;
399 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000400 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000401 }
402
403 Py_BEGIN_ALLOW_THREADS
404 rc = sqlite3_finalize(statement);
405 Py_END_ALLOW_THREADS
406 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000407 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000408 }
409
410 }
411
412error:
413 if (PyErr_Occurred()) {
414 return NULL;
415 } else {
416 Py_INCREF(Py_None);
417 return Py_None;
418 }
419}
420
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000421void _pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000422{
423 long longval;
424 const char* buffer;
425 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000426
Thomas Wouters477c8d52006-05-27 19:21:47 +0000427 if ((!py_val) || PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000428 sqlite3_result_null(context);
429 } else if (py_val == Py_None) {
430 sqlite3_result_null(context);
Christian Heimes217cfd12007-12-02 14:31:20 +0000431 } else if (PyLong_Check(py_val)) {
432 longval = PyLong_AsLong(py_val);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000433 sqlite3_result_int64(context, (PY_LONG_LONG)longval);
434 } else if (PyFloat_Check(py_val)) {
435 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
Guido van Rossumbae07c92007-10-08 02:46:15 +0000436 } else if (PyUnicode_Check(py_val)) {
437 sqlite3_result_text(context, PyUnicode_AsString(py_val), -1, SQLITE_TRANSIENT);
438 } else if (PyObject_CheckBuffer(py_val)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000439 if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) {
440 PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000441 } else {
442 sqlite3_result_blob(context, buffer, buflen, SQLITE_TRANSIENT);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000443 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000444 } else {
445 /* TODO: raise error */
446 }
447}
448
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000449PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000450{
451 PyObject* args;
452 int i;
453 sqlite3_value* cur_value;
454 PyObject* cur_py_value;
455 const char* val_str;
456 PY_LONG_LONG val_int;
457 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000458
459 args = PyTuple_New(argc);
460 if (!args) {
461 return NULL;
462 }
463
464 for (i = 0; i < argc; i++) {
465 cur_value = argv[i];
466 switch (sqlite3_value_type(argv[i])) {
467 case SQLITE_INTEGER:
468 val_int = sqlite3_value_int64(cur_value);
Christian Heimes217cfd12007-12-02 14:31:20 +0000469 cur_py_value = PyLong_FromLong((long)val_int);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000470 break;
471 case SQLITE_FLOAT:
472 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
473 break;
474 case SQLITE_TEXT:
475 val_str = (const char*)sqlite3_value_text(cur_value);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000476 cur_py_value = PyUnicode_FromString(val_str);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000477 /* TODO: have a way to show errors here */
478 if (!cur_py_value) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000479 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000480 Py_INCREF(Py_None);
481 cur_py_value = Py_None;
482 }
483 break;
484 case SQLITE_BLOB:
485 buflen = sqlite3_value_bytes(cur_value);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000486 cur_py_value = PyString_FromStringAndSize(
Guido van Rossumbae07c92007-10-08 02:46:15 +0000487 sqlite3_value_blob(cur_value), buflen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000488 break;
489 case SQLITE_NULL:
490 default:
491 Py_INCREF(Py_None);
492 cur_py_value = Py_None;
493 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000494
495 if (!cur_py_value) {
496 Py_DECREF(args);
497 return NULL;
498 }
499
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000500 PyTuple_SetItem(args, i, cur_py_value);
501
502 }
503
504 return args;
505}
506
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000507void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000508{
509 PyObject* args;
510 PyObject* py_func;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511 PyObject* py_retval = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000512
513 PyGILState_STATE threadstate;
514
515 threadstate = PyGILState_Ensure();
516
517 py_func = (PyObject*)sqlite3_user_data(context);
518
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000519 args = _pysqlite_build_py_params(context, argc, argv);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000520 if (args) {
521 py_retval = PyObject_CallObject(py_func, args);
522 Py_DECREF(args);
523 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000524
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000525 if (py_retval) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000526 _pysqlite_set_result(context, py_retval);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000527 Py_DECREF(py_retval);
528 } else {
529 if (_enable_callback_tracebacks) {
530 PyErr_Print();
531 } else {
532 PyErr_Clear();
533 }
534 _sqlite3_result_error(context, "user-defined function raised exception", -1);
535 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000536
537 PyGILState_Release(threadstate);
538}
539
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000540static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000541{
542 PyObject* args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000544 PyObject* aggregate_class;
545 PyObject** aggregate_instance;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546 PyObject* stepmethod = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000547
548 PyGILState_STATE threadstate;
549
550 threadstate = PyGILState_Ensure();
551
552 aggregate_class = (PyObject*)sqlite3_user_data(context);
553
554 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
555
556 if (*aggregate_instance == 0) {
557 *aggregate_instance = PyObject_CallFunction(aggregate_class, "");
558
Thomas Wouters477c8d52006-05-27 19:21:47 +0000559 if (PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000560 *aggregate_instance = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000561 if (_enable_callback_tracebacks) {
562 PyErr_Print();
563 } else {
564 PyErr_Clear();
565 }
566 _sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000567 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000568 }
569 }
570
571 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572 if (!stepmethod) {
573 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000574 }
575
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000576 args = _pysqlite_build_py_params(context, argc, params);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000577 if (!args) {
578 goto error;
579 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000580
581 function_result = PyObject_CallObject(stepmethod, args);
582 Py_DECREF(args);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000583
Thomas Wouters477c8d52006-05-27 19:21:47 +0000584 if (!function_result) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000585 if (_enable_callback_tracebacks) {
586 PyErr_Print();
587 } else {
588 PyErr_Clear();
589 }
590 _sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000591 }
592
Thomas Wouters477c8d52006-05-27 19:21:47 +0000593error:
594 Py_XDECREF(stepmethod);
595 Py_XDECREF(function_result);
596
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000597 PyGILState_Release(threadstate);
598}
599
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000600void _pysqlite_final_callback(sqlite3_context* context)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000602 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000603 PyObject** aggregate_instance;
604 PyObject* aggregate_class;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000605
606 PyGILState_STATE threadstate;
607
608 threadstate = PyGILState_Ensure();
609
610 aggregate_class = (PyObject*)sqlite3_user_data(context);
611
612 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
613 if (!*aggregate_instance) {
614 /* this branch is executed if there was an exception in the aggregate's
615 * __init__ */
616
Thomas Wouters477c8d52006-05-27 19:21:47 +0000617 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000618 }
619
Thomas Wouters477c8d52006-05-27 19:21:47 +0000620 function_result = PyObject_CallMethod(*aggregate_instance, "finalize", "");
621 if (!function_result) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000622 if (_enable_callback_tracebacks) {
623 PyErr_Print();
624 } else {
625 PyErr_Clear();
626 }
627 _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
628 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000629 _pysqlite_set_result(context, function_result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000630 }
631
Thomas Wouters477c8d52006-05-27 19:21:47 +0000632error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000633 Py_XDECREF(*aggregate_instance);
634 Py_XDECREF(function_result);
635
636 PyGILState_Release(threadstate);
637}
638
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000639void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000640{
641 PyObject* new_list;
642 PyObject* weakref;
643 int i;
644
645 /* we only need to do this once in a while */
646 if (self->created_statements++ < 200) {
647 return;
648 }
649
650 self->created_statements = 0;
651
652 new_list = PyList_New(0);
653 if (!new_list) {
654 return;
655 }
656
657 for (i = 0; i < PyList_Size(self->statements); i++) {
658 weakref = PyList_GetItem(self->statements, i);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000659 if (PyWeakref_GetObject(weakref) != Py_None) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000660 if (PyList_Append(new_list, weakref) != 0) {
661 Py_DECREF(new_list);
662 return;
663 }
664 }
665 }
666
667 Py_DECREF(self->statements);
668 self->statements = new_list;
669}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000670
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000671PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000672{
673 static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
674
675 PyObject* func;
676 char* name;
677 int narg;
678 int rc;
679
680 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
681 &name, &narg, &func))
682 {
683 return NULL;
684 }
685
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000686 rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000687
Thomas Wouters477c8d52006-05-27 19:21:47 +0000688 if (rc != SQLITE_OK) {
689 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000690 PyErr_SetString(pysqlite_OperationalError, "Error creating function");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000691 return NULL;
692 } else {
693 PyDict_SetItem(self->function_pinboard, func, Py_None);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694
Thomas Wouters477c8d52006-05-27 19:21:47 +0000695 Py_INCREF(Py_None);
696 return Py_None;
697 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000698}
699
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000700PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000701{
702 PyObject* aggregate_class;
703
704 int n_arg;
705 char* name;
706 static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
707 int rc;
708
709 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
710 kwlist, &name, &n_arg, &aggregate_class)) {
711 return NULL;
712 }
713
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000714 rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_pysqlite_step_callback, &_pysqlite_final_callback);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000715 if (rc != SQLITE_OK) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000717 PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000718 return NULL;
719 } else {
720 PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None);
721
722 Py_INCREF(Py_None);
723 return Py_None;
724 }
725}
726
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000727static int _authorizer_callback(void* user_arg, int action, const char* arg1, const char* arg2 , const char* dbname, const char* access_attempt_source)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000728{
729 PyObject *ret;
730 int rc;
731 PyGILState_STATE gilstate;
732
733 gilstate = PyGILState_Ensure();
734 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
735
736 if (!ret) {
737 if (_enable_callback_tracebacks) {
738 PyErr_Print();
739 } else {
740 PyErr_Clear();
741 }
742
743 rc = SQLITE_DENY;
744 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +0000745 if (PyLong_Check(ret)) {
746 rc = (int)PyLong_AsLong(ret);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000747 } else {
748 rc = SQLITE_DENY;
749 }
750 Py_DECREF(ret);
751 }
752
753 PyGILState_Release(gilstate);
754 return rc;
755}
756
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000757static int _progress_handler(void* user_arg)
758{
759 int rc;
760 PyObject *ret;
761 PyGILState_STATE gilstate;
762
763 gilstate = PyGILState_Ensure();
764 ret = PyObject_CallFunction((PyObject*)user_arg, "");
765
766 if (!ret) {
767 if (_enable_callback_tracebacks) {
768 PyErr_Print();
769 } else {
770 PyErr_Clear();
771 }
772
773 /* abort query if error occured */
774 rc = 1;
775 } else {
776 rc = (int)PyObject_IsTrue(ret);
777 Py_DECREF(ret);
778 }
779
780 PyGILState_Release(gilstate);
781 return rc;
782}
783
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000784PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000785{
786 PyObject* authorizer_cb;
787
788 static char *kwlist[] = { "authorizer_callback", NULL };
789 int rc;
790
791 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
792 kwlist, &authorizer_cb)) {
793 return NULL;
794 }
795
796 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
797
798 if (rc != SQLITE_OK) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000799 PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000800 return NULL;
801 } else {
802 PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None);
803
804 Py_INCREF(Py_None);
805 return Py_None;
806 }
807}
808
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000809PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
810{
811 PyObject* progress_handler;
812 int n;
813
814 static char *kwlist[] = { "progress_handler", "n", NULL };
815
816 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
817 kwlist, &progress_handler, &n)) {
818 return NULL;
819 }
820
821 if (progress_handler == Py_None) {
822 /* None clears the progress handler previously set */
823 sqlite3_progress_handler(self->db, 0, 0, (void*)0);
824 } else {
825 sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
826 PyDict_SetItem(self->function_pinboard, progress_handler, Py_None);
827 }
828
829 Py_INCREF(Py_None);
830 return Py_None;
831}
832
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000833int pysqlite_check_thread(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000834{
835 if (self->check_same_thread) {
836 if (PyThread_get_thread_ident() != self->thread_ident) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000837 PyErr_Format(pysqlite_ProgrammingError,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000838 "SQLite objects created in a thread can only be used in that same thread."
839 "The object was created in thread id %ld and this is thread id %ld",
840 self->thread_ident, PyThread_get_thread_ident());
841 return 0;
842 }
843
844 }
845
846 return 1;
847}
848
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000849static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000850{
851 Py_INCREF(self->isolation_level);
852 return self->isolation_level;
853}
854
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000855static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000856{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000857 if (!pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000858 return NULL;
859 } else {
860 return Py_BuildValue("i", sqlite3_total_changes(self->db));
861 }
862}
863
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000864static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000865{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000866 PyObject* res;
867 PyObject* begin_statement;
Georg Brandlceab6102007-11-25 00:45:05 +0000868 static PyObject* begin_word;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000869
870 Py_XDECREF(self->isolation_level);
871
872 if (self->begin_statement) {
873 PyMem_Free(self->begin_statement);
874 self->begin_statement = NULL;
875 }
876
877 if (isolation_level == Py_None) {
878 Py_INCREF(Py_None);
879 self->isolation_level = Py_None;
880
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000881 res = pysqlite_connection_commit(self, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000882 if (!res) {
883 return -1;
884 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000885 Py_DECREF(res);
886
887 self->inTransaction = 0;
888 } else {
Neal Norwitzefee9f52007-10-27 02:50:52 +0000889 const char *statement;
890 Py_ssize_t size;
891
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000892 Py_INCREF(isolation_level);
893 self->isolation_level = isolation_level;
894
Georg Brandlceab6102007-11-25 00:45:05 +0000895 if (!begin_word) {
896 begin_word = PyUnicode_FromString("BEGIN ");
897 if (!begin_word) return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000898 }
Georg Brandlceab6102007-11-25 00:45:05 +0000899 begin_statement = PyUnicode_Concat(begin_word, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000900 if (!begin_statement) {
901 return -1;
902 }
903
Neal Norwitzefee9f52007-10-27 02:50:52 +0000904 statement = PyUnicode_AsStringAndSize(begin_statement, &size);
905 self->begin_statement = PyMem_Malloc(size + 2);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000906 if (!self->begin_statement) {
907 return -1;
908 }
909
Neal Norwitzefee9f52007-10-27 02:50:52 +0000910 strcpy(self->begin_statement, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000911 Py_DECREF(begin_statement);
912 }
913
914 return 0;
915}
916
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000917PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000918{
919 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000920 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000921 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000922 int rc;
923
924 if (!PyArg_ParseTuple(args, "O", &sql)) {
925 return NULL;
926 }
927
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000928 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000929
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000930 statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000931 if (!statement) {
932 return NULL;
933 }
934
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000935 rc = pysqlite_statement_create(statement, self, sql);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000936
937 if (rc != SQLITE_OK) {
938 if (rc == PYSQLITE_TOO_MUCH_SQL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000939 PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000940 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000941 PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string or unicode.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000942 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000943 (void)pysqlite_statement_reset(statement);
944 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000945 }
946
947 Py_DECREF(statement);
948 statement = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000949 } else {
950 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
951 if (!weakref) {
952 Py_DECREF(statement);
953 statement = 0;
954 goto error;
955 }
956
957 if (PyList_Append(self->statements, weakref) != 0) {
958 Py_DECREF(weakref);
959 statement = 0;
960 goto error;
961 }
962
963 Py_DECREF(weakref);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000964 }
965
Thomas Wouters477c8d52006-05-27 19:21:47 +0000966error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000967 return (PyObject*)statement;
968}
969
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000970PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000971{
972 PyObject* cursor = 0;
973 PyObject* result = 0;
974 PyObject* method = 0;
975
976 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
977 if (!cursor) {
978 goto error;
979 }
980
981 method = PyObject_GetAttrString(cursor, "execute");
982 if (!method) {
983 Py_DECREF(cursor);
984 cursor = 0;
985 goto error;
986 }
987
988 result = PyObject_CallObject(method, args);
989 if (!result) {
990 Py_DECREF(cursor);
991 cursor = 0;
992 }
993
994error:
995 Py_XDECREF(result);
996 Py_XDECREF(method);
997
998 return cursor;
999}
1000
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001001PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001002{
1003 PyObject* cursor = 0;
1004 PyObject* result = 0;
1005 PyObject* method = 0;
1006
1007 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
1008 if (!cursor) {
1009 goto error;
1010 }
1011
1012 method = PyObject_GetAttrString(cursor, "executemany");
1013 if (!method) {
1014 Py_DECREF(cursor);
1015 cursor = 0;
1016 goto error;
1017 }
1018
1019 result = PyObject_CallObject(method, args);
1020 if (!result) {
1021 Py_DECREF(cursor);
1022 cursor = 0;
1023 }
1024
1025error:
1026 Py_XDECREF(result);
1027 Py_XDECREF(method);
1028
1029 return cursor;
1030}
1031
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001032PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001033{
1034 PyObject* cursor = 0;
1035 PyObject* result = 0;
1036 PyObject* method = 0;
1037
1038 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
1039 if (!cursor) {
1040 goto error;
1041 }
1042
1043 method = PyObject_GetAttrString(cursor, "executescript");
1044 if (!method) {
1045 Py_DECREF(cursor);
1046 cursor = 0;
1047 goto error;
1048 }
1049
1050 result = PyObject_CallObject(method, args);
1051 if (!result) {
1052 Py_DECREF(cursor);
1053 cursor = 0;
1054 }
1055
1056error:
1057 Py_XDECREF(result);
1058 Py_XDECREF(method);
1059
1060 return cursor;
1061}
1062
1063/* ------------------------- COLLATION CODE ------------------------ */
1064
1065static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001066pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001067 void* context,
1068 int text1_length, const void* text1_data,
1069 int text2_length, const void* text2_data)
1070{
1071 PyObject* callback = (PyObject*)context;
1072 PyObject* string1 = 0;
1073 PyObject* string2 = 0;
1074 PyGILState_STATE gilstate;
1075
1076 PyObject* retval = NULL;
1077 int result = 0;
1078
1079 gilstate = PyGILState_Ensure();
1080
1081 if (PyErr_Occurred()) {
1082 goto finally;
1083 }
1084
Guido van Rossum98297ee2007-11-06 21:34:58 +00001085 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1086 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001087
1088 if (!string1 || !string2) {
1089 goto finally; /* failed to allocate strings */
1090 }
1091
1092 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1093
1094 if (!retval) {
1095 /* execution failed */
1096 goto finally;
1097 }
1098
Christian Heimes217cfd12007-12-02 14:31:20 +00001099 result = PyLong_AsLong(retval);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001100 if (PyErr_Occurred()) {
1101 result = 0;
1102 }
1103
1104finally:
1105 Py_XDECREF(string1);
1106 Py_XDECREF(string2);
1107 Py_XDECREF(retval);
1108
1109 PyGILState_Release(gilstate);
1110
1111 return result;
1112}
1113
1114static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001115pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001116{
1117 PyObject* retval = NULL;
1118
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001119 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001120 goto finally;
1121 }
1122
1123 sqlite3_interrupt(self->db);
1124
1125 Py_INCREF(Py_None);
1126 retval = Py_None;
1127
1128finally:
1129 return retval;
1130}
1131
Christian Heimesbbe741d2008-03-28 10:53:29 +00001132/* Function author: Paul Kippes <kippesp@gmail.com>
1133 * Class method of Connection to call the Python function _iterdump
1134 * of the sqlite3 module.
1135 */
1136static PyObject *
1137pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1138{
1139 PyObject* retval = NULL;
1140 PyObject* module = NULL;
1141 PyObject* module_dict;
1142 PyObject* pyfn_iterdump;
1143
1144 if (!pysqlite_check_connection(self)) {
1145 goto finally;
1146 }
1147
1148 module = PyImport_ImportModule(MODULE_NAME ".dump");
1149 if (!module) {
1150 goto finally;
1151 }
1152
1153 module_dict = PyModule_GetDict(module);
1154 if (!module_dict) {
1155 goto finally;
1156 }
1157
1158 pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
1159 if (!pyfn_iterdump) {
1160 PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
1161 goto finally;
1162 }
1163
1164 args = PyTuple_New(1);
1165 if (!args) {
1166 goto finally;
1167 }
1168 Py_INCREF(self);
1169 PyTuple_SetItem(args, 0, (PyObject*)self);
1170 retval = PyObject_CallObject(pyfn_iterdump, args);
1171
1172finally:
1173 Py_XDECREF(args);
1174 Py_XDECREF(module);
1175 return retval;
1176}
1177
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001178static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001179pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001180{
1181 PyObject* callable;
1182 PyObject* uppercase_name = 0;
1183 PyObject* name;
1184 PyObject* retval;
1185 char* chk;
1186 int rc;
1187
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001188 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001189 goto finally;
1190 }
1191
Gerhard Häring6d214562007-08-10 18:15:11 +00001192 if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyUnicode_Type, &name, &callable)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001193 goto finally;
1194 }
1195
1196 uppercase_name = PyObject_CallMethod(name, "upper", "");
1197 if (!uppercase_name) {
1198 goto finally;
1199 }
1200
Guido van Rossum98297ee2007-11-06 21:34:58 +00001201 chk = PyUnicode_AsString(uppercase_name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001202 while (*chk) {
1203 if ((*chk >= '0' && *chk <= '9')
1204 || (*chk >= 'A' && *chk <= 'Z')
1205 || (*chk == '_'))
1206 {
1207 chk++;
1208 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001209 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001210 goto finally;
1211 }
1212 }
1213
1214 if (callable != Py_None && !PyCallable_Check(callable)) {
1215 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1216 goto finally;
1217 }
1218
1219 if (callable != Py_None) {
1220 PyDict_SetItem(self->collations, uppercase_name, callable);
1221 } else {
1222 PyDict_DelItem(self->collations, uppercase_name);
1223 }
1224
1225 rc = sqlite3_create_collation(self->db,
Guido van Rossum98297ee2007-11-06 21:34:58 +00001226 PyUnicode_AsString(uppercase_name),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001227 SQLITE_UTF8,
1228 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001229 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001230 if (rc != SQLITE_OK) {
1231 PyDict_DelItem(self->collations, uppercase_name);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001232 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001233 goto finally;
1234 }
1235
1236finally:
1237 Py_XDECREF(uppercase_name);
1238
1239 if (PyErr_Occurred()) {
1240 retval = NULL;
1241 } else {
1242 Py_INCREF(Py_None);
1243 retval = Py_None;
1244 }
1245
1246 return retval;
1247}
1248
Christian Heimesbbe741d2008-03-28 10:53:29 +00001249/* Called when the connection is used as a context manager. Returns itself as a
1250 * convenience to the caller. */
1251static PyObject *
1252pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1253{
1254 Py_INCREF(self);
1255 return (PyObject*)self;
1256}
1257
1258/** Called when the connection is used as a context manager. If there was any
1259 * exception, a rollback takes place; otherwise we commit. */
1260static PyObject *
1261pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1262{
1263 PyObject* exc_type, *exc_value, *exc_tb;
1264 char* method_name;
1265 PyObject* result;
1266
1267 if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1268 return NULL;
1269 }
1270
1271 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1272 method_name = "commit";
1273 } else {
1274 method_name = "rollback";
1275 }
1276
1277 result = PyObject_CallMethod((PyObject*)self, method_name, "");
1278 if (!result) {
1279 return NULL;
1280 }
1281 Py_DECREF(result);
1282
1283 Py_RETURN_FALSE;
1284}
1285
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001286static char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001287PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001288
1289static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001290 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1291 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001292 {NULL}
1293};
1294
1295static PyMethodDef connection_methods[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001296 {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001297 PyDoc_STR("Return a cursor for the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001298 {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001299 PyDoc_STR("Closes the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001300 {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001301 PyDoc_STR("Commit the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001302 {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001303 PyDoc_STR("Roll back the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001304 {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001305 PyDoc_STR("Creates a new function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001306 {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001307 PyDoc_STR("Creates a new aggregate. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001308 {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001309 PyDoc_STR("Sets authorizer callback. Non-standard.")},
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001310 {"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
1311 PyDoc_STR("Sets progress handler callback. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001312 {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001313 PyDoc_STR("Executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001314 {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001315 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001316 {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001317 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001318 {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319 PyDoc_STR("Creates a collation function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001320 {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001321 PyDoc_STR("Abort any pending database operation. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001322 {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
1323 PyDoc_STR("Returns iterator to the dump of the database in an SQL text"
1324 "format.")},
1325 {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1326 PyDoc_STR("For context manager. Non-standard.")},
1327 {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1328 PyDoc_STR("For context manager. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001329 {NULL, NULL}
1330};
1331
1332static struct PyMemberDef connection_members[] =
1333{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001334 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1335 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1336 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1337 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1338 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1339 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1340 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1341 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1342 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1343 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001344 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1345 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001346 {NULL}
1347};
1348
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001349PyTypeObject pysqlite_ConnectionType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001350 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001351 MODULE_NAME ".Connection", /* tp_name */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001352 sizeof(pysqlite_Connection), /* tp_basicsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001353 0, /* tp_itemsize */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001354 (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001355 0, /* tp_print */
1356 0, /* tp_getattr */
1357 0, /* tp_setattr */
1358 0, /* tp_compare */
1359 0, /* tp_repr */
1360 0, /* tp_as_number */
1361 0, /* tp_as_sequence */
1362 0, /* tp_as_mapping */
1363 0, /* tp_hash */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001364 (ternaryfunc)pysqlite_connection_call, /* tp_call */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001365 0, /* tp_str */
1366 0, /* tp_getattro */
1367 0, /* tp_setattro */
1368 0, /* tp_as_buffer */
1369 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1370 connection_doc, /* tp_doc */
1371 0, /* tp_traverse */
1372 0, /* tp_clear */
1373 0, /* tp_richcompare */
1374 0, /* tp_weaklistoffset */
1375 0, /* tp_iter */
1376 0, /* tp_iternext */
1377 connection_methods, /* tp_methods */
1378 connection_members, /* tp_members */
1379 connection_getset, /* tp_getset */
1380 0, /* tp_base */
1381 0, /* tp_dict */
1382 0, /* tp_descr_get */
1383 0, /* tp_descr_set */
1384 0, /* tp_dictoffset */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001385 (initproc)pysqlite_connection_init, /* tp_init */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001386 0, /* tp_alloc */
1387 0, /* tp_new */
1388 0 /* tp_free */
1389};
1390
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001391extern int pysqlite_connection_setup_types(void)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001392{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001393 pysqlite_ConnectionType.tp_new = PyType_GenericNew;
1394 return PyType_Ready(&pysqlite_ConnectionType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001395}