blob: 7365a8888789ca1ce3c2cc6f3b6a2339e6c04690 [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
Martin v. Löwise75fc142013-11-07 18:46:53 +010044_Py_IDENTIFIER(cursor);
45
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000046static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level);
Gerhard Häringf9cee222010-03-05 15:20:03 +000047static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000048
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049
Benjamin Petersond7b03282008-09-13 15:58:53 +000050static void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000051{
52 /* in older SQLite versions, calling sqlite3_result_error in callbacks
53 * triggers a bug in SQLite that leads either to irritating results or
54 * segfaults, depending on the SQLite version */
55#if SQLITE_VERSION_NUMBER >= 3003003
56 sqlite3_result_error(ctx, errmsg, len);
57#else
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000058 PyErr_SetString(pysqlite_OperationalError, errmsg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059#endif
60}
61
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000062int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063{
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010064 static char *kwlist[] = {
65 "database", "timeout", "detect_types", "isolation_level",
66 "check_same_thread", "factory", "cached_statements", "uri",
67 NULL
68 };
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000069
70 char* database;
71 int detect_types = 0;
72 PyObject* isolation_level = NULL;
73 PyObject* factory = NULL;
74 int check_same_thread = 1;
75 int cached_statements = 100;
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010076 int uri = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000077 double timeout = 5.0;
78 int rc;
79
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010080 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOip", kwlist,
81 &database, &timeout, &detect_types,
82 &isolation_level, &check_same_thread,
83 &factory, &cached_statements, &uri))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000084 {
Gerhard Häringe7ea7452008-03-29 00:45:29 +000085 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000086 }
87
Gerhard Häringf9cee222010-03-05 15:20:03 +000088 self->initialized = 1;
89
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000090 self->begin_statement = NULL;
91
92 self->statement_cache = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000093 self->statements = NULL;
Gerhard Häringf9cee222010-03-05 15:20:03 +000094 self->cursors = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000095
96 Py_INCREF(Py_None);
97 self->row_factory = Py_None;
98
99 Py_INCREF(&PyUnicode_Type);
100 self->text_factory = (PyObject*)&PyUnicode_Type;
101
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100102#ifdef SQLITE_OPEN_URI
103 Py_BEGIN_ALLOW_THREADS
104 rc = sqlite3_open_v2(database, &self->db,
105 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
106 (uri ? SQLITE_OPEN_URI : 0), NULL);
107#else
108 if (uri) {
109 PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
110 return -1;
111 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000112 Py_BEGIN_ALLOW_THREADS
113 rc = sqlite3_open(database, &self->db);
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100114#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000115 Py_END_ALLOW_THREADS
116
117 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000118 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000119 return -1;
120 }
121
122 if (!isolation_level) {
Neal Norwitzefee9f52007-10-27 02:50:52 +0000123 isolation_level = PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000124 if (!isolation_level) {
125 return -1;
126 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000127 } else {
128 Py_INCREF(isolation_level);
129 }
130 self->isolation_level = NULL;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000131 pysqlite_connection_set_isolation_level(self, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000132 Py_DECREF(isolation_level);
133
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000134 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000135 if (PyErr_Occurred()) {
136 return -1;
137 }
138
Gerhard Häringf9cee222010-03-05 15:20:03 +0000139 self->created_statements = 0;
140 self->created_cursors = 0;
141
142 /* Create lists of weak references to statements/cursors */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000143 self->statements = PyList_New(0);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000144 self->cursors = PyList_New(0);
145 if (!self->statements || !self->cursors) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000146 return -1;
147 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000148
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000149 /* By default, the Cache class INCREFs the factory in its initializer, and
150 * decrefs it in its deallocator method. Since this would create a circular
151 * reference here, we're breaking it by decrementing self, and telling the
152 * cache class to not decref the factory (self) in its deallocator.
153 */
154 self->statement_cache->decref_factory = 0;
155 Py_DECREF(self);
156
157 self->inTransaction = 0;
158 self->detect_types = detect_types;
159 self->timeout = timeout;
160 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
Georg Brandldfd73442009-04-05 11:47:34 +0000161#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000162 self->thread_ident = PyThread_get_thread_ident();
Georg Brandldfd73442009-04-05 11:47:34 +0000163#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000164 self->check_same_thread = check_same_thread;
165
166 self->function_pinboard = PyDict_New();
167 if (!self->function_pinboard) {
168 return -1;
169 }
170
171 self->collations = PyDict_New();
172 if (!self->collations) {
173 return -1;
174 }
175
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000176 self->Warning = pysqlite_Warning;
177 self->Error = pysqlite_Error;
178 self->InterfaceError = pysqlite_InterfaceError;
179 self->DatabaseError = pysqlite_DatabaseError;
180 self->DataError = pysqlite_DataError;
181 self->OperationalError = pysqlite_OperationalError;
182 self->IntegrityError = pysqlite_IntegrityError;
183 self->InternalError = pysqlite_InternalError;
184 self->ProgrammingError = pysqlite_ProgrammingError;
185 self->NotSupportedError = pysqlite_NotSupportedError;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000186
187 return 0;
188}
189
Thomas Wouters477c8d52006-05-27 19:21:47 +0000190/* Empty the entire statement cache of this connection */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000191void pysqlite_flush_statement_cache(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000192{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000193 pysqlite_Node* node;
194 pysqlite_Statement* statement;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000195
196 node = self->statement_cache->first;
197
198 while (node) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000199 statement = (pysqlite_Statement*)(node->data);
200 (void)pysqlite_statement_finalize(statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000201 node = node->next;
202 }
203
204 Py_DECREF(self->statement_cache);
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000205 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000206 Py_DECREF(self);
207 self->statement_cache->decref_factory = 0;
208}
209
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000210/* action in (ACTION_RESET, ACTION_FINALIZE) */
Gerhard Häringf9cee222010-03-05 15:20:03 +0000211void pysqlite_do_all_statements(pysqlite_Connection* self, int action, int reset_cursors)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000213 int i;
214 PyObject* weakref;
215 PyObject* statement;
Gerhard Häringf9cee222010-03-05 15:20:03 +0000216 pysqlite_Cursor* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000217
Thomas Wouters477c8d52006-05-27 19:21:47 +0000218 for (i = 0; i < PyList_Size(self->statements); i++) {
219 weakref = PyList_GetItem(self->statements, i);
220 statement = PyWeakref_GetObject(weakref);
221 if (statement != Py_None) {
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500222 Py_INCREF(statement);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000223 if (action == ACTION_RESET) {
224 (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
225 } else {
226 (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
227 }
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500228 Py_DECREF(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000229 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000230 }
Gerhard Häringf9cee222010-03-05 15:20:03 +0000231
232 if (reset_cursors) {
233 for (i = 0; i < PyList_Size(self->cursors); i++) {
234 weakref = PyList_GetItem(self->cursors, i);
235 cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
236 if ((PyObject*)cursor != Py_None) {
237 cursor->reset = 1;
238 }
239 }
240 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000241}
242
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000243void pysqlite_connection_dealloc(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000244{
245 Py_XDECREF(self->statement_cache);
246
247 /* Clean up if user has not called .close() explicitly. */
248 if (self->db) {
249 Py_BEGIN_ALLOW_THREADS
250 sqlite3_close(self->db);
251 Py_END_ALLOW_THREADS
252 }
253
254 if (self->begin_statement) {
255 PyMem_Free(self->begin_statement);
256 }
257 Py_XDECREF(self->isolation_level);
258 Py_XDECREF(self->function_pinboard);
259 Py_XDECREF(self->row_factory);
260 Py_XDECREF(self->text_factory);
261 Py_XDECREF(self->collations);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000262 Py_XDECREF(self->statements);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000263 Py_XDECREF(self->cursors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000264
Christian Heimes90aa7642007-12-19 02:45:37 +0000265 Py_TYPE(self)->tp_free((PyObject*)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000266}
267
Gerhard Häringf9cee222010-03-05 15:20:03 +0000268/*
269 * Registers a cursor with the connection.
270 *
271 * 0 => error; 1 => ok
272 */
273int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
274{
275 PyObject* weakref;
276
277 weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
278 if (!weakref) {
279 goto error;
280 }
281
282 if (PyList_Append(connection->cursors, weakref) != 0) {
283 Py_CLEAR(weakref);
284 goto error;
285 }
286
287 Py_DECREF(weakref);
288
289 return 1;
290error:
291 return 0;
292}
293
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000294PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000295{
296 static char *kwlist[] = {"factory", NULL, NULL};
297 PyObject* factory = NULL;
298 PyObject* cursor;
299
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000300 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
301 &factory)) {
302 return NULL;
303 }
304
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000305 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000306 return NULL;
307 }
308
309 if (factory == NULL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000310 factory = (PyObject*)&pysqlite_CursorType;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000311 }
312
313 cursor = PyObject_CallFunction(factory, "O", self);
314
Gerhard Häringf9cee222010-03-05 15:20:03 +0000315 _pysqlite_drop_unused_cursor_references(self);
316
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000317 if (cursor && self->row_factory != Py_None) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000318 Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000319 Py_INCREF(self->row_factory);
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000320 ((pysqlite_Cursor*)cursor)->row_factory = self->row_factory;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000321 }
322
323 return cursor;
324}
325
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000326PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000327{
328 int rc;
329
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000330 if (!pysqlite_check_thread(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000331 return NULL;
332 }
333
Gerhard Häringf9cee222010-03-05 15:20:03 +0000334 pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000335
336 if (self->db) {
337 Py_BEGIN_ALLOW_THREADS
338 rc = sqlite3_close(self->db);
339 Py_END_ALLOW_THREADS
340
341 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000342 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000343 return NULL;
344 } else {
345 self->db = NULL;
346 }
347 }
348
349 Py_INCREF(Py_None);
350 return Py_None;
351}
352
353/*
354 * Checks if a connection object is usable (i. e. not closed).
355 *
356 * 0 => error; 1 => ok
357 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000358int pysqlite_check_connection(pysqlite_Connection* con)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000359{
Gerhard Häringf9cee222010-03-05 15:20:03 +0000360 if (!con->initialized) {
361 PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
362 return 0;
363 }
364
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000365 if (!con->db) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000366 PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000367 return 0;
368 } else {
369 return 1;
370 }
371}
372
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000373PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000374{
375 int rc;
376 const char* tail;
377 sqlite3_stmt* statement;
378
379 Py_BEGIN_ALLOW_THREADS
380 rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
381 Py_END_ALLOW_THREADS
382
383 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000384 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000385 goto error;
386 }
387
Benjamin Petersond7b03282008-09-13 15:58:53 +0000388 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000389 if (rc == SQLITE_DONE) {
390 self->inTransaction = 1;
391 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000392 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000393 }
394
395 Py_BEGIN_ALLOW_THREADS
396 rc = sqlite3_finalize(statement);
397 Py_END_ALLOW_THREADS
398
399 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000400 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000401 }
402
403error:
404 if (PyErr_Occurred()) {
405 return NULL;
406 } else {
407 Py_INCREF(Py_None);
408 return Py_None;
409 }
410}
411
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000412PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000413{
414 int rc;
415 const char* tail;
416 sqlite3_stmt* statement;
417
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000418 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000419 return NULL;
420 }
421
422 if (self->inTransaction) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000423 pysqlite_do_all_statements(self, ACTION_RESET, 0);
424
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000425 Py_BEGIN_ALLOW_THREADS
426 rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
427 Py_END_ALLOW_THREADS
428 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000429 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000430 goto error;
431 }
432
Benjamin Petersond7b03282008-09-13 15:58:53 +0000433 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000434 if (rc == SQLITE_DONE) {
435 self->inTransaction = 0;
436 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000437 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000438 }
439
440 Py_BEGIN_ALLOW_THREADS
441 rc = sqlite3_finalize(statement);
442 Py_END_ALLOW_THREADS
443 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000444 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000445 }
446
447 }
448
449error:
450 if (PyErr_Occurred()) {
451 return NULL;
452 } else {
453 Py_INCREF(Py_None);
454 return Py_None;
455 }
456}
457
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000458PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000459{
460 int rc;
461 const char* tail;
462 sqlite3_stmt* statement;
463
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000464 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000465 return NULL;
466 }
467
468 if (self->inTransaction) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000469 pysqlite_do_all_statements(self, ACTION_RESET, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000470
471 Py_BEGIN_ALLOW_THREADS
Georg Brandl0eaa9402007-08-11 15:39:18 +0000472 rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000473 Py_END_ALLOW_THREADS
474 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000475 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000476 goto error;
477 }
478
Benjamin Petersond7b03282008-09-13 15:58:53 +0000479 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000480 if (rc == SQLITE_DONE) {
481 self->inTransaction = 0;
482 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000483 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000484 }
485
486 Py_BEGIN_ALLOW_THREADS
487 rc = sqlite3_finalize(statement);
488 Py_END_ALLOW_THREADS
489 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000490 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000491 }
492
493 }
494
495error:
496 if (PyErr_Occurred()) {
497 return NULL;
498 } else {
499 Py_INCREF(Py_None);
500 return Py_None;
501 }
502}
503
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200504static int
505_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000506{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200507 if (py_val == Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000508 sqlite3_result_null(context);
Christian Heimes217cfd12007-12-02 14:31:20 +0000509 } else if (PyLong_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200510 sqlite_int64 value = _pysqlite_long_as_int64(py_val);
511 if (value == -1 && PyErr_Occurred())
512 return -1;
513 sqlite3_result_int64(context, value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000514 } else if (PyFloat_Check(py_val)) {
515 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
Guido van Rossumbae07c92007-10-08 02:46:15 +0000516 } else if (PyUnicode_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200517 const char *str = _PyUnicode_AsString(py_val);
518 if (str == NULL)
519 return -1;
520 sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000521 } else if (PyObject_CheckBuffer(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200522 const char* buffer;
523 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000524 if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) {
525 PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200526 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000527 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200528 sqlite3_result_blob(context, buffer, buflen, SQLITE_TRANSIENT);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000529 } else {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200530 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000531 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200532 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000533}
534
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000535PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000536{
537 PyObject* args;
538 int i;
539 sqlite3_value* cur_value;
540 PyObject* cur_py_value;
541 const char* val_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000542 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000543
544 args = PyTuple_New(argc);
545 if (!args) {
546 return NULL;
547 }
548
549 for (i = 0; i < argc; i++) {
550 cur_value = argv[i];
551 switch (sqlite3_value_type(argv[i])) {
552 case SQLITE_INTEGER:
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200553 cur_py_value = _pysqlite_long_from_int64(sqlite3_value_int64(cur_value));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000554 break;
555 case SQLITE_FLOAT:
556 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
557 break;
558 case SQLITE_TEXT:
559 val_str = (const char*)sqlite3_value_text(cur_value);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000560 cur_py_value = PyUnicode_FromString(val_str);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000561 /* TODO: have a way to show errors here */
562 if (!cur_py_value) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000563 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000564 Py_INCREF(Py_None);
565 cur_py_value = Py_None;
566 }
567 break;
568 case SQLITE_BLOB:
569 buflen = sqlite3_value_bytes(cur_value);
Christian Heimes72b710a2008-05-26 13:28:38 +0000570 cur_py_value = PyBytes_FromStringAndSize(
Guido van Rossumbae07c92007-10-08 02:46:15 +0000571 sqlite3_value_blob(cur_value), buflen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000572 break;
573 case SQLITE_NULL:
574 default:
575 Py_INCREF(Py_None);
576 cur_py_value = Py_None;
577 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000578
579 if (!cur_py_value) {
580 Py_DECREF(args);
581 return NULL;
582 }
583
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000584 PyTuple_SetItem(args, i, cur_py_value);
585
586 }
587
588 return args;
589}
590
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000591void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000592{
593 PyObject* args;
594 PyObject* py_func;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000595 PyObject* py_retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200596 int ok;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000597
Georg Brandldfd73442009-04-05 11:47:34 +0000598#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000599 PyGILState_STATE threadstate;
600
601 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000602#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000603
604 py_func = (PyObject*)sqlite3_user_data(context);
605
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000606 args = _pysqlite_build_py_params(context, argc, argv);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000607 if (args) {
608 py_retval = PyObject_CallObject(py_func, args);
609 Py_DECREF(args);
610 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000611
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200612 ok = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000613 if (py_retval) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200614 ok = _pysqlite_set_result(context, py_retval) == 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000615 Py_DECREF(py_retval);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200616 }
617 if (!ok) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000618 if (_enable_callback_tracebacks) {
619 PyErr_Print();
620 } else {
621 PyErr_Clear();
622 }
623 _sqlite3_result_error(context, "user-defined function raised exception", -1);
624 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000625
Georg Brandldfd73442009-04-05 11:47:34 +0000626#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000628#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000629}
630
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000631static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000632{
633 PyObject* args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000634 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000635 PyObject* aggregate_class;
636 PyObject** aggregate_instance;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000637 PyObject* stepmethod = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000638
Georg Brandldfd73442009-04-05 11:47:34 +0000639#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000640 PyGILState_STATE threadstate;
641
642 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000643#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000644
645 aggregate_class = (PyObject*)sqlite3_user_data(context);
646
647 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
648
649 if (*aggregate_instance == 0) {
650 *aggregate_instance = PyObject_CallFunction(aggregate_class, "");
651
Thomas Wouters477c8d52006-05-27 19:21:47 +0000652 if (PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000653 *aggregate_instance = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000654 if (_enable_callback_tracebacks) {
655 PyErr_Print();
656 } else {
657 PyErr_Clear();
658 }
659 _sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000660 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000661 }
662 }
663
664 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000665 if (!stepmethod) {
666 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000667 }
668
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000669 args = _pysqlite_build_py_params(context, argc, params);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000670 if (!args) {
671 goto error;
672 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000673
674 function_result = PyObject_CallObject(stepmethod, args);
675 Py_DECREF(args);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676
Thomas Wouters477c8d52006-05-27 19:21:47 +0000677 if (!function_result) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000678 if (_enable_callback_tracebacks) {
679 PyErr_Print();
680 } else {
681 PyErr_Clear();
682 }
683 _sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000684 }
685
Thomas Wouters477c8d52006-05-27 19:21:47 +0000686error:
687 Py_XDECREF(stepmethod);
688 Py_XDECREF(function_result);
689
Georg Brandldfd73442009-04-05 11:47:34 +0000690#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000691 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000692#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000693}
694
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000695void _pysqlite_final_callback(sqlite3_context* context)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000696{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200697 PyObject* function_result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000698 PyObject** aggregate_instance;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200699 _Py_IDENTIFIER(finalize);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200700 int ok;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200701 PyObject *exception, *value, *tb;
Victor Stinnerffff7632013-08-02 01:48:10 +0200702 int restore;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000703
Georg Brandldfd73442009-04-05 11:47:34 +0000704#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000705 PyGILState_STATE threadstate;
706
707 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000708#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000709
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000710 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
711 if (!*aggregate_instance) {
712 /* this branch is executed if there was an exception in the aggregate's
713 * __init__ */
714
Thomas Wouters477c8d52006-05-27 19:21:47 +0000715 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000716 }
717
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200718 /* Keep the exception (if any) of the last call to step() */
719 PyErr_Fetch(&exception, &value, &tb);
Victor Stinnerffff7632013-08-02 01:48:10 +0200720 restore = 1;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200721
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200722 function_result = _PyObject_CallMethodId(*aggregate_instance, &PyId_finalize, "");
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200723
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200724 Py_DECREF(*aggregate_instance);
725
726 ok = 0;
727 if (function_result) {
728 ok = _pysqlite_set_result(context, function_result) == 0;
729 Py_DECREF(function_result);
730 }
731 if (!ok) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000732 if (_enable_callback_tracebacks) {
733 PyErr_Print();
734 } else {
735 PyErr_Clear();
736 }
737 _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
Victor Stinnerffff7632013-08-02 01:48:10 +0200738#if SQLITE_VERSION_NUMBER < 3003003
739 /* with old SQLite versions, _sqlite3_result_error() sets a new Python
740 exception, so don't restore the previous exception */
741 restore = 0;
742#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000743 }
744
Victor Stinnerffff7632013-08-02 01:48:10 +0200745 if (restore) {
746 /* Restore the exception (if any) of the last call to step(),
747 but clear also the current exception if finalize() failed */
748 PyErr_Restore(exception, value, tb);
749 }
Victor Stinner3a857322013-07-22 08:34:32 +0200750
Thomas Wouters477c8d52006-05-27 19:21:47 +0000751error:
Georg Brandldfd73442009-04-05 11:47:34 +0000752#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000753 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000754#endif
Victor Stinnerb84fc0f2013-08-28 01:44:42 +0200755 /* explicit return to avoid a compilation error if WITH_THREAD
756 is not defined */
757 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758}
759
Gerhard Häringf9cee222010-03-05 15:20:03 +0000760static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761{
762 PyObject* new_list;
763 PyObject* weakref;
764 int i;
765
766 /* we only need to do this once in a while */
767 if (self->created_statements++ < 200) {
768 return;
769 }
770
771 self->created_statements = 0;
772
773 new_list = PyList_New(0);
774 if (!new_list) {
775 return;
776 }
777
778 for (i = 0; i < PyList_Size(self->statements); i++) {
779 weakref = PyList_GetItem(self->statements, i);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000780 if (PyWeakref_GetObject(weakref) != Py_None) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000781 if (PyList_Append(new_list, weakref) != 0) {
782 Py_DECREF(new_list);
783 return;
784 }
785 }
786 }
787
788 Py_DECREF(self->statements);
789 self->statements = new_list;
790}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000791
Gerhard Häringf9cee222010-03-05 15:20:03 +0000792static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
793{
794 PyObject* new_list;
795 PyObject* weakref;
796 int i;
797
798 /* we only need to do this once in a while */
799 if (self->created_cursors++ < 200) {
800 return;
801 }
802
803 self->created_cursors = 0;
804
805 new_list = PyList_New(0);
806 if (!new_list) {
807 return;
808 }
809
810 for (i = 0; i < PyList_Size(self->cursors); i++) {
811 weakref = PyList_GetItem(self->cursors, i);
812 if (PyWeakref_GetObject(weakref) != Py_None) {
813 if (PyList_Append(new_list, weakref) != 0) {
814 Py_DECREF(new_list);
815 return;
816 }
817 }
818 }
819
820 Py_DECREF(self->cursors);
821 self->cursors = new_list;
822}
823
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000824PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000825{
826 static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
827
828 PyObject* func;
829 char* name;
830 int narg;
831 int rc;
832
Gerhard Häringf9cee222010-03-05 15:20:03 +0000833 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
834 return NULL;
835 }
836
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000837 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
838 &name, &narg, &func))
839 {
840 return NULL;
841 }
842
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000843 rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000844
Thomas Wouters477c8d52006-05-27 19:21:47 +0000845 if (rc != SQLITE_OK) {
846 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000847 PyErr_SetString(pysqlite_OperationalError, "Error creating function");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000848 return NULL;
849 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000850 if (PyDict_SetItem(self->function_pinboard, func, Py_None) == -1)
851 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000852
Thomas Wouters477c8d52006-05-27 19:21:47 +0000853 Py_INCREF(Py_None);
854 return Py_None;
855 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000856}
857
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000858PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000859{
860 PyObject* aggregate_class;
861
862 int n_arg;
863 char* name;
864 static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
865 int rc;
866
Gerhard Häringf9cee222010-03-05 15:20:03 +0000867 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
868 return NULL;
869 }
870
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000871 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
872 kwlist, &name, &n_arg, &aggregate_class)) {
873 return NULL;
874 }
875
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000876 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 +0000877 if (rc != SQLITE_OK) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000878 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000879 PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000880 return NULL;
881 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000882 if (PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None) == -1)
883 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000884
885 Py_INCREF(Py_None);
886 return Py_None;
887 }
888}
889
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000890static 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 +0000891{
892 PyObject *ret;
893 int rc;
Georg Brandldfd73442009-04-05 11:47:34 +0000894#ifdef WITH_THREAD
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000895 PyGILState_STATE gilstate;
896
897 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000898#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000899
Victor Stinnerd4095d92013-07-26 22:23:33 +0200900 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000901
Victor Stinnerd4095d92013-07-26 22:23:33 +0200902 if (ret == NULL) {
903 if (_enable_callback_tracebacks)
904 PyErr_Print();
905 else
906 PyErr_Clear();
Victor Stinner41801f52013-07-21 13:05:38 +0200907
Victor Stinnerd4095d92013-07-26 22:23:33 +0200908 rc = SQLITE_DENY;
Victor Stinner41801f52013-07-21 13:05:38 +0200909 }
910 else {
Victor Stinnerd4095d92013-07-26 22:23:33 +0200911 if (PyLong_Check(ret)) {
912 rc = _PyLong_AsInt(ret);
913 if (rc == -1 && PyErr_Occurred()) {
914 if (_enable_callback_tracebacks)
915 PyErr_Print();
916 else
917 PyErr_Clear();
918 rc = SQLITE_DENY;
919 }
920 }
921 else {
922 rc = SQLITE_DENY;
923 }
924 Py_DECREF(ret);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000925 }
926
Georg Brandldfd73442009-04-05 11:47:34 +0000927#ifdef WITH_THREAD
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000928 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000929#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000930 return rc;
931}
932
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000933static int _progress_handler(void* user_arg)
934{
935 int rc;
936 PyObject *ret;
Georg Brandldfd73442009-04-05 11:47:34 +0000937#ifdef WITH_THREAD
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000938 PyGILState_STATE gilstate;
939
940 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000941#endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000942 ret = PyObject_CallFunction((PyObject*)user_arg, "");
943
944 if (!ret) {
945 if (_enable_callback_tracebacks) {
946 PyErr_Print();
947 } else {
948 PyErr_Clear();
949 }
950
Mark Dickinson934896d2009-02-21 20:59:32 +0000951 /* abort query if error occurred */
Victor Stinner86999502010-05-19 01:27:23 +0000952 rc = 1;
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000953 } else {
954 rc = (int)PyObject_IsTrue(ret);
955 Py_DECREF(ret);
956 }
957
Georg Brandldfd73442009-04-05 11:47:34 +0000958#ifdef WITH_THREAD
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000959 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000960#endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000961 return rc;
962}
963
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200964static void _trace_callback(void* user_arg, const char* statement_string)
965{
966 PyObject *py_statement = NULL;
967 PyObject *ret = NULL;
968
969#ifdef WITH_THREAD
970 PyGILState_STATE gilstate;
971
972 gilstate = PyGILState_Ensure();
973#endif
974 py_statement = PyUnicode_DecodeUTF8(statement_string,
975 strlen(statement_string), "replace");
976 if (py_statement) {
977 ret = PyObject_CallFunctionObjArgs((PyObject*)user_arg, py_statement, NULL);
978 Py_DECREF(py_statement);
979 }
980
981 if (ret) {
982 Py_DECREF(ret);
983 } else {
984 if (_enable_callback_tracebacks) {
985 PyErr_Print();
986 } else {
987 PyErr_Clear();
988 }
989 }
990
991#ifdef WITH_THREAD
992 PyGILState_Release(gilstate);
993#endif
994}
995
Gerhard Häringf9cee222010-03-05 15:20:03 +0000996static PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000997{
998 PyObject* authorizer_cb;
999
1000 static char *kwlist[] = { "authorizer_callback", NULL };
1001 int rc;
1002
Gerhard Häringf9cee222010-03-05 15:20:03 +00001003 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1004 return NULL;
1005 }
1006
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001007 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
1008 kwlist, &authorizer_cb)) {
1009 return NULL;
1010 }
1011
1012 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
1013
1014 if (rc != SQLITE_OK) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001015 PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001016 return NULL;
1017 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001018 if (PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None) == -1)
1019 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001020
1021 Py_INCREF(Py_None);
1022 return Py_None;
1023 }
1024}
1025
Gerhard Häringf9cee222010-03-05 15:20:03 +00001026static PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001027{
1028 PyObject* progress_handler;
1029 int n;
1030
1031 static char *kwlist[] = { "progress_handler", "n", NULL };
1032
Gerhard Häringf9cee222010-03-05 15:20:03 +00001033 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1034 return NULL;
1035 }
1036
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001037 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
1038 kwlist, &progress_handler, &n)) {
1039 return NULL;
1040 }
1041
1042 if (progress_handler == Py_None) {
1043 /* None clears the progress handler previously set */
1044 sqlite3_progress_handler(self->db, 0, 0, (void*)0);
1045 } else {
1046 sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
Gerhard Häringf9cee222010-03-05 15:20:03 +00001047 if (PyDict_SetItem(self->function_pinboard, progress_handler, Py_None) == -1)
1048 return NULL;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001049 }
1050
1051 Py_INCREF(Py_None);
1052 return Py_None;
1053}
1054
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001055static PyObject* pysqlite_connection_set_trace_callback(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1056{
1057 PyObject* trace_callback;
1058
1059 static char *kwlist[] = { "trace_callback", NULL };
1060
1061 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1062 return NULL;
1063 }
1064
1065 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_trace_callback",
1066 kwlist, &trace_callback)) {
1067 return NULL;
1068 }
1069
1070 if (trace_callback == Py_None) {
1071 /* None clears the trace callback previously set */
1072 sqlite3_trace(self->db, 0, (void*)0);
1073 } else {
1074 if (PyDict_SetItem(self->function_pinboard, trace_callback, Py_None) == -1)
1075 return NULL;
1076 sqlite3_trace(self->db, _trace_callback, trace_callback);
1077 }
1078
1079 Py_INCREF(Py_None);
1080 return Py_None;
1081}
1082
Gerhard Häringf9cee222010-03-05 15:20:03 +00001083#ifdef HAVE_LOAD_EXTENSION
1084static PyObject* pysqlite_enable_load_extension(pysqlite_Connection* self, PyObject* args)
1085{
1086 int rc;
1087 int onoff;
1088
1089 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1090 return NULL;
1091 }
1092
1093 if (!PyArg_ParseTuple(args, "i", &onoff)) {
1094 return NULL;
1095 }
1096
1097 rc = sqlite3_enable_load_extension(self->db, onoff);
1098
1099 if (rc != SQLITE_OK) {
1100 PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
1101 return NULL;
1102 } else {
1103 Py_INCREF(Py_None);
1104 return Py_None;
1105 }
1106}
1107
1108static PyObject* pysqlite_load_extension(pysqlite_Connection* self, PyObject* args)
1109{
1110 int rc;
1111 char* extension_name;
1112 char* errmsg;
1113
1114 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1115 return NULL;
1116 }
1117
1118 if (!PyArg_ParseTuple(args, "s", &extension_name)) {
1119 return NULL;
1120 }
1121
1122 rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1123 if (rc != 0) {
1124 PyErr_SetString(pysqlite_OperationalError, errmsg);
1125 return NULL;
1126 } else {
1127 Py_INCREF(Py_None);
1128 return Py_None;
1129 }
1130}
1131#endif
1132
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001133int pysqlite_check_thread(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001134{
Georg Brandldfd73442009-04-05 11:47:34 +00001135#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001136 if (self->check_same_thread) {
1137 if (PyThread_get_thread_ident() != self->thread_ident) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001138 PyErr_Format(pysqlite_ProgrammingError,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001139 "SQLite objects created in a thread can only be used in that same thread."
1140 "The object was created in thread id %ld and this is thread id %ld",
1141 self->thread_ident, PyThread_get_thread_ident());
1142 return 0;
1143 }
1144
1145 }
Georg Brandldfd73442009-04-05 11:47:34 +00001146#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001147 return 1;
1148}
1149
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001150static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001151{
1152 Py_INCREF(self->isolation_level);
1153 return self->isolation_level;
1154}
1155
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001156static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001157{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001158 if (!pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001159 return NULL;
1160 } else {
1161 return Py_BuildValue("i", sqlite3_total_changes(self->db));
1162 }
1163}
1164
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001165static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001166{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001167 PyObject* res;
1168 PyObject* begin_statement;
Georg Brandlceab6102007-11-25 00:45:05 +00001169 static PyObject* begin_word;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001170
1171 Py_XDECREF(self->isolation_level);
1172
1173 if (self->begin_statement) {
1174 PyMem_Free(self->begin_statement);
1175 self->begin_statement = NULL;
1176 }
1177
1178 if (isolation_level == Py_None) {
1179 Py_INCREF(Py_None);
1180 self->isolation_level = Py_None;
1181
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001182 res = pysqlite_connection_commit(self, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001183 if (!res) {
1184 return -1;
1185 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001186 Py_DECREF(res);
1187
1188 self->inTransaction = 0;
1189 } else {
Neal Norwitzefee9f52007-10-27 02:50:52 +00001190 const char *statement;
1191 Py_ssize_t size;
1192
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001193 Py_INCREF(isolation_level);
1194 self->isolation_level = isolation_level;
1195
Georg Brandlceab6102007-11-25 00:45:05 +00001196 if (!begin_word) {
1197 begin_word = PyUnicode_FromString("BEGIN ");
1198 if (!begin_word) return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001199 }
Georg Brandlceab6102007-11-25 00:45:05 +00001200 begin_statement = PyUnicode_Concat(begin_word, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001201 if (!begin_statement) {
1202 return -1;
1203 }
1204
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001205 statement = _PyUnicode_AsStringAndSize(begin_statement, &size);
Georg Brandl3dbca812008-07-23 16:10:53 +00001206 if (!statement) {
Victor Stinnerff27d6b2010-03-13 00:57:22 +00001207 Py_DECREF(begin_statement);
Georg Brandl3dbca812008-07-23 16:10:53 +00001208 return -1;
1209 }
Neal Norwitzefee9f52007-10-27 02:50:52 +00001210 self->begin_statement = PyMem_Malloc(size + 2);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001211 if (!self->begin_statement) {
Georg Brandl3dbca812008-07-23 16:10:53 +00001212 Py_DECREF(begin_statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001213 return -1;
1214 }
1215
Neal Norwitzefee9f52007-10-27 02:50:52 +00001216 strcpy(self->begin_statement, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001217 Py_DECREF(begin_statement);
1218 }
1219
1220 return 0;
1221}
1222
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001223PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001224{
1225 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001226 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001227 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001228 int rc;
1229
Gerhard Häringf9cee222010-03-05 15:20:03 +00001230 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1231 return NULL;
1232 }
1233
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001234 if (!PyArg_ParseTuple(args, "O", &sql))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001235 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001236
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001237 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001238
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001239 statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001240 if (!statement) {
1241 return NULL;
1242 }
1243
Victor Stinner0201f442010-03-13 03:28:34 +00001244 statement->db = NULL;
1245 statement->st = NULL;
1246 statement->sql = NULL;
1247 statement->in_use = 0;
1248 statement->in_weakreflist = NULL;
1249
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001250 rc = pysqlite_statement_create(statement, self, sql);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001251 if (rc != SQLITE_OK) {
1252 if (rc == PYSQLITE_TOO_MUCH_SQL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001253 PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001254 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001255 PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string or unicode.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001256 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001257 (void)pysqlite_statement_reset(statement);
1258 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001259 }
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001260 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001261 }
1262
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001263 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
1264 if (weakref == NULL)
1265 goto error;
1266 if (PyList_Append(self->statements, weakref) != 0) {
1267 Py_DECREF(weakref);
1268 goto error;
1269 }
1270 Py_DECREF(weakref);
1271
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001272 return (PyObject*)statement;
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001273
1274error:
1275 Py_DECREF(statement);
1276 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001277}
1278
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001279PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001280{
1281 PyObject* cursor = 0;
1282 PyObject* result = 0;
1283 PyObject* method = 0;
1284
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;
1313
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001314 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001315 if (!cursor) {
1316 goto error;
1317 }
1318
1319 method = PyObject_GetAttrString(cursor, "executemany");
1320 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001321 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001322 goto error;
1323 }
1324
1325 result = PyObject_CallObject(method, args);
1326 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001327 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001328 }
1329
1330error:
1331 Py_XDECREF(result);
1332 Py_XDECREF(method);
1333
1334 return cursor;
1335}
1336
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001337PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001338{
1339 PyObject* cursor = 0;
1340 PyObject* result = 0;
1341 PyObject* method = 0;
1342
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001343 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001344 if (!cursor) {
1345 goto error;
1346 }
1347
1348 method = PyObject_GetAttrString(cursor, "executescript");
1349 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001350 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001351 goto error;
1352 }
1353
1354 result = PyObject_CallObject(method, args);
1355 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001356 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001357 }
1358
1359error:
1360 Py_XDECREF(result);
1361 Py_XDECREF(method);
1362
1363 return cursor;
1364}
1365
1366/* ------------------------- COLLATION CODE ------------------------ */
1367
1368static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001369pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001370 void* context,
1371 int text1_length, const void* text1_data,
1372 int text2_length, const void* text2_data)
1373{
1374 PyObject* callback = (PyObject*)context;
1375 PyObject* string1 = 0;
1376 PyObject* string2 = 0;
Georg Brandldfd73442009-04-05 11:47:34 +00001377#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001378 PyGILState_STATE gilstate;
Georg Brandldfd73442009-04-05 11:47:34 +00001379#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001380 PyObject* retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001381 long longval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001382 int result = 0;
Georg Brandldfd73442009-04-05 11:47:34 +00001383#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001384 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +00001385#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001386
1387 if (PyErr_Occurred()) {
1388 goto finally;
1389 }
1390
Guido van Rossum98297ee2007-11-06 21:34:58 +00001391 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1392 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001393
1394 if (!string1 || !string2) {
1395 goto finally; /* failed to allocate strings */
1396 }
1397
1398 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1399
1400 if (!retval) {
1401 /* execution failed */
1402 goto finally;
1403 }
1404
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001405 longval = PyLong_AsLongAndOverflow(retval, &result);
1406 if (longval == -1 && PyErr_Occurred()) {
1407 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001408 result = 0;
1409 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001410 else if (!result) {
1411 if (longval > 0)
1412 result = 1;
1413 else if (longval < 0)
1414 result = -1;
1415 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001416
1417finally:
1418 Py_XDECREF(string1);
1419 Py_XDECREF(string2);
1420 Py_XDECREF(retval);
Georg Brandldfd73442009-04-05 11:47:34 +00001421#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001422 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +00001423#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001424 return result;
1425}
1426
1427static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001428pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001429{
1430 PyObject* retval = NULL;
1431
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001432 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001433 goto finally;
1434 }
1435
1436 sqlite3_interrupt(self->db);
1437
1438 Py_INCREF(Py_None);
1439 retval = Py_None;
1440
1441finally:
1442 return retval;
1443}
1444
Christian Heimesbbe741d2008-03-28 10:53:29 +00001445/* Function author: Paul Kippes <kippesp@gmail.com>
1446 * Class method of Connection to call the Python function _iterdump
1447 * of the sqlite3 module.
1448 */
1449static PyObject *
1450pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1451{
1452 PyObject* retval = NULL;
1453 PyObject* module = NULL;
1454 PyObject* module_dict;
1455 PyObject* pyfn_iterdump;
1456
1457 if (!pysqlite_check_connection(self)) {
1458 goto finally;
1459 }
1460
1461 module = PyImport_ImportModule(MODULE_NAME ".dump");
1462 if (!module) {
1463 goto finally;
1464 }
1465
1466 module_dict = PyModule_GetDict(module);
1467 if (!module_dict) {
1468 goto finally;
1469 }
1470
1471 pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
1472 if (!pyfn_iterdump) {
1473 PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
1474 goto finally;
1475 }
1476
1477 args = PyTuple_New(1);
1478 if (!args) {
1479 goto finally;
1480 }
1481 Py_INCREF(self);
1482 PyTuple_SetItem(args, 0, (PyObject*)self);
1483 retval = PyObject_CallObject(pyfn_iterdump, args);
1484
1485finally:
1486 Py_XDECREF(args);
1487 Py_XDECREF(module);
1488 return retval;
1489}
1490
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001491static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001492pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001493{
1494 PyObject* callable;
1495 PyObject* uppercase_name = 0;
1496 PyObject* name;
1497 PyObject* retval;
Victor Stinner35466c52010-04-22 11:23:23 +00001498 Py_ssize_t i, len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001499 _Py_IDENTIFIER(upper);
Victor Stinner35466c52010-04-22 11:23:23 +00001500 char *uppercase_name_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001501 int rc;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001502 unsigned int kind;
1503 void *data;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001504
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001505 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001506 goto finally;
1507 }
1508
Gerhard Häring6d214562007-08-10 18:15:11 +00001509 if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyUnicode_Type, &name, &callable)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001510 goto finally;
1511 }
1512
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001513 uppercase_name = _PyObject_CallMethodId(name, &PyId_upper, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001514 if (!uppercase_name) {
1515 goto finally;
1516 }
1517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001518 if (PyUnicode_READY(uppercase_name))
1519 goto finally;
1520 len = PyUnicode_GET_LENGTH(uppercase_name);
1521 kind = PyUnicode_KIND(uppercase_name);
1522 data = PyUnicode_DATA(uppercase_name);
1523 for (i=0; i<len; i++) {
1524 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1525 if ((ch >= '0' && ch <= '9')
1526 || (ch >= 'A' && ch <= 'Z')
1527 || (ch == '_'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001528 {
Victor Stinner35466c52010-04-22 11:23:23 +00001529 continue;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001530 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001531 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001532 goto finally;
1533 }
1534 }
1535
Victor Stinner35466c52010-04-22 11:23:23 +00001536 uppercase_name_str = _PyUnicode_AsString(uppercase_name);
1537 if (!uppercase_name_str)
1538 goto finally;
1539
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001540 if (callable != Py_None && !PyCallable_Check(callable)) {
1541 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1542 goto finally;
1543 }
1544
1545 if (callable != Py_None) {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001546 if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
1547 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001548 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001549 if (PyDict_DelItem(self->collations, uppercase_name) == -1)
1550 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001551 }
1552
1553 rc = sqlite3_create_collation(self->db,
Victor Stinner35466c52010-04-22 11:23:23 +00001554 uppercase_name_str,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001555 SQLITE_UTF8,
1556 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001557 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001558 if (rc != SQLITE_OK) {
1559 PyDict_DelItem(self->collations, uppercase_name);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001560 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001561 goto finally;
1562 }
1563
1564finally:
1565 Py_XDECREF(uppercase_name);
1566
1567 if (PyErr_Occurred()) {
1568 retval = NULL;
1569 } else {
1570 Py_INCREF(Py_None);
1571 retval = Py_None;
1572 }
1573
1574 return retval;
1575}
1576
Christian Heimesbbe741d2008-03-28 10:53:29 +00001577/* Called when the connection is used as a context manager. Returns itself as a
1578 * convenience to the caller. */
1579static PyObject *
1580pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1581{
1582 Py_INCREF(self);
1583 return (PyObject*)self;
1584}
1585
1586/** Called when the connection is used as a context manager. If there was any
1587 * exception, a rollback takes place; otherwise we commit. */
1588static PyObject *
1589pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1590{
1591 PyObject* exc_type, *exc_value, *exc_tb;
1592 char* method_name;
1593 PyObject* result;
1594
1595 if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1596 return NULL;
1597 }
1598
1599 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1600 method_name = "commit";
1601 } else {
1602 method_name = "rollback";
1603 }
1604
1605 result = PyObject_CallMethod((PyObject*)self, method_name, "");
1606 if (!result) {
1607 return NULL;
1608 }
1609 Py_DECREF(result);
1610
1611 Py_RETURN_FALSE;
1612}
1613
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001614static char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001615PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001616
1617static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001618 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1619 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001620 {NULL}
1621};
1622
1623static PyMethodDef connection_methods[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001624 {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001625 PyDoc_STR("Return a cursor for the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001626 {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001627 PyDoc_STR("Closes the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001628 {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001629 PyDoc_STR("Commit the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001630 {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001631 PyDoc_STR("Roll back the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001632 {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001633 PyDoc_STR("Creates a new function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001634 {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001635 PyDoc_STR("Creates a new aggregate. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001636 {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001637 PyDoc_STR("Sets authorizer callback. Non-standard.")},
Gerhard Häringf9cee222010-03-05 15:20:03 +00001638 #ifdef HAVE_LOAD_EXTENSION
1639 {"enable_load_extension", (PyCFunction)pysqlite_enable_load_extension, METH_VARARGS,
1640 PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
1641 {"load_extension", (PyCFunction)pysqlite_load_extension, METH_VARARGS,
1642 PyDoc_STR("Load SQLite extension module. Non-standard.")},
1643 #endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001644 {"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
1645 PyDoc_STR("Sets progress handler callback. Non-standard.")},
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001646 {"set_trace_callback", (PyCFunction)pysqlite_connection_set_trace_callback, METH_VARARGS|METH_KEYWORDS,
1647 PyDoc_STR("Sets a trace callback called for each SQL statement (passed as unicode). Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001648 {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001649 PyDoc_STR("Executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001650 {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001651 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001652 {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001653 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001654 {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001655 PyDoc_STR("Creates a collation function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001656 {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001657 PyDoc_STR("Abort any pending database operation. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001658 {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
Benjamin Petersond7b03282008-09-13 15:58:53 +00001659 PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001660 {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1661 PyDoc_STR("For context manager. Non-standard.")},
1662 {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1663 PyDoc_STR("For context manager. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001664 {NULL, NULL}
1665};
1666
1667static struct PyMemberDef connection_members[] =
1668{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001669 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1670 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1671 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1672 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1673 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1674 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1675 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1676 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1677 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1678 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001679 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1680 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
R. David Murrayd35251d2010-06-01 01:32:12 +00001681 {"in_transaction", T_BOOL, offsetof(pysqlite_Connection, inTransaction), READONLY},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001682 {NULL}
1683};
1684
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001685PyTypeObject pysqlite_ConnectionType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001686 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001687 MODULE_NAME ".Connection", /* tp_name */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001688 sizeof(pysqlite_Connection), /* tp_basicsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001689 0, /* tp_itemsize */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001690 (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001691 0, /* tp_print */
1692 0, /* tp_getattr */
1693 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001694 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001695 0, /* tp_repr */
1696 0, /* tp_as_number */
1697 0, /* tp_as_sequence */
1698 0, /* tp_as_mapping */
1699 0, /* tp_hash */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001700 (ternaryfunc)pysqlite_connection_call, /* tp_call */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001701 0, /* tp_str */
1702 0, /* tp_getattro */
1703 0, /* tp_setattro */
1704 0, /* tp_as_buffer */
1705 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1706 connection_doc, /* tp_doc */
1707 0, /* tp_traverse */
1708 0, /* tp_clear */
1709 0, /* tp_richcompare */
1710 0, /* tp_weaklistoffset */
1711 0, /* tp_iter */
1712 0, /* tp_iternext */
1713 connection_methods, /* tp_methods */
1714 connection_members, /* tp_members */
1715 connection_getset, /* tp_getset */
1716 0, /* tp_base */
1717 0, /* tp_dict */
1718 0, /* tp_descr_get */
1719 0, /* tp_descr_set */
1720 0, /* tp_dictoffset */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001721 (initproc)pysqlite_connection_init, /* tp_init */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001722 0, /* tp_alloc */
1723 0, /* tp_new */
1724 0 /* tp_free */
1725};
1726
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001727extern int pysqlite_connection_setup_types(void)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001728{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001729 pysqlite_ConnectionType.tp_new = PyType_GenericNew;
1730 return PyType_Ready(&pysqlite_ConnectionType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001731}