blob: 7fa69e783a142996818198756211d3d16621a15d [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
Benjamin Petersond7b03282008-09-13 15:58:53 +000041static void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042{
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
Benjamin Petersond7b03282008-09-13 15:58:53 +0000307 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000308 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
Benjamin Petersond7b03282008-09-13 15:58:53 +0000350 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000351 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
Benjamin Petersond7b03282008-09-13 15:58:53 +0000396 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000397 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)) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000437 sqlite3_result_text(context, _PyUnicode_AsString(py_val), -1, SQLITE_TRANSIENT);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000438 } 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);
Christian Heimes72b710a2008-05-26 13:28:38 +0000486 cur_py_value = PyBytes_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
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000904 statement = _PyUnicode_AsStringAndSize(begin_statement, &size);
Georg Brandl3dbca812008-07-23 16:10:53 +0000905 if (!statement) {
906 Py_DECREF(statement);
907 return -1;
908 }
Neal Norwitzefee9f52007-10-27 02:50:52 +0000909 self->begin_statement = PyMem_Malloc(size + 2);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000910 if (!self->begin_statement) {
Georg Brandl3dbca812008-07-23 16:10:53 +0000911 Py_DECREF(begin_statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000912 return -1;
913 }
914
Neal Norwitzefee9f52007-10-27 02:50:52 +0000915 strcpy(self->begin_statement, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000916 Py_DECREF(begin_statement);
917 }
918
919 return 0;
920}
921
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000922PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000923{
924 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000925 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000926 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000927 int rc;
928
929 if (!PyArg_ParseTuple(args, "O", &sql)) {
930 return NULL;
931 }
932
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000933 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000934
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000935 statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000936 if (!statement) {
937 return NULL;
938 }
939
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000940 rc = pysqlite_statement_create(statement, self, sql);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000941
942 if (rc != SQLITE_OK) {
943 if (rc == PYSQLITE_TOO_MUCH_SQL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000944 PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000945 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000946 PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string or unicode.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000947 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000948 (void)pysqlite_statement_reset(statement);
949 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000950 }
951
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +0000952 Py_CLEAR(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000953 } else {
954 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
955 if (!weakref) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +0000956 Py_CLEAR(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000957 goto error;
958 }
959
960 if (PyList_Append(self->statements, weakref) != 0) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +0000961 Py_CLEAR(weakref);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000962 goto error;
963 }
964
965 Py_DECREF(weakref);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000966 }
967
Thomas Wouters477c8d52006-05-27 19:21:47 +0000968error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000969 return (PyObject*)statement;
970}
971
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000972PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000973{
974 PyObject* cursor = 0;
975 PyObject* result = 0;
976 PyObject* method = 0;
977
978 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
979 if (!cursor) {
980 goto error;
981 }
982
983 method = PyObject_GetAttrString(cursor, "execute");
984 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +0000985 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000986 goto error;
987 }
988
989 result = PyObject_CallObject(method, args);
990 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +0000991 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000992 }
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) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001014 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001015 goto error;
1016 }
1017
1018 result = PyObject_CallObject(method, args);
1019 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001020 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001021 }
1022
1023error:
1024 Py_XDECREF(result);
1025 Py_XDECREF(method);
1026
1027 return cursor;
1028}
1029
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001030PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001031{
1032 PyObject* cursor = 0;
1033 PyObject* result = 0;
1034 PyObject* method = 0;
1035
1036 cursor = PyObject_CallMethod((PyObject*)self, "cursor", "");
1037 if (!cursor) {
1038 goto error;
1039 }
1040
1041 method = PyObject_GetAttrString(cursor, "executescript");
1042 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001043 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001044 goto error;
1045 }
1046
1047 result = PyObject_CallObject(method, args);
1048 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001049 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001050 }
1051
1052error:
1053 Py_XDECREF(result);
1054 Py_XDECREF(method);
1055
1056 return cursor;
1057}
1058
1059/* ------------------------- COLLATION CODE ------------------------ */
1060
1061static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001062pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001063 void* context,
1064 int text1_length, const void* text1_data,
1065 int text2_length, const void* text2_data)
1066{
1067 PyObject* callback = (PyObject*)context;
1068 PyObject* string1 = 0;
1069 PyObject* string2 = 0;
1070 PyGILState_STATE gilstate;
1071
1072 PyObject* retval = NULL;
1073 int result = 0;
1074
1075 gilstate = PyGILState_Ensure();
1076
1077 if (PyErr_Occurred()) {
1078 goto finally;
1079 }
1080
Guido van Rossum98297ee2007-11-06 21:34:58 +00001081 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1082 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001083
1084 if (!string1 || !string2) {
1085 goto finally; /* failed to allocate strings */
1086 }
1087
1088 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1089
1090 if (!retval) {
1091 /* execution failed */
1092 goto finally;
1093 }
1094
Christian Heimes217cfd12007-12-02 14:31:20 +00001095 result = PyLong_AsLong(retval);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001096 if (PyErr_Occurred()) {
1097 result = 0;
1098 }
1099
1100finally:
1101 Py_XDECREF(string1);
1102 Py_XDECREF(string2);
1103 Py_XDECREF(retval);
1104
1105 PyGILState_Release(gilstate);
1106
1107 return result;
1108}
1109
1110static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001111pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001112{
1113 PyObject* retval = NULL;
1114
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001115 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001116 goto finally;
1117 }
1118
1119 sqlite3_interrupt(self->db);
1120
1121 Py_INCREF(Py_None);
1122 retval = Py_None;
1123
1124finally:
1125 return retval;
1126}
1127
Christian Heimesbbe741d2008-03-28 10:53:29 +00001128/* Function author: Paul Kippes <kippesp@gmail.com>
1129 * Class method of Connection to call the Python function _iterdump
1130 * of the sqlite3 module.
1131 */
1132static PyObject *
1133pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1134{
1135 PyObject* retval = NULL;
1136 PyObject* module = NULL;
1137 PyObject* module_dict;
1138 PyObject* pyfn_iterdump;
1139
1140 if (!pysqlite_check_connection(self)) {
1141 goto finally;
1142 }
1143
1144 module = PyImport_ImportModule(MODULE_NAME ".dump");
1145 if (!module) {
1146 goto finally;
1147 }
1148
1149 module_dict = PyModule_GetDict(module);
1150 if (!module_dict) {
1151 goto finally;
1152 }
1153
1154 pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
1155 if (!pyfn_iterdump) {
1156 PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
1157 goto finally;
1158 }
1159
1160 args = PyTuple_New(1);
1161 if (!args) {
1162 goto finally;
1163 }
1164 Py_INCREF(self);
1165 PyTuple_SetItem(args, 0, (PyObject*)self);
1166 retval = PyObject_CallObject(pyfn_iterdump, args);
1167
1168finally:
1169 Py_XDECREF(args);
1170 Py_XDECREF(module);
1171 return retval;
1172}
1173
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001174static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001175pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001176{
1177 PyObject* callable;
1178 PyObject* uppercase_name = 0;
1179 PyObject* name;
1180 PyObject* retval;
1181 char* chk;
1182 int rc;
1183
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001184 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001185 goto finally;
1186 }
1187
Gerhard Häring6d214562007-08-10 18:15:11 +00001188 if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyUnicode_Type, &name, &callable)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001189 goto finally;
1190 }
1191
1192 uppercase_name = PyObject_CallMethod(name, "upper", "");
1193 if (!uppercase_name) {
1194 goto finally;
1195 }
1196
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001197 chk = _PyUnicode_AsString(uppercase_name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001198 while (*chk) {
1199 if ((*chk >= '0' && *chk <= '9')
1200 || (*chk >= 'A' && *chk <= 'Z')
1201 || (*chk == '_'))
1202 {
1203 chk++;
1204 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001205 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001206 goto finally;
1207 }
1208 }
1209
1210 if (callable != Py_None && !PyCallable_Check(callable)) {
1211 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1212 goto finally;
1213 }
1214
1215 if (callable != Py_None) {
1216 PyDict_SetItem(self->collations, uppercase_name, callable);
1217 } else {
1218 PyDict_DelItem(self->collations, uppercase_name);
1219 }
1220
1221 rc = sqlite3_create_collation(self->db,
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001222 _PyUnicode_AsString(uppercase_name),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001223 SQLITE_UTF8,
1224 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001225 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001226 if (rc != SQLITE_OK) {
1227 PyDict_DelItem(self->collations, uppercase_name);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001228 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001229 goto finally;
1230 }
1231
1232finally:
1233 Py_XDECREF(uppercase_name);
1234
1235 if (PyErr_Occurred()) {
1236 retval = NULL;
1237 } else {
1238 Py_INCREF(Py_None);
1239 retval = Py_None;
1240 }
1241
1242 return retval;
1243}
1244
Christian Heimesbbe741d2008-03-28 10:53:29 +00001245/* Called when the connection is used as a context manager. Returns itself as a
1246 * convenience to the caller. */
1247static PyObject *
1248pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1249{
1250 Py_INCREF(self);
1251 return (PyObject*)self;
1252}
1253
1254/** Called when the connection is used as a context manager. If there was any
1255 * exception, a rollback takes place; otherwise we commit. */
1256static PyObject *
1257pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1258{
1259 PyObject* exc_type, *exc_value, *exc_tb;
1260 char* method_name;
1261 PyObject* result;
1262
1263 if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1264 return NULL;
1265 }
1266
1267 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1268 method_name = "commit";
1269 } else {
1270 method_name = "rollback";
1271 }
1272
1273 result = PyObject_CallMethod((PyObject*)self, method_name, "");
1274 if (!result) {
1275 return NULL;
1276 }
1277 Py_DECREF(result);
1278
1279 Py_RETURN_FALSE;
1280}
1281
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001282static char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001283PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001284
1285static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001286 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1287 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001288 {NULL}
1289};
1290
1291static PyMethodDef connection_methods[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001292 {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001293 PyDoc_STR("Return a cursor for the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001294 {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001295 PyDoc_STR("Closes the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001296 {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001297 PyDoc_STR("Commit the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001298 {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001299 PyDoc_STR("Roll back the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001300 {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001301 PyDoc_STR("Creates a new function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001302 {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001303 PyDoc_STR("Creates a new aggregate. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001304 {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001305 PyDoc_STR("Sets authorizer callback. Non-standard.")},
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001306 {"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
1307 PyDoc_STR("Sets progress handler callback. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001308 {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001309 PyDoc_STR("Executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001310 {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001311 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001312 {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001313 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001314 {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001315 PyDoc_STR("Creates a collation function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001316 {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001317 PyDoc_STR("Abort any pending database operation. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001318 {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
Benjamin Petersond7b03282008-09-13 15:58:53 +00001319 PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001320 {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1321 PyDoc_STR("For context manager. Non-standard.")},
1322 {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1323 PyDoc_STR("For context manager. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001324 {NULL, NULL}
1325};
1326
1327static struct PyMemberDef connection_members[] =
1328{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001329 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1330 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1331 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1332 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1333 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1334 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1335 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1336 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1337 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1338 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001339 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1340 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001341 {NULL}
1342};
1343
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001344PyTypeObject pysqlite_ConnectionType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001345 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001346 MODULE_NAME ".Connection", /* tp_name */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001347 sizeof(pysqlite_Connection), /* tp_basicsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001348 0, /* tp_itemsize */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001349 (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001350 0, /* tp_print */
1351 0, /* tp_getattr */
1352 0, /* tp_setattr */
1353 0, /* tp_compare */
1354 0, /* tp_repr */
1355 0, /* tp_as_number */
1356 0, /* tp_as_sequence */
1357 0, /* tp_as_mapping */
1358 0, /* tp_hash */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001359 (ternaryfunc)pysqlite_connection_call, /* tp_call */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001360 0, /* tp_str */
1361 0, /* tp_getattro */
1362 0, /* tp_setattro */
1363 0, /* tp_as_buffer */
1364 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1365 connection_doc, /* tp_doc */
1366 0, /* tp_traverse */
1367 0, /* tp_clear */
1368 0, /* tp_richcompare */
1369 0, /* tp_weaklistoffset */
1370 0, /* tp_iter */
1371 0, /* tp_iternext */
1372 connection_methods, /* tp_methods */
1373 connection_members, /* tp_members */
1374 connection_getset, /* tp_getset */
1375 0, /* tp_base */
1376 0, /* tp_dict */
1377 0, /* tp_descr_get */
1378 0, /* tp_descr_set */
1379 0, /* tp_dictoffset */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001380 (initproc)pysqlite_connection_init, /* tp_init */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001381 0, /* tp_alloc */
1382 0, /* tp_new */
1383 0 /* tp_free */
1384};
1385
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001386extern int pysqlite_connection_setup_types(void)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001387{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001388 pysqlite_ConnectionType.tp_new = PyType_GenericNew;
1389 return PyType_Ready(&pysqlite_ConnectionType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001390}