blob: 531516c277b7168470e709b5c7809e91731bf3b0 [file] [log] [blame]
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001/* connection.c - the connection type
2 *
Florent Xiclunac934f322010-09-03 23:47:32 +00003 * Copyright (C) 2004-2010 Gerhard Häring <gh@ghaering.de>
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004 *
5 * This file is part of pysqlite.
Victor Stinner86999502010-05-19 01:27:23 +00006 *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007 * 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"
R. David Murrayd35251d2010-06-01 01:32:12 +000026#include "structmember.h"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000027#include "connection.h"
28#include "statement.h"
29#include "cursor.h"
30#include "prepare_protocol.h"
31#include "util.h"
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000032
33#include "pythread.h"
34
Gerhard Häringe7ea7452008-03-29 00:45:29 +000035#define ACTION_FINALIZE 1
36#define ACTION_RESET 2
37
Gerhard Häringf9cee222010-03-05 15:20:03 +000038#if SQLITE_VERSION_NUMBER >= 3003008
39#ifndef SQLITE_OMIT_LOAD_EXTENSION
40#define HAVE_LOAD_EXTENSION
41#endif
42#endif
43
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000044static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level);
Gerhard Häringf9cee222010-03-05 15:20:03 +000045static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000046
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047
Benjamin Petersond7b03282008-09-13 15:58:53 +000048static void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049{
50 /* in older SQLite versions, calling sqlite3_result_error in callbacks
51 * triggers a bug in SQLite that leads either to irritating results or
52 * segfaults, depending on the SQLite version */
53#if SQLITE_VERSION_NUMBER >= 3003003
54 sqlite3_result_error(ctx, errmsg, len);
55#else
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000056 PyErr_SetString(pysqlite_OperationalError, errmsg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057#endif
58}
59
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000060int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061{
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010062 static char *kwlist[] = {
63 "database", "timeout", "detect_types", "isolation_level",
64 "check_same_thread", "factory", "cached_statements", "uri",
65 NULL
66 };
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000067
68 char* database;
69 int detect_types = 0;
70 PyObject* isolation_level = NULL;
71 PyObject* factory = NULL;
72 int check_same_thread = 1;
73 int cached_statements = 100;
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010074 int uri = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000075 double timeout = 5.0;
76 int rc;
77
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010078 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOip", kwlist,
79 &database, &timeout, &detect_types,
80 &isolation_level, &check_same_thread,
81 &factory, &cached_statements, &uri))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000082 {
Gerhard Häringe7ea7452008-03-29 00:45:29 +000083 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000084 }
85
Gerhard Häringf9cee222010-03-05 15:20:03 +000086 self->initialized = 1;
87
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000088 self->begin_statement = NULL;
89
90 self->statement_cache = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000091 self->statements = NULL;
Gerhard Häringf9cee222010-03-05 15:20:03 +000092 self->cursors = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000093
94 Py_INCREF(Py_None);
95 self->row_factory = Py_None;
96
97 Py_INCREF(&PyUnicode_Type);
98 self->text_factory = (PyObject*)&PyUnicode_Type;
99
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100100#ifdef SQLITE_OPEN_URI
101 Py_BEGIN_ALLOW_THREADS
102 rc = sqlite3_open_v2(database, &self->db,
103 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
104 (uri ? SQLITE_OPEN_URI : 0), NULL);
105#else
106 if (uri) {
107 PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
108 return -1;
109 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000110 Py_BEGIN_ALLOW_THREADS
111 rc = sqlite3_open(database, &self->db);
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100112#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000113 Py_END_ALLOW_THREADS
114
115 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000116 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000117 return -1;
118 }
119
120 if (!isolation_level) {
Neal Norwitzefee9f52007-10-27 02:50:52 +0000121 isolation_level = PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000122 if (!isolation_level) {
123 return -1;
124 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000125 } else {
126 Py_INCREF(isolation_level);
127 }
128 self->isolation_level = NULL;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000129 pysqlite_connection_set_isolation_level(self, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000130 Py_DECREF(isolation_level);
131
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000132 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000133 if (PyErr_Occurred()) {
134 return -1;
135 }
136
Gerhard Häringf9cee222010-03-05 15:20:03 +0000137 self->created_statements = 0;
138 self->created_cursors = 0;
139
140 /* Create lists of weak references to statements/cursors */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000141 self->statements = PyList_New(0);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000142 self->cursors = PyList_New(0);
143 if (!self->statements || !self->cursors) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000144 return -1;
145 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000146
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000147 /* By default, the Cache class INCREFs the factory in its initializer, and
148 * decrefs it in its deallocator method. Since this would create a circular
149 * reference here, we're breaking it by decrementing self, and telling the
150 * cache class to not decref the factory (self) in its deallocator.
151 */
152 self->statement_cache->decref_factory = 0;
153 Py_DECREF(self);
154
155 self->inTransaction = 0;
156 self->detect_types = detect_types;
157 self->timeout = timeout;
158 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
Georg Brandldfd73442009-04-05 11:47:34 +0000159#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000160 self->thread_ident = PyThread_get_thread_ident();
Georg Brandldfd73442009-04-05 11:47:34 +0000161#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000162 self->check_same_thread = check_same_thread;
163
164 self->function_pinboard = PyDict_New();
165 if (!self->function_pinboard) {
166 return -1;
167 }
168
169 self->collations = PyDict_New();
170 if (!self->collations) {
171 return -1;
172 }
173
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000174 self->Warning = pysqlite_Warning;
175 self->Error = pysqlite_Error;
176 self->InterfaceError = pysqlite_InterfaceError;
177 self->DatabaseError = pysqlite_DatabaseError;
178 self->DataError = pysqlite_DataError;
179 self->OperationalError = pysqlite_OperationalError;
180 self->IntegrityError = pysqlite_IntegrityError;
181 self->InternalError = pysqlite_InternalError;
182 self->ProgrammingError = pysqlite_ProgrammingError;
183 self->NotSupportedError = pysqlite_NotSupportedError;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184
185 return 0;
186}
187
Thomas Wouters477c8d52006-05-27 19:21:47 +0000188/* Empty the entire statement cache of this connection */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000189void pysqlite_flush_statement_cache(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000190{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000191 pysqlite_Node* node;
192 pysqlite_Statement* statement;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000193
194 node = self->statement_cache->first;
195
196 while (node) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000197 statement = (pysqlite_Statement*)(node->data);
198 (void)pysqlite_statement_finalize(statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000199 node = node->next;
200 }
201
202 Py_DECREF(self->statement_cache);
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000203 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000204 Py_DECREF(self);
205 self->statement_cache->decref_factory = 0;
206}
207
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000208/* action in (ACTION_RESET, ACTION_FINALIZE) */
Gerhard Häringf9cee222010-03-05 15:20:03 +0000209void pysqlite_do_all_statements(pysqlite_Connection* self, int action, int reset_cursors)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000211 int i;
212 PyObject* weakref;
213 PyObject* statement;
Gerhard Häringf9cee222010-03-05 15:20:03 +0000214 pysqlite_Cursor* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000215
Thomas Wouters477c8d52006-05-27 19:21:47 +0000216 for (i = 0; i < PyList_Size(self->statements); i++) {
217 weakref = PyList_GetItem(self->statements, i);
218 statement = PyWeakref_GetObject(weakref);
219 if (statement != Py_None) {
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500220 Py_INCREF(statement);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000221 if (action == ACTION_RESET) {
222 (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
223 } else {
224 (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
225 }
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500226 Py_DECREF(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000227 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000228 }
Gerhard Häringf9cee222010-03-05 15:20:03 +0000229
230 if (reset_cursors) {
231 for (i = 0; i < PyList_Size(self->cursors); i++) {
232 weakref = PyList_GetItem(self->cursors, i);
233 cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
234 if ((PyObject*)cursor != Py_None) {
235 cursor->reset = 1;
236 }
237 }
238 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000239}
240
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000241void pysqlite_connection_dealloc(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000242{
243 Py_XDECREF(self->statement_cache);
244
245 /* Clean up if user has not called .close() explicitly. */
246 if (self->db) {
247 Py_BEGIN_ALLOW_THREADS
248 sqlite3_close(self->db);
249 Py_END_ALLOW_THREADS
250 }
251
252 if (self->begin_statement) {
253 PyMem_Free(self->begin_statement);
254 }
255 Py_XDECREF(self->isolation_level);
256 Py_XDECREF(self->function_pinboard);
257 Py_XDECREF(self->row_factory);
258 Py_XDECREF(self->text_factory);
259 Py_XDECREF(self->collations);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000260 Py_XDECREF(self->statements);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000261 Py_XDECREF(self->cursors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000262
Christian Heimes90aa7642007-12-19 02:45:37 +0000263 Py_TYPE(self)->tp_free((PyObject*)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000264}
265
Gerhard Häringf9cee222010-03-05 15:20:03 +0000266/*
267 * Registers a cursor with the connection.
268 *
269 * 0 => error; 1 => ok
270 */
271int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
272{
273 PyObject* weakref;
274
275 weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
276 if (!weakref) {
277 goto error;
278 }
279
280 if (PyList_Append(connection->cursors, weakref) != 0) {
281 Py_CLEAR(weakref);
282 goto error;
283 }
284
285 Py_DECREF(weakref);
286
287 return 1;
288error:
289 return 0;
290}
291
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000292PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000293{
294 static char *kwlist[] = {"factory", NULL, NULL};
295 PyObject* factory = NULL;
296 PyObject* cursor;
297
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000298 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
299 &factory)) {
300 return NULL;
301 }
302
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000303 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000304 return NULL;
305 }
306
307 if (factory == NULL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000308 factory = (PyObject*)&pysqlite_CursorType;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000309 }
310
311 cursor = PyObject_CallFunction(factory, "O", self);
312
Gerhard Häringf9cee222010-03-05 15:20:03 +0000313 _pysqlite_drop_unused_cursor_references(self);
314
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000315 if (cursor && self->row_factory != Py_None) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000316 Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000317 Py_INCREF(self->row_factory);
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000318 ((pysqlite_Cursor*)cursor)->row_factory = self->row_factory;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000319 }
320
321 return cursor;
322}
323
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000324PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000325{
326 int rc;
327
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000328 if (!pysqlite_check_thread(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000329 return NULL;
330 }
331
Gerhard Häringf9cee222010-03-05 15:20:03 +0000332 pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000333
334 if (self->db) {
335 Py_BEGIN_ALLOW_THREADS
336 rc = sqlite3_close(self->db);
337 Py_END_ALLOW_THREADS
338
339 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000340 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000341 return NULL;
342 } else {
343 self->db = NULL;
344 }
345 }
346
347 Py_INCREF(Py_None);
348 return Py_None;
349}
350
351/*
352 * Checks if a connection object is usable (i. e. not closed).
353 *
354 * 0 => error; 1 => ok
355 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000356int pysqlite_check_connection(pysqlite_Connection* con)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000357{
Gerhard Häringf9cee222010-03-05 15:20:03 +0000358 if (!con->initialized) {
359 PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
360 return 0;
361 }
362
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000363 if (!con->db) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000364 PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000365 return 0;
366 } else {
367 return 1;
368 }
369}
370
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000371PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000372{
373 int rc;
374 const char* tail;
375 sqlite3_stmt* statement;
376
377 Py_BEGIN_ALLOW_THREADS
378 rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
379 Py_END_ALLOW_THREADS
380
381 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000382 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000383 goto error;
384 }
385
Benjamin Petersond7b03282008-09-13 15:58:53 +0000386 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000387 if (rc == SQLITE_DONE) {
388 self->inTransaction = 1;
389 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000390 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000391 }
392
393 Py_BEGIN_ALLOW_THREADS
394 rc = sqlite3_finalize(statement);
395 Py_END_ALLOW_THREADS
396
397 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000398 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000399 }
400
401error:
402 if (PyErr_Occurred()) {
403 return NULL;
404 } else {
405 Py_INCREF(Py_None);
406 return Py_None;
407 }
408}
409
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000410PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000411{
412 int rc;
413 const char* tail;
414 sqlite3_stmt* statement;
415
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000416 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417 return NULL;
418 }
419
420 if (self->inTransaction) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000421 pysqlite_do_all_statements(self, ACTION_RESET, 0);
422
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000423 Py_BEGIN_ALLOW_THREADS
424 rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
425 Py_END_ALLOW_THREADS
426 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000427 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000428 goto error;
429 }
430
Benjamin Petersond7b03282008-09-13 15:58:53 +0000431 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000432 if (rc == SQLITE_DONE) {
433 self->inTransaction = 0;
434 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000435 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000436 }
437
438 Py_BEGIN_ALLOW_THREADS
439 rc = sqlite3_finalize(statement);
440 Py_END_ALLOW_THREADS
441 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000442 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000443 }
444
445 }
446
447error:
448 if (PyErr_Occurred()) {
449 return NULL;
450 } else {
451 Py_INCREF(Py_None);
452 return Py_None;
453 }
454}
455
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000456PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000457{
458 int rc;
459 const char* tail;
460 sqlite3_stmt* statement;
461
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000462 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000463 return NULL;
464 }
465
466 if (self->inTransaction) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000467 pysqlite_do_all_statements(self, ACTION_RESET, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000468
469 Py_BEGIN_ALLOW_THREADS
Georg Brandl0eaa9402007-08-11 15:39:18 +0000470 rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000471 Py_END_ALLOW_THREADS
472 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000473 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000474 goto error;
475 }
476
Benjamin Petersond7b03282008-09-13 15:58:53 +0000477 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000478 if (rc == SQLITE_DONE) {
479 self->inTransaction = 0;
480 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000481 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000482 }
483
484 Py_BEGIN_ALLOW_THREADS
485 rc = sqlite3_finalize(statement);
486 Py_END_ALLOW_THREADS
487 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000488 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000489 }
490
491 }
492
493error:
494 if (PyErr_Occurred()) {
495 return NULL;
496 } else {
497 Py_INCREF(Py_None);
498 return Py_None;
499 }
500}
501
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200502static int
503_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000504{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200505 if (py_val == Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000506 sqlite3_result_null(context);
Christian Heimes217cfd12007-12-02 14:31:20 +0000507 } else if (PyLong_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200508 sqlite_int64 value = _pysqlite_long_as_int64(py_val);
509 if (value == -1 && PyErr_Occurred())
510 return -1;
511 sqlite3_result_int64(context, value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000512 } else if (PyFloat_Check(py_val)) {
513 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
Guido van Rossumbae07c92007-10-08 02:46:15 +0000514 } else if (PyUnicode_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200515 const char *str = _PyUnicode_AsString(py_val);
516 if (str == NULL)
517 return -1;
518 sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000519 } else if (PyObject_CheckBuffer(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200520 const char* buffer;
521 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000522 if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) {
523 PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200524 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000525 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200526 sqlite3_result_blob(context, buffer, buflen, SQLITE_TRANSIENT);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000527 } else {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200528 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000529 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200530 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000531}
532
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000533PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000534{
535 PyObject* args;
536 int i;
537 sqlite3_value* cur_value;
538 PyObject* cur_py_value;
539 const char* val_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000540 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000541
542 args = PyTuple_New(argc);
543 if (!args) {
544 return NULL;
545 }
546
547 for (i = 0; i < argc; i++) {
548 cur_value = argv[i];
549 switch (sqlite3_value_type(argv[i])) {
550 case SQLITE_INTEGER:
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200551 cur_py_value = _pysqlite_long_from_int64(sqlite3_value_int64(cur_value));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000552 break;
553 case SQLITE_FLOAT:
554 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
555 break;
556 case SQLITE_TEXT:
557 val_str = (const char*)sqlite3_value_text(cur_value);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000558 cur_py_value = PyUnicode_FromString(val_str);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000559 /* TODO: have a way to show errors here */
560 if (!cur_py_value) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000561 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000562 Py_INCREF(Py_None);
563 cur_py_value = Py_None;
564 }
565 break;
566 case SQLITE_BLOB:
567 buflen = sqlite3_value_bytes(cur_value);
Christian Heimes72b710a2008-05-26 13:28:38 +0000568 cur_py_value = PyBytes_FromStringAndSize(
Guido van Rossumbae07c92007-10-08 02:46:15 +0000569 sqlite3_value_blob(cur_value), buflen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000570 break;
571 case SQLITE_NULL:
572 default:
573 Py_INCREF(Py_None);
574 cur_py_value = Py_None;
575 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000576
577 if (!cur_py_value) {
578 Py_DECREF(args);
579 return NULL;
580 }
581
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000582 PyTuple_SetItem(args, i, cur_py_value);
583
584 }
585
586 return args;
587}
588
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000589void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000590{
591 PyObject* args;
592 PyObject* py_func;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000593 PyObject* py_retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200594 int ok;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000595
Georg Brandldfd73442009-04-05 11:47:34 +0000596#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000597 PyGILState_STATE threadstate;
598
599 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000600#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601
602 py_func = (PyObject*)sqlite3_user_data(context);
603
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000604 args = _pysqlite_build_py_params(context, argc, argv);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000605 if (args) {
606 py_retval = PyObject_CallObject(py_func, args);
607 Py_DECREF(args);
608 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000609
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200610 ok = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000611 if (py_retval) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200612 ok = _pysqlite_set_result(context, py_retval) == 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000613 Py_DECREF(py_retval);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200614 }
615 if (!ok) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000616 if (_enable_callback_tracebacks) {
617 PyErr_Print();
618 } else {
619 PyErr_Clear();
620 }
621 _sqlite3_result_error(context, "user-defined function raised exception", -1);
622 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000623
Georg Brandldfd73442009-04-05 11:47:34 +0000624#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000625 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000626#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627}
628
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000629static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000630{
631 PyObject* args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000632 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000633 PyObject* aggregate_class;
634 PyObject** aggregate_instance;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000635 PyObject* stepmethod = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000636
Georg Brandldfd73442009-04-05 11:47:34 +0000637#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000638 PyGILState_STATE threadstate;
639
640 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000641#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000642
643 aggregate_class = (PyObject*)sqlite3_user_data(context);
644
645 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
646
647 if (*aggregate_instance == 0) {
648 *aggregate_instance = PyObject_CallFunction(aggregate_class, "");
649
Thomas Wouters477c8d52006-05-27 19:21:47 +0000650 if (PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000651 *aggregate_instance = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000652 if (_enable_callback_tracebacks) {
653 PyErr_Print();
654 } else {
655 PyErr_Clear();
656 }
657 _sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000658 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000659 }
660 }
661
662 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000663 if (!stepmethod) {
664 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000665 }
666
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000667 args = _pysqlite_build_py_params(context, argc, params);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000668 if (!args) {
669 goto error;
670 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000671
672 function_result = PyObject_CallObject(stepmethod, args);
673 Py_DECREF(args);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000674
Thomas Wouters477c8d52006-05-27 19:21:47 +0000675 if (!function_result) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000676 if (_enable_callback_tracebacks) {
677 PyErr_Print();
678 } else {
679 PyErr_Clear();
680 }
681 _sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000682 }
683
Thomas Wouters477c8d52006-05-27 19:21:47 +0000684error:
685 Py_XDECREF(stepmethod);
686 Py_XDECREF(function_result);
687
Georg Brandldfd73442009-04-05 11:47:34 +0000688#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000689 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000690#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000691}
692
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000693void _pysqlite_final_callback(sqlite3_context* context)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200695 PyObject* function_result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000696 PyObject** aggregate_instance;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200697 _Py_IDENTIFIER(finalize);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200698 int ok;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200699 PyObject *exception, *value, *tb;
Victor Stinnerffff7632013-08-02 01:48:10 +0200700 int restore;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000701
Georg Brandldfd73442009-04-05 11:47:34 +0000702#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000703 PyGILState_STATE threadstate;
704
705 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000706#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000707
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000708 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
709 if (!*aggregate_instance) {
710 /* this branch is executed if there was an exception in the aggregate's
711 * __init__ */
712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000714 }
715
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200716 /* Keep the exception (if any) of the last call to step() */
717 PyErr_Fetch(&exception, &value, &tb);
Victor Stinnerffff7632013-08-02 01:48:10 +0200718 restore = 1;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200719
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200720 function_result = _PyObject_CallMethodId(*aggregate_instance, &PyId_finalize, "");
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200721
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200722 Py_DECREF(*aggregate_instance);
723
724 ok = 0;
725 if (function_result) {
726 ok = _pysqlite_set_result(context, function_result) == 0;
727 Py_DECREF(function_result);
728 }
729 if (!ok) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000730 if (_enable_callback_tracebacks) {
731 PyErr_Print();
732 } else {
733 PyErr_Clear();
734 }
735 _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
Victor Stinnerffff7632013-08-02 01:48:10 +0200736#if SQLITE_VERSION_NUMBER < 3003003
737 /* with old SQLite versions, _sqlite3_result_error() sets a new Python
738 exception, so don't restore the previous exception */
739 restore = 0;
740#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000741 }
742
Victor Stinnerffff7632013-08-02 01:48:10 +0200743 if (restore) {
744 /* Restore the exception (if any) of the last call to step(),
745 but clear also the current exception if finalize() failed */
746 PyErr_Restore(exception, value, tb);
747 }
Victor Stinner3a857322013-07-22 08:34:32 +0200748
Thomas Wouters477c8d52006-05-27 19:21:47 +0000749error:
Georg Brandldfd73442009-04-05 11:47:34 +0000750#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000751 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000752#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000753}
754
Gerhard Häringf9cee222010-03-05 15:20:03 +0000755static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000756{
757 PyObject* new_list;
758 PyObject* weakref;
759 int i;
760
761 /* we only need to do this once in a while */
762 if (self->created_statements++ < 200) {
763 return;
764 }
765
766 self->created_statements = 0;
767
768 new_list = PyList_New(0);
769 if (!new_list) {
770 return;
771 }
772
773 for (i = 0; i < PyList_Size(self->statements); i++) {
774 weakref = PyList_GetItem(self->statements, i);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000775 if (PyWeakref_GetObject(weakref) != Py_None) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776 if (PyList_Append(new_list, weakref) != 0) {
777 Py_DECREF(new_list);
778 return;
779 }
780 }
781 }
782
783 Py_DECREF(self->statements);
784 self->statements = new_list;
785}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786
Gerhard Häringf9cee222010-03-05 15:20:03 +0000787static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
788{
789 PyObject* new_list;
790 PyObject* weakref;
791 int i;
792
793 /* we only need to do this once in a while */
794 if (self->created_cursors++ < 200) {
795 return;
796 }
797
798 self->created_cursors = 0;
799
800 new_list = PyList_New(0);
801 if (!new_list) {
802 return;
803 }
804
805 for (i = 0; i < PyList_Size(self->cursors); i++) {
806 weakref = PyList_GetItem(self->cursors, i);
807 if (PyWeakref_GetObject(weakref) != Py_None) {
808 if (PyList_Append(new_list, weakref) != 0) {
809 Py_DECREF(new_list);
810 return;
811 }
812 }
813 }
814
815 Py_DECREF(self->cursors);
816 self->cursors = new_list;
817}
818
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000819PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000820{
821 static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
822
823 PyObject* func;
824 char* name;
825 int narg;
826 int rc;
827
Gerhard Häringf9cee222010-03-05 15:20:03 +0000828 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
829 return NULL;
830 }
831
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000832 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
833 &name, &narg, &func))
834 {
835 return NULL;
836 }
837
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000838 rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839
Thomas Wouters477c8d52006-05-27 19:21:47 +0000840 if (rc != SQLITE_OK) {
841 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000842 PyErr_SetString(pysqlite_OperationalError, "Error creating function");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000843 return NULL;
844 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000845 if (PyDict_SetItem(self->function_pinboard, func, Py_None) == -1)
846 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000847
Thomas Wouters477c8d52006-05-27 19:21:47 +0000848 Py_INCREF(Py_None);
849 return Py_None;
850 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000851}
852
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000853PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000854{
855 PyObject* aggregate_class;
856
857 int n_arg;
858 char* name;
859 static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
860 int rc;
861
Gerhard Häringf9cee222010-03-05 15:20:03 +0000862 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
863 return NULL;
864 }
865
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000866 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
867 kwlist, &name, &n_arg, &aggregate_class)) {
868 return NULL;
869 }
870
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000871 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 +0000872 if (rc != SQLITE_OK) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000873 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000874 PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000875 return NULL;
876 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000877 if (PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None) == -1)
878 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000879
880 Py_INCREF(Py_None);
881 return Py_None;
882 }
883}
884
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000885static 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 +0000886{
887 PyObject *ret;
888 int rc;
Georg Brandldfd73442009-04-05 11:47:34 +0000889#ifdef WITH_THREAD
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000890 PyGILState_STATE gilstate;
891
892 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000893#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000894
Victor Stinnerd4095d92013-07-26 22:23:33 +0200895 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000896
Victor Stinnerd4095d92013-07-26 22:23:33 +0200897 if (ret == NULL) {
898 if (_enable_callback_tracebacks)
899 PyErr_Print();
900 else
901 PyErr_Clear();
Victor Stinner41801f52013-07-21 13:05:38 +0200902
Victor Stinnerd4095d92013-07-26 22:23:33 +0200903 rc = SQLITE_DENY;
Victor Stinner41801f52013-07-21 13:05:38 +0200904 }
905 else {
Victor Stinnerd4095d92013-07-26 22:23:33 +0200906 if (PyLong_Check(ret)) {
907 rc = _PyLong_AsInt(ret);
908 if (rc == -1 && PyErr_Occurred()) {
909 if (_enable_callback_tracebacks)
910 PyErr_Print();
911 else
912 PyErr_Clear();
913 rc = SQLITE_DENY;
914 }
915 }
916 else {
917 rc = SQLITE_DENY;
918 }
919 Py_DECREF(ret);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000920 }
921
Georg Brandldfd73442009-04-05 11:47:34 +0000922#ifdef WITH_THREAD
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000923 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000924#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000925 return rc;
926}
927
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000928static int _progress_handler(void* user_arg)
929{
930 int rc;
931 PyObject *ret;
Georg Brandldfd73442009-04-05 11:47:34 +0000932#ifdef WITH_THREAD
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000933 PyGILState_STATE gilstate;
934
935 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000936#endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000937 ret = PyObject_CallFunction((PyObject*)user_arg, "");
938
939 if (!ret) {
940 if (_enable_callback_tracebacks) {
941 PyErr_Print();
942 } else {
943 PyErr_Clear();
944 }
945
Mark Dickinson934896d2009-02-21 20:59:32 +0000946 /* abort query if error occurred */
Victor Stinner86999502010-05-19 01:27:23 +0000947 rc = 1;
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000948 } else {
949 rc = (int)PyObject_IsTrue(ret);
950 Py_DECREF(ret);
951 }
952
Georg Brandldfd73442009-04-05 11:47:34 +0000953#ifdef WITH_THREAD
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000954 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000955#endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000956 return rc;
957}
958
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200959static void _trace_callback(void* user_arg, const char* statement_string)
960{
961 PyObject *py_statement = NULL;
962 PyObject *ret = NULL;
963
964#ifdef WITH_THREAD
965 PyGILState_STATE gilstate;
966
967 gilstate = PyGILState_Ensure();
968#endif
969 py_statement = PyUnicode_DecodeUTF8(statement_string,
970 strlen(statement_string), "replace");
971 if (py_statement) {
972 ret = PyObject_CallFunctionObjArgs((PyObject*)user_arg, py_statement, NULL);
973 Py_DECREF(py_statement);
974 }
975
976 if (ret) {
977 Py_DECREF(ret);
978 } else {
979 if (_enable_callback_tracebacks) {
980 PyErr_Print();
981 } else {
982 PyErr_Clear();
983 }
984 }
985
986#ifdef WITH_THREAD
987 PyGILState_Release(gilstate);
988#endif
989}
990
Gerhard Häringf9cee222010-03-05 15:20:03 +0000991static PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000992{
993 PyObject* authorizer_cb;
994
995 static char *kwlist[] = { "authorizer_callback", NULL };
996 int rc;
997
Gerhard Häringf9cee222010-03-05 15:20:03 +0000998 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
999 return NULL;
1000 }
1001
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001002 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
1003 kwlist, &authorizer_cb)) {
1004 return NULL;
1005 }
1006
1007 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
1008
1009 if (rc != SQLITE_OK) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001010 PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001011 return NULL;
1012 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001013 if (PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None) == -1)
1014 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001015
1016 Py_INCREF(Py_None);
1017 return Py_None;
1018 }
1019}
1020
Gerhard Häringf9cee222010-03-05 15:20:03 +00001021static PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001022{
1023 PyObject* progress_handler;
1024 int n;
1025
1026 static char *kwlist[] = { "progress_handler", "n", NULL };
1027
Gerhard Häringf9cee222010-03-05 15:20:03 +00001028 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1029 return NULL;
1030 }
1031
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001032 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
1033 kwlist, &progress_handler, &n)) {
1034 return NULL;
1035 }
1036
1037 if (progress_handler == Py_None) {
1038 /* None clears the progress handler previously set */
1039 sqlite3_progress_handler(self->db, 0, 0, (void*)0);
1040 } else {
1041 sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
Gerhard Häringf9cee222010-03-05 15:20:03 +00001042 if (PyDict_SetItem(self->function_pinboard, progress_handler, Py_None) == -1)
1043 return NULL;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001044 }
1045
1046 Py_INCREF(Py_None);
1047 return Py_None;
1048}
1049
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001050static PyObject* pysqlite_connection_set_trace_callback(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1051{
1052 PyObject* trace_callback;
1053
1054 static char *kwlist[] = { "trace_callback", NULL };
1055
1056 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1057 return NULL;
1058 }
1059
1060 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_trace_callback",
1061 kwlist, &trace_callback)) {
1062 return NULL;
1063 }
1064
1065 if (trace_callback == Py_None) {
1066 /* None clears the trace callback previously set */
1067 sqlite3_trace(self->db, 0, (void*)0);
1068 } else {
1069 if (PyDict_SetItem(self->function_pinboard, trace_callback, Py_None) == -1)
1070 return NULL;
1071 sqlite3_trace(self->db, _trace_callback, trace_callback);
1072 }
1073
1074 Py_INCREF(Py_None);
1075 return Py_None;
1076}
1077
Gerhard Häringf9cee222010-03-05 15:20:03 +00001078#ifdef HAVE_LOAD_EXTENSION
1079static PyObject* pysqlite_enable_load_extension(pysqlite_Connection* self, PyObject* args)
1080{
1081 int rc;
1082 int onoff;
1083
1084 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1085 return NULL;
1086 }
1087
1088 if (!PyArg_ParseTuple(args, "i", &onoff)) {
1089 return NULL;
1090 }
1091
1092 rc = sqlite3_enable_load_extension(self->db, onoff);
1093
1094 if (rc != SQLITE_OK) {
1095 PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
1096 return NULL;
1097 } else {
1098 Py_INCREF(Py_None);
1099 return Py_None;
1100 }
1101}
1102
1103static PyObject* pysqlite_load_extension(pysqlite_Connection* self, PyObject* args)
1104{
1105 int rc;
1106 char* extension_name;
1107 char* errmsg;
1108
1109 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1110 return NULL;
1111 }
1112
1113 if (!PyArg_ParseTuple(args, "s", &extension_name)) {
1114 return NULL;
1115 }
1116
1117 rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1118 if (rc != 0) {
1119 PyErr_SetString(pysqlite_OperationalError, errmsg);
1120 return NULL;
1121 } else {
1122 Py_INCREF(Py_None);
1123 return Py_None;
1124 }
1125}
1126#endif
1127
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001128int pysqlite_check_thread(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001129{
Georg Brandldfd73442009-04-05 11:47:34 +00001130#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001131 if (self->check_same_thread) {
1132 if (PyThread_get_thread_ident() != self->thread_ident) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001133 PyErr_Format(pysqlite_ProgrammingError,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001134 "SQLite objects created in a thread can only be used in that same thread."
1135 "The object was created in thread id %ld and this is thread id %ld",
1136 self->thread_ident, PyThread_get_thread_ident());
1137 return 0;
1138 }
1139
1140 }
Georg Brandldfd73442009-04-05 11:47:34 +00001141#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001142 return 1;
1143}
1144
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001145static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001146{
1147 Py_INCREF(self->isolation_level);
1148 return self->isolation_level;
1149}
1150
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001151static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001152{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001153 if (!pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001154 return NULL;
1155 } else {
1156 return Py_BuildValue("i", sqlite3_total_changes(self->db));
1157 }
1158}
1159
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001160static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001161{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001162 PyObject* res;
1163 PyObject* begin_statement;
Georg Brandlceab6102007-11-25 00:45:05 +00001164 static PyObject* begin_word;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001165
1166 Py_XDECREF(self->isolation_level);
1167
1168 if (self->begin_statement) {
1169 PyMem_Free(self->begin_statement);
1170 self->begin_statement = NULL;
1171 }
1172
1173 if (isolation_level == Py_None) {
1174 Py_INCREF(Py_None);
1175 self->isolation_level = Py_None;
1176
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001177 res = pysqlite_connection_commit(self, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001178 if (!res) {
1179 return -1;
1180 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001181 Py_DECREF(res);
1182
1183 self->inTransaction = 0;
1184 } else {
Neal Norwitzefee9f52007-10-27 02:50:52 +00001185 const char *statement;
1186 Py_ssize_t size;
1187
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001188 Py_INCREF(isolation_level);
1189 self->isolation_level = isolation_level;
1190
Georg Brandlceab6102007-11-25 00:45:05 +00001191 if (!begin_word) {
1192 begin_word = PyUnicode_FromString("BEGIN ");
1193 if (!begin_word) return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001194 }
Georg Brandlceab6102007-11-25 00:45:05 +00001195 begin_statement = PyUnicode_Concat(begin_word, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001196 if (!begin_statement) {
1197 return -1;
1198 }
1199
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001200 statement = _PyUnicode_AsStringAndSize(begin_statement, &size);
Georg Brandl3dbca812008-07-23 16:10:53 +00001201 if (!statement) {
Victor Stinnerff27d6b2010-03-13 00:57:22 +00001202 Py_DECREF(begin_statement);
Georg Brandl3dbca812008-07-23 16:10:53 +00001203 return -1;
1204 }
Neal Norwitzefee9f52007-10-27 02:50:52 +00001205 self->begin_statement = PyMem_Malloc(size + 2);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001206 if (!self->begin_statement) {
Georg Brandl3dbca812008-07-23 16:10:53 +00001207 Py_DECREF(begin_statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001208 return -1;
1209 }
1210
Neal Norwitzefee9f52007-10-27 02:50:52 +00001211 strcpy(self->begin_statement, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001212 Py_DECREF(begin_statement);
1213 }
1214
1215 return 0;
1216}
1217
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001218PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001219{
1220 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001221 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001222 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001223 int rc;
1224
Gerhard Häringf9cee222010-03-05 15:20:03 +00001225 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1226 return NULL;
1227 }
1228
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001229 if (!PyArg_ParseTuple(args, "O", &sql)) {
1230 return NULL;
1231 }
1232
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001233 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001234
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001235 statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001236 if (!statement) {
1237 return NULL;
1238 }
1239
Victor Stinner0201f442010-03-13 03:28:34 +00001240 statement->db = NULL;
1241 statement->st = NULL;
1242 statement->sql = NULL;
1243 statement->in_use = 0;
1244 statement->in_weakreflist = NULL;
1245
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001246 rc = pysqlite_statement_create(statement, self, sql);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001247
1248 if (rc != SQLITE_OK) {
1249 if (rc == PYSQLITE_TOO_MUCH_SQL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001250 PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001251 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001252 PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string or unicode.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001253 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001254 (void)pysqlite_statement_reset(statement);
1255 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001256 }
1257
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001258 Py_CLEAR(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001259 } else {
1260 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
1261 if (!weakref) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001262 Py_CLEAR(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001263 goto error;
1264 }
1265
1266 if (PyList_Append(self->statements, weakref) != 0) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001267 Py_CLEAR(weakref);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001268 goto error;
1269 }
1270
1271 Py_DECREF(weakref);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001272 }
1273
Thomas Wouters477c8d52006-05-27 19:21:47 +00001274error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001275 return (PyObject*)statement;
1276}
1277
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001278PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001279{
1280 PyObject* cursor = 0;
1281 PyObject* result = 0;
1282 PyObject* method = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001283 _Py_IDENTIFIER(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001284
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001285 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001286 if (!cursor) {
1287 goto error;
1288 }
1289
1290 method = PyObject_GetAttrString(cursor, "execute");
1291 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001292 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001293 goto error;
1294 }
1295
1296 result = PyObject_CallObject(method, args);
1297 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001298 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001299 }
1300
1301error:
1302 Py_XDECREF(result);
1303 Py_XDECREF(method);
1304
1305 return cursor;
1306}
1307
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001308PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001309{
1310 PyObject* cursor = 0;
1311 PyObject* result = 0;
1312 PyObject* method = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001313 _Py_IDENTIFIER(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001314
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001315 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001316 if (!cursor) {
1317 goto error;
1318 }
1319
1320 method = PyObject_GetAttrString(cursor, "executemany");
1321 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001322 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001323 goto error;
1324 }
1325
1326 result = PyObject_CallObject(method, args);
1327 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001328 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001329 }
1330
1331error:
1332 Py_XDECREF(result);
1333 Py_XDECREF(method);
1334
1335 return cursor;
1336}
1337
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001338PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001339{
1340 PyObject* cursor = 0;
1341 PyObject* result = 0;
1342 PyObject* method = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001343 _Py_IDENTIFIER(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001344
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001345 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001346 if (!cursor) {
1347 goto error;
1348 }
1349
1350 method = PyObject_GetAttrString(cursor, "executescript");
1351 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001352 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001353 goto error;
1354 }
1355
1356 result = PyObject_CallObject(method, args);
1357 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001358 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001359 }
1360
1361error:
1362 Py_XDECREF(result);
1363 Py_XDECREF(method);
1364
1365 return cursor;
1366}
1367
1368/* ------------------------- COLLATION CODE ------------------------ */
1369
1370static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001371pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001372 void* context,
1373 int text1_length, const void* text1_data,
1374 int text2_length, const void* text2_data)
1375{
1376 PyObject* callback = (PyObject*)context;
1377 PyObject* string1 = 0;
1378 PyObject* string2 = 0;
Georg Brandldfd73442009-04-05 11:47:34 +00001379#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001380 PyGILState_STATE gilstate;
Georg Brandldfd73442009-04-05 11:47:34 +00001381#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001382 PyObject* retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001383 long longval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001384 int result = 0;
Georg Brandldfd73442009-04-05 11:47:34 +00001385#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001386 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +00001387#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001388
1389 if (PyErr_Occurred()) {
1390 goto finally;
1391 }
1392
Guido van Rossum98297ee2007-11-06 21:34:58 +00001393 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1394 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001395
1396 if (!string1 || !string2) {
1397 goto finally; /* failed to allocate strings */
1398 }
1399
1400 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1401
1402 if (!retval) {
1403 /* execution failed */
1404 goto finally;
1405 }
1406
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001407 longval = PyLong_AsLongAndOverflow(retval, &result);
1408 if (longval == -1 && PyErr_Occurred()) {
1409 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001410 result = 0;
1411 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001412 else if (!result) {
1413 if (longval > 0)
1414 result = 1;
1415 else if (longval < 0)
1416 result = -1;
1417 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001418
1419finally:
1420 Py_XDECREF(string1);
1421 Py_XDECREF(string2);
1422 Py_XDECREF(retval);
Georg Brandldfd73442009-04-05 11:47:34 +00001423#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001424 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +00001425#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001426 return result;
1427}
1428
1429static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001430pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001431{
1432 PyObject* retval = NULL;
1433
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001434 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001435 goto finally;
1436 }
1437
1438 sqlite3_interrupt(self->db);
1439
1440 Py_INCREF(Py_None);
1441 retval = Py_None;
1442
1443finally:
1444 return retval;
1445}
1446
Christian Heimesbbe741d2008-03-28 10:53:29 +00001447/* Function author: Paul Kippes <kippesp@gmail.com>
1448 * Class method of Connection to call the Python function _iterdump
1449 * of the sqlite3 module.
1450 */
1451static PyObject *
1452pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1453{
1454 PyObject* retval = NULL;
1455 PyObject* module = NULL;
1456 PyObject* module_dict;
1457 PyObject* pyfn_iterdump;
1458
1459 if (!pysqlite_check_connection(self)) {
1460 goto finally;
1461 }
1462
1463 module = PyImport_ImportModule(MODULE_NAME ".dump");
1464 if (!module) {
1465 goto finally;
1466 }
1467
1468 module_dict = PyModule_GetDict(module);
1469 if (!module_dict) {
1470 goto finally;
1471 }
1472
1473 pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
1474 if (!pyfn_iterdump) {
1475 PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
1476 goto finally;
1477 }
1478
1479 args = PyTuple_New(1);
1480 if (!args) {
1481 goto finally;
1482 }
1483 Py_INCREF(self);
1484 PyTuple_SetItem(args, 0, (PyObject*)self);
1485 retval = PyObject_CallObject(pyfn_iterdump, args);
1486
1487finally:
1488 Py_XDECREF(args);
1489 Py_XDECREF(module);
1490 return retval;
1491}
1492
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001493static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001494pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001495{
1496 PyObject* callable;
1497 PyObject* uppercase_name = 0;
1498 PyObject* name;
1499 PyObject* retval;
Victor Stinner35466c52010-04-22 11:23:23 +00001500 Py_ssize_t i, len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001501 _Py_IDENTIFIER(upper);
Victor Stinner35466c52010-04-22 11:23:23 +00001502 char *uppercase_name_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001503 int rc;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001504 unsigned int kind;
1505 void *data;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001506
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001507 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001508 goto finally;
1509 }
1510
Gerhard Häring6d214562007-08-10 18:15:11 +00001511 if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyUnicode_Type, &name, &callable)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001512 goto finally;
1513 }
1514
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001515 uppercase_name = _PyObject_CallMethodId(name, &PyId_upper, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001516 if (!uppercase_name) {
1517 goto finally;
1518 }
1519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001520 if (PyUnicode_READY(uppercase_name))
1521 goto finally;
1522 len = PyUnicode_GET_LENGTH(uppercase_name);
1523 kind = PyUnicode_KIND(uppercase_name);
1524 data = PyUnicode_DATA(uppercase_name);
1525 for (i=0; i<len; i++) {
1526 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1527 if ((ch >= '0' && ch <= '9')
1528 || (ch >= 'A' && ch <= 'Z')
1529 || (ch == '_'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001530 {
Victor Stinner35466c52010-04-22 11:23:23 +00001531 continue;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001532 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001533 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001534 goto finally;
1535 }
1536 }
1537
Victor Stinner35466c52010-04-22 11:23:23 +00001538 uppercase_name_str = _PyUnicode_AsString(uppercase_name);
1539 if (!uppercase_name_str)
1540 goto finally;
1541
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001542 if (callable != Py_None && !PyCallable_Check(callable)) {
1543 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1544 goto finally;
1545 }
1546
1547 if (callable != Py_None) {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001548 if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
1549 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001550 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001551 if (PyDict_DelItem(self->collations, uppercase_name) == -1)
1552 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001553 }
1554
1555 rc = sqlite3_create_collation(self->db,
Victor Stinner35466c52010-04-22 11:23:23 +00001556 uppercase_name_str,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001557 SQLITE_UTF8,
1558 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001559 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001560 if (rc != SQLITE_OK) {
1561 PyDict_DelItem(self->collations, uppercase_name);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001562 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001563 goto finally;
1564 }
1565
1566finally:
1567 Py_XDECREF(uppercase_name);
1568
1569 if (PyErr_Occurred()) {
1570 retval = NULL;
1571 } else {
1572 Py_INCREF(Py_None);
1573 retval = Py_None;
1574 }
1575
1576 return retval;
1577}
1578
Christian Heimesbbe741d2008-03-28 10:53:29 +00001579/* Called when the connection is used as a context manager. Returns itself as a
1580 * convenience to the caller. */
1581static PyObject *
1582pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1583{
1584 Py_INCREF(self);
1585 return (PyObject*)self;
1586}
1587
1588/** Called when the connection is used as a context manager. If there was any
1589 * exception, a rollback takes place; otherwise we commit. */
1590static PyObject *
1591pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1592{
1593 PyObject* exc_type, *exc_value, *exc_tb;
1594 char* method_name;
1595 PyObject* result;
1596
1597 if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1598 return NULL;
1599 }
1600
1601 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1602 method_name = "commit";
1603 } else {
1604 method_name = "rollback";
1605 }
1606
1607 result = PyObject_CallMethod((PyObject*)self, method_name, "");
1608 if (!result) {
1609 return NULL;
1610 }
1611 Py_DECREF(result);
1612
1613 Py_RETURN_FALSE;
1614}
1615
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001616static char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001617PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001618
1619static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001620 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1621 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001622 {NULL}
1623};
1624
1625static PyMethodDef connection_methods[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001626 {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001627 PyDoc_STR("Return a cursor for the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001628 {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001629 PyDoc_STR("Closes the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001630 {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001631 PyDoc_STR("Commit the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001632 {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001633 PyDoc_STR("Roll back the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001634 {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001635 PyDoc_STR("Creates a new function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001636 {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001637 PyDoc_STR("Creates a new aggregate. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001638 {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001639 PyDoc_STR("Sets authorizer callback. Non-standard.")},
Gerhard Häringf9cee222010-03-05 15:20:03 +00001640 #ifdef HAVE_LOAD_EXTENSION
1641 {"enable_load_extension", (PyCFunction)pysqlite_enable_load_extension, METH_VARARGS,
1642 PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
1643 {"load_extension", (PyCFunction)pysqlite_load_extension, METH_VARARGS,
1644 PyDoc_STR("Load SQLite extension module. Non-standard.")},
1645 #endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001646 {"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
1647 PyDoc_STR("Sets progress handler callback. Non-standard.")},
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001648 {"set_trace_callback", (PyCFunction)pysqlite_connection_set_trace_callback, METH_VARARGS|METH_KEYWORDS,
1649 PyDoc_STR("Sets a trace callback called for each SQL statement (passed as unicode). Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001650 {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001651 PyDoc_STR("Executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001652 {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001653 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001654 {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001655 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001656 {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001657 PyDoc_STR("Creates a collation function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001658 {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001659 PyDoc_STR("Abort any pending database operation. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001660 {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
Benjamin Petersond7b03282008-09-13 15:58:53 +00001661 PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001662 {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1663 PyDoc_STR("For context manager. Non-standard.")},
1664 {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1665 PyDoc_STR("For context manager. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001666 {NULL, NULL}
1667};
1668
1669static struct PyMemberDef connection_members[] =
1670{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001671 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1672 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1673 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1674 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1675 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1676 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1677 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1678 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1679 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1680 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001681 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1682 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
R. David Murrayd35251d2010-06-01 01:32:12 +00001683 {"in_transaction", T_BOOL, offsetof(pysqlite_Connection, inTransaction), READONLY},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001684 {NULL}
1685};
1686
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001687PyTypeObject pysqlite_ConnectionType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001688 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001689 MODULE_NAME ".Connection", /* tp_name */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001690 sizeof(pysqlite_Connection), /* tp_basicsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001691 0, /* tp_itemsize */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001692 (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001693 0, /* tp_print */
1694 0, /* tp_getattr */
1695 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001696 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001697 0, /* tp_repr */
1698 0, /* tp_as_number */
1699 0, /* tp_as_sequence */
1700 0, /* tp_as_mapping */
1701 0, /* tp_hash */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001702 (ternaryfunc)pysqlite_connection_call, /* tp_call */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001703 0, /* tp_str */
1704 0, /* tp_getattro */
1705 0, /* tp_setattro */
1706 0, /* tp_as_buffer */
1707 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1708 connection_doc, /* tp_doc */
1709 0, /* tp_traverse */
1710 0, /* tp_clear */
1711 0, /* tp_richcompare */
1712 0, /* tp_weaklistoffset */
1713 0, /* tp_iter */
1714 0, /* tp_iternext */
1715 connection_methods, /* tp_methods */
1716 connection_members, /* tp_members */
1717 connection_getset, /* tp_getset */
1718 0, /* tp_base */
1719 0, /* tp_dict */
1720 0, /* tp_descr_get */
1721 0, /* tp_descr_set */
1722 0, /* tp_dictoffset */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001723 (initproc)pysqlite_connection_init, /* tp_init */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001724 0, /* tp_alloc */
1725 0, /* tp_new */
1726 0 /* tp_free */
1727};
1728
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001729extern int pysqlite_connection_setup_types(void)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001730{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001731 pysqlite_ConnectionType.tp_new = PyType_GenericNew;
1732 return PyType_Ready(&pysqlite_ConnectionType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001733}