blob: b56ddac136ea6c4c65e608f9cffc1bb33e03f685 [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"
32#include "sqlitecompat.h"
33
34#include "pythread.h"
35
Gerhard Häringe7ea7452008-03-29 00:45:29 +000036#define ACTION_FINALIZE 1
37#define ACTION_RESET 2
38
Gerhard Häringf9cee222010-03-05 15:20:03 +000039#if SQLITE_VERSION_NUMBER >= 3003008
40#ifndef SQLITE_OMIT_LOAD_EXTENSION
41#define HAVE_LOAD_EXTENSION
42#endif
43#endif
44
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000045static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level);
Gerhard Häringf9cee222010-03-05 15:20:03 +000046static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000047
Thomas Wouters0e3f5912006-08-11 14:57:12 +000048
Benjamin Petersond7b03282008-09-13 15:58:53 +000049static void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050{
51 /* in older SQLite versions, calling sqlite3_result_error in callbacks
52 * triggers a bug in SQLite that leads either to irritating results or
53 * segfaults, depending on the SQLite version */
54#if SQLITE_VERSION_NUMBER >= 3003003
55 sqlite3_result_error(ctx, errmsg, len);
56#else
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000057 PyErr_SetString(pysqlite_OperationalError, errmsg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000058#endif
59}
60
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000061int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000062{
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010063 static char *kwlist[] = {
64 "database", "timeout", "detect_types", "isolation_level",
65 "check_same_thread", "factory", "cached_statements", "uri",
66 NULL
67 };
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69 char* database;
70 int detect_types = 0;
71 PyObject* isolation_level = NULL;
72 PyObject* factory = NULL;
73 int check_same_thread = 1;
74 int cached_statements = 100;
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010075 int uri = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000076 double timeout = 5.0;
77 int rc;
78
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010079 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOip", kwlist,
80 &database, &timeout, &detect_types,
81 &isolation_level, &check_same_thread,
82 &factory, &cached_statements, &uri))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000083 {
Gerhard Häringe7ea7452008-03-29 00:45:29 +000084 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000085 }
86
Gerhard Häringf9cee222010-03-05 15:20:03 +000087 self->initialized = 1;
88
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089 self->begin_statement = NULL;
90
91 self->statement_cache = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000092 self->statements = NULL;
Gerhard Häringf9cee222010-03-05 15:20:03 +000093 self->cursors = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000094
95 Py_INCREF(Py_None);
96 self->row_factory = Py_None;
97
98 Py_INCREF(&PyUnicode_Type);
99 self->text_factory = (PyObject*)&PyUnicode_Type;
100
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100101#ifdef SQLITE_OPEN_URI
102 Py_BEGIN_ALLOW_THREADS
103 rc = sqlite3_open_v2(database, &self->db,
104 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
105 (uri ? SQLITE_OPEN_URI : 0), NULL);
106#else
107 if (uri) {
108 PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
109 return -1;
110 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000111 Py_BEGIN_ALLOW_THREADS
112 rc = sqlite3_open(database, &self->db);
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100113#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000114 Py_END_ALLOW_THREADS
115
116 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000117 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 return -1;
119 }
120
121 if (!isolation_level) {
Neal Norwitzefee9f52007-10-27 02:50:52 +0000122 isolation_level = PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123 if (!isolation_level) {
124 return -1;
125 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000126 } else {
127 Py_INCREF(isolation_level);
128 }
129 self->isolation_level = NULL;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000130 pysqlite_connection_set_isolation_level(self, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000131 Py_DECREF(isolation_level);
132
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000133 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000134 if (PyErr_Occurred()) {
135 return -1;
136 }
137
Gerhard Häringf9cee222010-03-05 15:20:03 +0000138 self->created_statements = 0;
139 self->created_cursors = 0;
140
141 /* Create lists of weak references to statements/cursors */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000142 self->statements = PyList_New(0);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000143 self->cursors = PyList_New(0);
144 if (!self->statements || !self->cursors) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000145 return -1;
146 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000147
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000148 /* By default, the Cache class INCREFs the factory in its initializer, and
149 * decrefs it in its deallocator method. Since this would create a circular
150 * reference here, we're breaking it by decrementing self, and telling the
151 * cache class to not decref the factory (self) in its deallocator.
152 */
153 self->statement_cache->decref_factory = 0;
154 Py_DECREF(self);
155
156 self->inTransaction = 0;
157 self->detect_types = detect_types;
158 self->timeout = timeout;
159 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
Georg Brandldfd73442009-04-05 11:47:34 +0000160#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000161 self->thread_ident = PyThread_get_thread_ident();
Georg Brandldfd73442009-04-05 11:47:34 +0000162#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163 self->check_same_thread = check_same_thread;
164
165 self->function_pinboard = PyDict_New();
166 if (!self->function_pinboard) {
167 return -1;
168 }
169
170 self->collations = PyDict_New();
171 if (!self->collations) {
172 return -1;
173 }
174
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000175 self->Warning = pysqlite_Warning;
176 self->Error = pysqlite_Error;
177 self->InterfaceError = pysqlite_InterfaceError;
178 self->DatabaseError = pysqlite_DatabaseError;
179 self->DataError = pysqlite_DataError;
180 self->OperationalError = pysqlite_OperationalError;
181 self->IntegrityError = pysqlite_IntegrityError;
182 self->InternalError = pysqlite_InternalError;
183 self->ProgrammingError = pysqlite_ProgrammingError;
184 self->NotSupportedError = pysqlite_NotSupportedError;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000185
186 return 0;
187}
188
Thomas Wouters477c8d52006-05-27 19:21:47 +0000189/* Empty the entire statement cache of this connection */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000190void pysqlite_flush_statement_cache(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000192 pysqlite_Node* node;
193 pysqlite_Statement* statement;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194
195 node = self->statement_cache->first;
196
197 while (node) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000198 statement = (pysqlite_Statement*)(node->data);
199 (void)pysqlite_statement_finalize(statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200 node = node->next;
201 }
202
203 Py_DECREF(self->statement_cache);
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000204 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000205 Py_DECREF(self);
206 self->statement_cache->decref_factory = 0;
207}
208
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000209/* action in (ACTION_RESET, ACTION_FINALIZE) */
Gerhard Häringf9cee222010-03-05 15:20:03 +0000210void pysqlite_do_all_statements(pysqlite_Connection* self, int action, int reset_cursors)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000212 int i;
213 PyObject* weakref;
214 PyObject* statement;
Gerhard Häringf9cee222010-03-05 15:20:03 +0000215 pysqlite_Cursor* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216
Thomas Wouters477c8d52006-05-27 19:21:47 +0000217 for (i = 0; i < PyList_Size(self->statements); i++) {
218 weakref = PyList_GetItem(self->statements, i);
219 statement = PyWeakref_GetObject(weakref);
220 if (statement != Py_None) {
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500221 Py_INCREF(statement);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000222 if (action == ACTION_RESET) {
223 (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
224 } else {
225 (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
226 }
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500227 Py_DECREF(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000228 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000229 }
Gerhard Häringf9cee222010-03-05 15:20:03 +0000230
231 if (reset_cursors) {
232 for (i = 0; i < PyList_Size(self->cursors); i++) {
233 weakref = PyList_GetItem(self->cursors, i);
234 cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
235 if ((PyObject*)cursor != Py_None) {
236 cursor->reset = 1;
237 }
238 }
239 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000240}
241
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000242void pysqlite_connection_dealloc(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000243{
244 Py_XDECREF(self->statement_cache);
245
246 /* Clean up if user has not called .close() explicitly. */
247 if (self->db) {
248 Py_BEGIN_ALLOW_THREADS
249 sqlite3_close(self->db);
250 Py_END_ALLOW_THREADS
251 }
252
253 if (self->begin_statement) {
254 PyMem_Free(self->begin_statement);
255 }
256 Py_XDECREF(self->isolation_level);
257 Py_XDECREF(self->function_pinboard);
258 Py_XDECREF(self->row_factory);
259 Py_XDECREF(self->text_factory);
260 Py_XDECREF(self->collations);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000261 Py_XDECREF(self->statements);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000262 Py_XDECREF(self->cursors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000263
Christian Heimes90aa7642007-12-19 02:45:37 +0000264 Py_TYPE(self)->tp_free((PyObject*)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000265}
266
Gerhard Häringf9cee222010-03-05 15:20:03 +0000267/*
268 * Registers a cursor with the connection.
269 *
270 * 0 => error; 1 => ok
271 */
272int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
273{
274 PyObject* weakref;
275
276 weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
277 if (!weakref) {
278 goto error;
279 }
280
281 if (PyList_Append(connection->cursors, weakref) != 0) {
282 Py_CLEAR(weakref);
283 goto error;
284 }
285
286 Py_DECREF(weakref);
287
288 return 1;
289error:
290 return 0;
291}
292
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000293PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000294{
295 static char *kwlist[] = {"factory", NULL, NULL};
296 PyObject* factory = NULL;
297 PyObject* cursor;
298
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000299 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
300 &factory)) {
301 return NULL;
302 }
303
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000304 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000305 return NULL;
306 }
307
308 if (factory == NULL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000309 factory = (PyObject*)&pysqlite_CursorType;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000310 }
311
312 cursor = PyObject_CallFunction(factory, "O", self);
313
Gerhard Häringf9cee222010-03-05 15:20:03 +0000314 _pysqlite_drop_unused_cursor_references(self);
315
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000316 if (cursor && self->row_factory != Py_None) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000317 Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000318 Py_INCREF(self->row_factory);
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000319 ((pysqlite_Cursor*)cursor)->row_factory = self->row_factory;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 }
321
322 return cursor;
323}
324
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000325PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000326{
327 int rc;
328
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000329 if (!pysqlite_check_thread(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000330 return NULL;
331 }
332
Gerhard Häringf9cee222010-03-05 15:20:03 +0000333 pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000334
335 if (self->db) {
336 Py_BEGIN_ALLOW_THREADS
337 rc = sqlite3_close(self->db);
338 Py_END_ALLOW_THREADS
339
340 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000341 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000342 return NULL;
343 } else {
344 self->db = NULL;
345 }
346 }
347
348 Py_INCREF(Py_None);
349 return Py_None;
350}
351
352/*
353 * Checks if a connection object is usable (i. e. not closed).
354 *
355 * 0 => error; 1 => ok
356 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000357int pysqlite_check_connection(pysqlite_Connection* con)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000358{
Gerhard Häringf9cee222010-03-05 15:20:03 +0000359 if (!con->initialized) {
360 PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
361 return 0;
362 }
363
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000364 if (!con->db) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000365 PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000366 return 0;
367 } else {
368 return 1;
369 }
370}
371
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000372PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000373{
374 int rc;
375 const char* tail;
376 sqlite3_stmt* statement;
377
378 Py_BEGIN_ALLOW_THREADS
379 rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
380 Py_END_ALLOW_THREADS
381
382 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000383 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000384 goto error;
385 }
386
Benjamin Petersond7b03282008-09-13 15:58:53 +0000387 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000388 if (rc == SQLITE_DONE) {
389 self->inTransaction = 1;
390 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000391 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000392 }
393
394 Py_BEGIN_ALLOW_THREADS
395 rc = sqlite3_finalize(statement);
396 Py_END_ALLOW_THREADS
397
398 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000399 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000400 }
401
402error:
403 if (PyErr_Occurred()) {
404 return NULL;
405 } else {
406 Py_INCREF(Py_None);
407 return Py_None;
408 }
409}
410
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000411PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000412{
413 int rc;
414 const char* tail;
415 sqlite3_stmt* statement;
416
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000417 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000418 return NULL;
419 }
420
421 if (self->inTransaction) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000422 pysqlite_do_all_statements(self, ACTION_RESET, 0);
423
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000424 Py_BEGIN_ALLOW_THREADS
425 rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
426 Py_END_ALLOW_THREADS
427 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000428 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000429 goto error;
430 }
431
Benjamin Petersond7b03282008-09-13 15:58:53 +0000432 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000433 if (rc == SQLITE_DONE) {
434 self->inTransaction = 0;
435 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000436 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000437 }
438
439 Py_BEGIN_ALLOW_THREADS
440 rc = sqlite3_finalize(statement);
441 Py_END_ALLOW_THREADS
442 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000443 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000444 }
445
446 }
447
448error:
449 if (PyErr_Occurred()) {
450 return NULL;
451 } else {
452 Py_INCREF(Py_None);
453 return Py_None;
454 }
455}
456
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000457PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000458{
459 int rc;
460 const char* tail;
461 sqlite3_stmt* statement;
462
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000463 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000464 return NULL;
465 }
466
467 if (self->inTransaction) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000468 pysqlite_do_all_statements(self, ACTION_RESET, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000469
470 Py_BEGIN_ALLOW_THREADS
Georg Brandl0eaa9402007-08-11 15:39:18 +0000471 rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000472 Py_END_ALLOW_THREADS
473 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000474 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000475 goto error;
476 }
477
Benjamin Petersond7b03282008-09-13 15:58:53 +0000478 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000479 if (rc == SQLITE_DONE) {
480 self->inTransaction = 0;
481 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000482 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000483 }
484
485 Py_BEGIN_ALLOW_THREADS
486 rc = sqlite3_finalize(statement);
487 Py_END_ALLOW_THREADS
488 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000489 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000490 }
491
492 }
493
494error:
495 if (PyErr_Occurred()) {
496 return NULL;
497 } else {
498 Py_INCREF(Py_None);
499 return Py_None;
500 }
501}
502
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200503static int
504_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000505{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200506 if (py_val == Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000507 sqlite3_result_null(context);
Christian Heimes217cfd12007-12-02 14:31:20 +0000508 } else if (PyLong_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200509 sqlite_int64 value = _pysqlite_long_as_int64(py_val);
510 if (value == -1 && PyErr_Occurred())
511 return -1;
512 sqlite3_result_int64(context, value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000513 } else if (PyFloat_Check(py_val)) {
514 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
Guido van Rossumbae07c92007-10-08 02:46:15 +0000515 } else if (PyUnicode_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200516 const char *str = _PyUnicode_AsString(py_val);
517 if (str == NULL)
518 return -1;
519 sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000520 } else if (PyObject_CheckBuffer(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200521 const char* buffer;
522 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000523 if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) {
524 PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200525 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000526 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200527 sqlite3_result_blob(context, buffer, buflen, SQLITE_TRANSIENT);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000528 } else {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200529 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000530 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200531 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000532}
533
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000534PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000535{
536 PyObject* args;
537 int i;
538 sqlite3_value* cur_value;
539 PyObject* cur_py_value;
540 const char* val_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000541 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000542
543 args = PyTuple_New(argc);
544 if (!args) {
545 return NULL;
546 }
547
548 for (i = 0; i < argc; i++) {
549 cur_value = argv[i];
550 switch (sqlite3_value_type(argv[i])) {
551 case SQLITE_INTEGER:
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200552 cur_py_value = _pysqlite_long_from_int64(sqlite3_value_int64(cur_value));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000553 break;
554 case SQLITE_FLOAT:
555 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
556 break;
557 case SQLITE_TEXT:
558 val_str = (const char*)sqlite3_value_text(cur_value);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000559 cur_py_value = PyUnicode_FromString(val_str);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000560 /* TODO: have a way to show errors here */
561 if (!cur_py_value) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000562 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000563 Py_INCREF(Py_None);
564 cur_py_value = Py_None;
565 }
566 break;
567 case SQLITE_BLOB:
568 buflen = sqlite3_value_bytes(cur_value);
Christian Heimes72b710a2008-05-26 13:28:38 +0000569 cur_py_value = PyBytes_FromStringAndSize(
Guido van Rossumbae07c92007-10-08 02:46:15 +0000570 sqlite3_value_blob(cur_value), buflen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000571 break;
572 case SQLITE_NULL:
573 default:
574 Py_INCREF(Py_None);
575 cur_py_value = Py_None;
576 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000577
578 if (!cur_py_value) {
579 Py_DECREF(args);
580 return NULL;
581 }
582
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000583 PyTuple_SetItem(args, i, cur_py_value);
584
585 }
586
587 return args;
588}
589
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000590void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000591{
592 PyObject* args;
593 PyObject* py_func;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000594 PyObject* py_retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200595 int ok;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000596
Georg Brandldfd73442009-04-05 11:47:34 +0000597#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000598 PyGILState_STATE threadstate;
599
600 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000601#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000602
603 py_func = (PyObject*)sqlite3_user_data(context);
604
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000605 args = _pysqlite_build_py_params(context, argc, argv);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000606 if (args) {
607 py_retval = PyObject_CallObject(py_func, args);
608 Py_DECREF(args);
609 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000610
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200611 ok = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612 if (py_retval) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200613 ok = _pysqlite_set_result(context, py_retval) == 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000614 Py_DECREF(py_retval);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200615 }
616 if (!ok) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617 if (_enable_callback_tracebacks) {
618 PyErr_Print();
619 } else {
620 PyErr_Clear();
621 }
622 _sqlite3_result_error(context, "user-defined function raised exception", -1);
623 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000624
Georg Brandldfd73442009-04-05 11:47:34 +0000625#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000626 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000627#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000628}
629
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000630static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000631{
632 PyObject* args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000633 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000634 PyObject* aggregate_class;
635 PyObject** aggregate_instance;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000636 PyObject* stepmethod = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000637
Georg Brandldfd73442009-04-05 11:47:34 +0000638#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000639 PyGILState_STATE threadstate;
640
641 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000642#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000643
644 aggregate_class = (PyObject*)sqlite3_user_data(context);
645
646 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
647
648 if (*aggregate_instance == 0) {
649 *aggregate_instance = PyObject_CallFunction(aggregate_class, "");
650
Thomas Wouters477c8d52006-05-27 19:21:47 +0000651 if (PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000652 *aggregate_instance = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653 if (_enable_callback_tracebacks) {
654 PyErr_Print();
655 } else {
656 PyErr_Clear();
657 }
658 _sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000659 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000660 }
661 }
662
663 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000664 if (!stepmethod) {
665 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000666 }
667
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000668 args = _pysqlite_build_py_params(context, argc, params);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000669 if (!args) {
670 goto error;
671 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000672
673 function_result = PyObject_CallObject(stepmethod, args);
674 Py_DECREF(args);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000675
Thomas Wouters477c8d52006-05-27 19:21:47 +0000676 if (!function_result) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000677 if (_enable_callback_tracebacks) {
678 PyErr_Print();
679 } else {
680 PyErr_Clear();
681 }
682 _sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000683 }
684
Thomas Wouters477c8d52006-05-27 19:21:47 +0000685error:
686 Py_XDECREF(stepmethod);
687 Py_XDECREF(function_result);
688
Georg Brandldfd73442009-04-05 11:47:34 +0000689#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000690 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000691#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000692}
693
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000694void _pysqlite_final_callback(sqlite3_context* context)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000695{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200696 PyObject* function_result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000697 PyObject** aggregate_instance;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200698 _Py_IDENTIFIER(finalize);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200699 int ok;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200700 PyObject *exception, *value, *tb;
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);
718
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200719 function_result = _PyObject_CallMethodId(*aggregate_instance, &PyId_finalize, "");
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200720
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200721 Py_DECREF(*aggregate_instance);
722
723 ok = 0;
724 if (function_result) {
725 ok = _pysqlite_set_result(context, function_result) == 0;
726 Py_DECREF(function_result);
727 }
728 if (!ok) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000729 if (_enable_callback_tracebacks) {
730 PyErr_Print();
731 } else {
732 PyErr_Clear();
733 }
734 _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000735 }
736
Victor Stinner3a857322013-07-22 08:34:32 +0200737 /* Restore the exception (if any) of the last call to step(),
738 but clear also the current exception if finalize() failed */
739 PyErr_Restore(exception, value, tb);
740
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741error:
Georg Brandldfd73442009-04-05 11:47:34 +0000742#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000743 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000744#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000745}
746
Gerhard Häringf9cee222010-03-05 15:20:03 +0000747static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000748{
749 PyObject* new_list;
750 PyObject* weakref;
751 int i;
752
753 /* we only need to do this once in a while */
754 if (self->created_statements++ < 200) {
755 return;
756 }
757
758 self->created_statements = 0;
759
760 new_list = PyList_New(0);
761 if (!new_list) {
762 return;
763 }
764
765 for (i = 0; i < PyList_Size(self->statements); i++) {
766 weakref = PyList_GetItem(self->statements, i);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000767 if (PyWeakref_GetObject(weakref) != Py_None) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000768 if (PyList_Append(new_list, weakref) != 0) {
769 Py_DECREF(new_list);
770 return;
771 }
772 }
773 }
774
775 Py_DECREF(self->statements);
776 self->statements = new_list;
777}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000778
Gerhard Häringf9cee222010-03-05 15:20:03 +0000779static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
780{
781 PyObject* new_list;
782 PyObject* weakref;
783 int i;
784
785 /* we only need to do this once in a while */
786 if (self->created_cursors++ < 200) {
787 return;
788 }
789
790 self->created_cursors = 0;
791
792 new_list = PyList_New(0);
793 if (!new_list) {
794 return;
795 }
796
797 for (i = 0; i < PyList_Size(self->cursors); i++) {
798 weakref = PyList_GetItem(self->cursors, i);
799 if (PyWeakref_GetObject(weakref) != Py_None) {
800 if (PyList_Append(new_list, weakref) != 0) {
801 Py_DECREF(new_list);
802 return;
803 }
804 }
805 }
806
807 Py_DECREF(self->cursors);
808 self->cursors = new_list;
809}
810
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000811PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000812{
813 static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
814
815 PyObject* func;
816 char* name;
817 int narg;
818 int rc;
819
Gerhard Häringf9cee222010-03-05 15:20:03 +0000820 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
821 return NULL;
822 }
823
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000824 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
825 &name, &narg, &func))
826 {
827 return NULL;
828 }
829
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000830 rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831
Thomas Wouters477c8d52006-05-27 19:21:47 +0000832 if (rc != SQLITE_OK) {
833 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000834 PyErr_SetString(pysqlite_OperationalError, "Error creating function");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000835 return NULL;
836 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000837 if (PyDict_SetItem(self->function_pinboard, func, Py_None) == -1)
838 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000839
Thomas Wouters477c8d52006-05-27 19:21:47 +0000840 Py_INCREF(Py_None);
841 return Py_None;
842 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000843}
844
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000845PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000846{
847 PyObject* aggregate_class;
848
849 int n_arg;
850 char* name;
851 static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
852 int rc;
853
Gerhard Häringf9cee222010-03-05 15:20:03 +0000854 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
855 return NULL;
856 }
857
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000858 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
859 kwlist, &name, &n_arg, &aggregate_class)) {
860 return NULL;
861 }
862
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000863 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 +0000864 if (rc != SQLITE_OK) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000865 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000866 PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000867 return NULL;
868 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000869 if (PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None) == -1)
870 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000871
872 Py_INCREF(Py_None);
873 return Py_None;
874 }
875}
876
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000877static 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 +0000878{
879 PyObject *ret;
880 int rc;
Georg Brandldfd73442009-04-05 11:47:34 +0000881#ifdef WITH_THREAD
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000882 PyGILState_STATE gilstate;
883
884 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000885#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000886
Victor Stinnerd4095d92013-07-26 22:23:33 +0200887 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000888
Victor Stinnerd4095d92013-07-26 22:23:33 +0200889 if (ret == NULL) {
890 if (_enable_callback_tracebacks)
891 PyErr_Print();
892 else
893 PyErr_Clear();
Victor Stinner41801f52013-07-21 13:05:38 +0200894
Victor Stinnerd4095d92013-07-26 22:23:33 +0200895 rc = SQLITE_DENY;
Victor Stinner41801f52013-07-21 13:05:38 +0200896 }
897 else {
Victor Stinnerd4095d92013-07-26 22:23:33 +0200898 if (PyLong_Check(ret)) {
899 rc = _PyLong_AsInt(ret);
900 if (rc == -1 && PyErr_Occurred()) {
901 if (_enable_callback_tracebacks)
902 PyErr_Print();
903 else
904 PyErr_Clear();
905 rc = SQLITE_DENY;
906 }
907 }
908 else {
909 rc = SQLITE_DENY;
910 }
911 Py_DECREF(ret);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000912 }
913
Georg Brandldfd73442009-04-05 11:47:34 +0000914#ifdef WITH_THREAD
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000915 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000916#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000917 return rc;
918}
919
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000920static int _progress_handler(void* user_arg)
921{
922 int rc;
923 PyObject *ret;
Georg Brandldfd73442009-04-05 11:47:34 +0000924#ifdef WITH_THREAD
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000925 PyGILState_STATE gilstate;
926
927 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000928#endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000929 ret = PyObject_CallFunction((PyObject*)user_arg, "");
930
931 if (!ret) {
932 if (_enable_callback_tracebacks) {
933 PyErr_Print();
934 } else {
935 PyErr_Clear();
936 }
937
Mark Dickinson934896d2009-02-21 20:59:32 +0000938 /* abort query if error occurred */
Victor Stinner86999502010-05-19 01:27:23 +0000939 rc = 1;
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000940 } else {
941 rc = (int)PyObject_IsTrue(ret);
942 Py_DECREF(ret);
943 }
944
Georg Brandldfd73442009-04-05 11:47:34 +0000945#ifdef WITH_THREAD
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000946 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000947#endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000948 return rc;
949}
950
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200951static void _trace_callback(void* user_arg, const char* statement_string)
952{
953 PyObject *py_statement = NULL;
954 PyObject *ret = NULL;
955
956#ifdef WITH_THREAD
957 PyGILState_STATE gilstate;
958
959 gilstate = PyGILState_Ensure();
960#endif
961 py_statement = PyUnicode_DecodeUTF8(statement_string,
962 strlen(statement_string), "replace");
963 if (py_statement) {
964 ret = PyObject_CallFunctionObjArgs((PyObject*)user_arg, py_statement, NULL);
965 Py_DECREF(py_statement);
966 }
967
968 if (ret) {
969 Py_DECREF(ret);
970 } else {
971 if (_enable_callback_tracebacks) {
972 PyErr_Print();
973 } else {
974 PyErr_Clear();
975 }
976 }
977
978#ifdef WITH_THREAD
979 PyGILState_Release(gilstate);
980#endif
981}
982
Gerhard Häringf9cee222010-03-05 15:20:03 +0000983static PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000984{
985 PyObject* authorizer_cb;
986
987 static char *kwlist[] = { "authorizer_callback", NULL };
988 int rc;
989
Gerhard Häringf9cee222010-03-05 15:20:03 +0000990 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
991 return NULL;
992 }
993
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000994 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
995 kwlist, &authorizer_cb)) {
996 return NULL;
997 }
998
999 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
1000
1001 if (rc != SQLITE_OK) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001002 PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001003 return NULL;
1004 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001005 if (PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None) == -1)
1006 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001007
1008 Py_INCREF(Py_None);
1009 return Py_None;
1010 }
1011}
1012
Gerhard Häringf9cee222010-03-05 15:20:03 +00001013static PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001014{
1015 PyObject* progress_handler;
1016 int n;
1017
1018 static char *kwlist[] = { "progress_handler", "n", NULL };
1019
Gerhard Häringf9cee222010-03-05 15:20:03 +00001020 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1021 return NULL;
1022 }
1023
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001024 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
1025 kwlist, &progress_handler, &n)) {
1026 return NULL;
1027 }
1028
1029 if (progress_handler == Py_None) {
1030 /* None clears the progress handler previously set */
1031 sqlite3_progress_handler(self->db, 0, 0, (void*)0);
1032 } else {
1033 sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
Gerhard Häringf9cee222010-03-05 15:20:03 +00001034 if (PyDict_SetItem(self->function_pinboard, progress_handler, Py_None) == -1)
1035 return NULL;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001036 }
1037
1038 Py_INCREF(Py_None);
1039 return Py_None;
1040}
1041
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001042static PyObject* pysqlite_connection_set_trace_callback(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1043{
1044 PyObject* trace_callback;
1045
1046 static char *kwlist[] = { "trace_callback", NULL };
1047
1048 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1049 return NULL;
1050 }
1051
1052 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_trace_callback",
1053 kwlist, &trace_callback)) {
1054 return NULL;
1055 }
1056
1057 if (trace_callback == Py_None) {
1058 /* None clears the trace callback previously set */
1059 sqlite3_trace(self->db, 0, (void*)0);
1060 } else {
1061 if (PyDict_SetItem(self->function_pinboard, trace_callback, Py_None) == -1)
1062 return NULL;
1063 sqlite3_trace(self->db, _trace_callback, trace_callback);
1064 }
1065
1066 Py_INCREF(Py_None);
1067 return Py_None;
1068}
1069
Gerhard Häringf9cee222010-03-05 15:20:03 +00001070#ifdef HAVE_LOAD_EXTENSION
1071static PyObject* pysqlite_enable_load_extension(pysqlite_Connection* self, PyObject* args)
1072{
1073 int rc;
1074 int onoff;
1075
1076 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1077 return NULL;
1078 }
1079
1080 if (!PyArg_ParseTuple(args, "i", &onoff)) {
1081 return NULL;
1082 }
1083
1084 rc = sqlite3_enable_load_extension(self->db, onoff);
1085
1086 if (rc != SQLITE_OK) {
1087 PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
1088 return NULL;
1089 } else {
1090 Py_INCREF(Py_None);
1091 return Py_None;
1092 }
1093}
1094
1095static PyObject* pysqlite_load_extension(pysqlite_Connection* self, PyObject* args)
1096{
1097 int rc;
1098 char* extension_name;
1099 char* errmsg;
1100
1101 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1102 return NULL;
1103 }
1104
1105 if (!PyArg_ParseTuple(args, "s", &extension_name)) {
1106 return NULL;
1107 }
1108
1109 rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1110 if (rc != 0) {
1111 PyErr_SetString(pysqlite_OperationalError, errmsg);
1112 return NULL;
1113 } else {
1114 Py_INCREF(Py_None);
1115 return Py_None;
1116 }
1117}
1118#endif
1119
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001120int pysqlite_check_thread(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001121{
Georg Brandldfd73442009-04-05 11:47:34 +00001122#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001123 if (self->check_same_thread) {
1124 if (PyThread_get_thread_ident() != self->thread_ident) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001125 PyErr_Format(pysqlite_ProgrammingError,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001126 "SQLite objects created in a thread can only be used in that same thread."
1127 "The object was created in thread id %ld and this is thread id %ld",
1128 self->thread_ident, PyThread_get_thread_ident());
1129 return 0;
1130 }
1131
1132 }
Georg Brandldfd73442009-04-05 11:47:34 +00001133#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001134 return 1;
1135}
1136
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001137static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001138{
1139 Py_INCREF(self->isolation_level);
1140 return self->isolation_level;
1141}
1142
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001143static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001144{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001145 if (!pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001146 return NULL;
1147 } else {
1148 return Py_BuildValue("i", sqlite3_total_changes(self->db));
1149 }
1150}
1151
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001152static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001153{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001154 PyObject* res;
1155 PyObject* begin_statement;
Georg Brandlceab6102007-11-25 00:45:05 +00001156 static PyObject* begin_word;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001157
1158 Py_XDECREF(self->isolation_level);
1159
1160 if (self->begin_statement) {
1161 PyMem_Free(self->begin_statement);
1162 self->begin_statement = NULL;
1163 }
1164
1165 if (isolation_level == Py_None) {
1166 Py_INCREF(Py_None);
1167 self->isolation_level = Py_None;
1168
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001169 res = pysqlite_connection_commit(self, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001170 if (!res) {
1171 return -1;
1172 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001173 Py_DECREF(res);
1174
1175 self->inTransaction = 0;
1176 } else {
Neal Norwitzefee9f52007-10-27 02:50:52 +00001177 const char *statement;
1178 Py_ssize_t size;
1179
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001180 Py_INCREF(isolation_level);
1181 self->isolation_level = isolation_level;
1182
Georg Brandlceab6102007-11-25 00:45:05 +00001183 if (!begin_word) {
1184 begin_word = PyUnicode_FromString("BEGIN ");
1185 if (!begin_word) return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001186 }
Georg Brandlceab6102007-11-25 00:45:05 +00001187 begin_statement = PyUnicode_Concat(begin_word, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001188 if (!begin_statement) {
1189 return -1;
1190 }
1191
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001192 statement = _PyUnicode_AsStringAndSize(begin_statement, &size);
Georg Brandl3dbca812008-07-23 16:10:53 +00001193 if (!statement) {
Victor Stinnerff27d6b2010-03-13 00:57:22 +00001194 Py_DECREF(begin_statement);
Georg Brandl3dbca812008-07-23 16:10:53 +00001195 return -1;
1196 }
Neal Norwitzefee9f52007-10-27 02:50:52 +00001197 self->begin_statement = PyMem_Malloc(size + 2);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001198 if (!self->begin_statement) {
Georg Brandl3dbca812008-07-23 16:10:53 +00001199 Py_DECREF(begin_statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001200 return -1;
1201 }
1202
Neal Norwitzefee9f52007-10-27 02:50:52 +00001203 strcpy(self->begin_statement, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001204 Py_DECREF(begin_statement);
1205 }
1206
1207 return 0;
1208}
1209
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001210PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001211{
1212 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001213 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001214 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001215 int rc;
1216
Gerhard Häringf9cee222010-03-05 15:20:03 +00001217 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1218 return NULL;
1219 }
1220
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001221 if (!PyArg_ParseTuple(args, "O", &sql)) {
1222 return NULL;
1223 }
1224
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001225 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001226
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001227 statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001228 if (!statement) {
1229 return NULL;
1230 }
1231
Victor Stinner0201f442010-03-13 03:28:34 +00001232 statement->db = NULL;
1233 statement->st = NULL;
1234 statement->sql = NULL;
1235 statement->in_use = 0;
1236 statement->in_weakreflist = NULL;
1237
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001238 rc = pysqlite_statement_create(statement, self, sql);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001239
1240 if (rc != SQLITE_OK) {
1241 if (rc == PYSQLITE_TOO_MUCH_SQL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001242 PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001243 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001244 PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string or unicode.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001245 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001246 (void)pysqlite_statement_reset(statement);
1247 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001248 }
1249
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001250 Py_CLEAR(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001251 } else {
1252 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
1253 if (!weakref) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001254 Py_CLEAR(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001255 goto error;
1256 }
1257
1258 if (PyList_Append(self->statements, weakref) != 0) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001259 Py_CLEAR(weakref);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001260 goto error;
1261 }
1262
1263 Py_DECREF(weakref);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001264 }
1265
Thomas Wouters477c8d52006-05-27 19:21:47 +00001266error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001267 return (PyObject*)statement;
1268}
1269
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001270PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001271{
1272 PyObject* cursor = 0;
1273 PyObject* result = 0;
1274 PyObject* method = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001275 _Py_IDENTIFIER(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001276
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001277 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001278 if (!cursor) {
1279 goto error;
1280 }
1281
1282 method = PyObject_GetAttrString(cursor, "execute");
1283 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001284 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001285 goto error;
1286 }
1287
1288 result = PyObject_CallObject(method, args);
1289 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001290 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001291 }
1292
1293error:
1294 Py_XDECREF(result);
1295 Py_XDECREF(method);
1296
1297 return cursor;
1298}
1299
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001300PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001301{
1302 PyObject* cursor = 0;
1303 PyObject* result = 0;
1304 PyObject* method = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001305 _Py_IDENTIFIER(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001306
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001307 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001308 if (!cursor) {
1309 goto error;
1310 }
1311
1312 method = PyObject_GetAttrString(cursor, "executemany");
1313 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001314 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001315 goto error;
1316 }
1317
1318 result = PyObject_CallObject(method, args);
1319 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001320 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001321 }
1322
1323error:
1324 Py_XDECREF(result);
1325 Py_XDECREF(method);
1326
1327 return cursor;
1328}
1329
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001330PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001331{
1332 PyObject* cursor = 0;
1333 PyObject* result = 0;
1334 PyObject* method = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001335 _Py_IDENTIFIER(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001336
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001337 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001338 if (!cursor) {
1339 goto error;
1340 }
1341
1342 method = PyObject_GetAttrString(cursor, "executescript");
1343 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001344 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001345 goto error;
1346 }
1347
1348 result = PyObject_CallObject(method, args);
1349 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001350 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001351 }
1352
1353error:
1354 Py_XDECREF(result);
1355 Py_XDECREF(method);
1356
1357 return cursor;
1358}
1359
1360/* ------------------------- COLLATION CODE ------------------------ */
1361
1362static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001363pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001364 void* context,
1365 int text1_length, const void* text1_data,
1366 int text2_length, const void* text2_data)
1367{
1368 PyObject* callback = (PyObject*)context;
1369 PyObject* string1 = 0;
1370 PyObject* string2 = 0;
Georg Brandldfd73442009-04-05 11:47:34 +00001371#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001372 PyGILState_STATE gilstate;
Georg Brandldfd73442009-04-05 11:47:34 +00001373#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001374 PyObject* retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001375 long longval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001376 int result = 0;
Georg Brandldfd73442009-04-05 11:47:34 +00001377#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001378 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +00001379#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001380
1381 if (PyErr_Occurred()) {
1382 goto finally;
1383 }
1384
Guido van Rossum98297ee2007-11-06 21:34:58 +00001385 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1386 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001387
1388 if (!string1 || !string2) {
1389 goto finally; /* failed to allocate strings */
1390 }
1391
1392 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1393
1394 if (!retval) {
1395 /* execution failed */
1396 goto finally;
1397 }
1398
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001399 longval = PyLong_AsLongAndOverflow(retval, &result);
1400 if (longval == -1 && PyErr_Occurred()) {
1401 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001402 result = 0;
1403 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001404 else if (!result) {
1405 if (longval > 0)
1406 result = 1;
1407 else if (longval < 0)
1408 result = -1;
1409 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001410
1411finally:
1412 Py_XDECREF(string1);
1413 Py_XDECREF(string2);
1414 Py_XDECREF(retval);
Georg Brandldfd73442009-04-05 11:47:34 +00001415#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001416 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +00001417#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001418 return result;
1419}
1420
1421static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001422pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001423{
1424 PyObject* retval = NULL;
1425
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001426 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001427 goto finally;
1428 }
1429
1430 sqlite3_interrupt(self->db);
1431
1432 Py_INCREF(Py_None);
1433 retval = Py_None;
1434
1435finally:
1436 return retval;
1437}
1438
Christian Heimesbbe741d2008-03-28 10:53:29 +00001439/* Function author: Paul Kippes <kippesp@gmail.com>
1440 * Class method of Connection to call the Python function _iterdump
1441 * of the sqlite3 module.
1442 */
1443static PyObject *
1444pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1445{
1446 PyObject* retval = NULL;
1447 PyObject* module = NULL;
1448 PyObject* module_dict;
1449 PyObject* pyfn_iterdump;
1450
1451 if (!pysqlite_check_connection(self)) {
1452 goto finally;
1453 }
1454
1455 module = PyImport_ImportModule(MODULE_NAME ".dump");
1456 if (!module) {
1457 goto finally;
1458 }
1459
1460 module_dict = PyModule_GetDict(module);
1461 if (!module_dict) {
1462 goto finally;
1463 }
1464
1465 pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
1466 if (!pyfn_iterdump) {
1467 PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
1468 goto finally;
1469 }
1470
1471 args = PyTuple_New(1);
1472 if (!args) {
1473 goto finally;
1474 }
1475 Py_INCREF(self);
1476 PyTuple_SetItem(args, 0, (PyObject*)self);
1477 retval = PyObject_CallObject(pyfn_iterdump, args);
1478
1479finally:
1480 Py_XDECREF(args);
1481 Py_XDECREF(module);
1482 return retval;
1483}
1484
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001485static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001486pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001487{
1488 PyObject* callable;
1489 PyObject* uppercase_name = 0;
1490 PyObject* name;
1491 PyObject* retval;
Victor Stinner35466c52010-04-22 11:23:23 +00001492 Py_ssize_t i, len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001493 _Py_IDENTIFIER(upper);
Victor Stinner35466c52010-04-22 11:23:23 +00001494 char *uppercase_name_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001495 int rc;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001496 unsigned int kind;
1497 void *data;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001498
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001499 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001500 goto finally;
1501 }
1502
Gerhard Häring6d214562007-08-10 18:15:11 +00001503 if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyUnicode_Type, &name, &callable)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001504 goto finally;
1505 }
1506
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001507 uppercase_name = _PyObject_CallMethodId(name, &PyId_upper, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001508 if (!uppercase_name) {
1509 goto finally;
1510 }
1511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 if (PyUnicode_READY(uppercase_name))
1513 goto finally;
1514 len = PyUnicode_GET_LENGTH(uppercase_name);
1515 kind = PyUnicode_KIND(uppercase_name);
1516 data = PyUnicode_DATA(uppercase_name);
1517 for (i=0; i<len; i++) {
1518 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1519 if ((ch >= '0' && ch <= '9')
1520 || (ch >= 'A' && ch <= 'Z')
1521 || (ch == '_'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001522 {
Victor Stinner35466c52010-04-22 11:23:23 +00001523 continue;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001524 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001525 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001526 goto finally;
1527 }
1528 }
1529
Victor Stinner35466c52010-04-22 11:23:23 +00001530 uppercase_name_str = _PyUnicode_AsString(uppercase_name);
1531 if (!uppercase_name_str)
1532 goto finally;
1533
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001534 if (callable != Py_None && !PyCallable_Check(callable)) {
1535 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1536 goto finally;
1537 }
1538
1539 if (callable != Py_None) {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001540 if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
1541 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001542 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001543 if (PyDict_DelItem(self->collations, uppercase_name) == -1)
1544 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001545 }
1546
1547 rc = sqlite3_create_collation(self->db,
Victor Stinner35466c52010-04-22 11:23:23 +00001548 uppercase_name_str,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001549 SQLITE_UTF8,
1550 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001551 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001552 if (rc != SQLITE_OK) {
1553 PyDict_DelItem(self->collations, uppercase_name);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001554 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001555 goto finally;
1556 }
1557
1558finally:
1559 Py_XDECREF(uppercase_name);
1560
1561 if (PyErr_Occurred()) {
1562 retval = NULL;
1563 } else {
1564 Py_INCREF(Py_None);
1565 retval = Py_None;
1566 }
1567
1568 return retval;
1569}
1570
Christian Heimesbbe741d2008-03-28 10:53:29 +00001571/* Called when the connection is used as a context manager. Returns itself as a
1572 * convenience to the caller. */
1573static PyObject *
1574pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1575{
1576 Py_INCREF(self);
1577 return (PyObject*)self;
1578}
1579
1580/** Called when the connection is used as a context manager. If there was any
1581 * exception, a rollback takes place; otherwise we commit. */
1582static PyObject *
1583pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1584{
1585 PyObject* exc_type, *exc_value, *exc_tb;
1586 char* method_name;
1587 PyObject* result;
1588
1589 if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1590 return NULL;
1591 }
1592
1593 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1594 method_name = "commit";
1595 } else {
1596 method_name = "rollback";
1597 }
1598
1599 result = PyObject_CallMethod((PyObject*)self, method_name, "");
1600 if (!result) {
1601 return NULL;
1602 }
1603 Py_DECREF(result);
1604
1605 Py_RETURN_FALSE;
1606}
1607
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001608static char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001609PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001610
1611static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001612 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1613 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001614 {NULL}
1615};
1616
1617static PyMethodDef connection_methods[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001618 {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001619 PyDoc_STR("Return a cursor for the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001620 {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001621 PyDoc_STR("Closes the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001622 {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001623 PyDoc_STR("Commit the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001624 {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001625 PyDoc_STR("Roll back the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001626 {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001627 PyDoc_STR("Creates a new function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001628 {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001629 PyDoc_STR("Creates a new aggregate. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001630 {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001631 PyDoc_STR("Sets authorizer callback. Non-standard.")},
Gerhard Häringf9cee222010-03-05 15:20:03 +00001632 #ifdef HAVE_LOAD_EXTENSION
1633 {"enable_load_extension", (PyCFunction)pysqlite_enable_load_extension, METH_VARARGS,
1634 PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
1635 {"load_extension", (PyCFunction)pysqlite_load_extension, METH_VARARGS,
1636 PyDoc_STR("Load SQLite extension module. Non-standard.")},
1637 #endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001638 {"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
1639 PyDoc_STR("Sets progress handler callback. Non-standard.")},
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001640 {"set_trace_callback", (PyCFunction)pysqlite_connection_set_trace_callback, METH_VARARGS|METH_KEYWORDS,
1641 PyDoc_STR("Sets a trace callback called for each SQL statement (passed as unicode). Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001642 {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001643 PyDoc_STR("Executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001644 {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001645 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001646 {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001647 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001648 {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001649 PyDoc_STR("Creates a collation function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001650 {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001651 PyDoc_STR("Abort any pending database operation. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001652 {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
Benjamin Petersond7b03282008-09-13 15:58:53 +00001653 PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001654 {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1655 PyDoc_STR("For context manager. Non-standard.")},
1656 {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1657 PyDoc_STR("For context manager. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001658 {NULL, NULL}
1659};
1660
1661static struct PyMemberDef connection_members[] =
1662{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001663 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1664 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1665 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1666 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1667 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1668 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1669 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1670 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1671 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1672 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001673 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1674 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
R. David Murrayd35251d2010-06-01 01:32:12 +00001675 {"in_transaction", T_BOOL, offsetof(pysqlite_Connection, inTransaction), READONLY},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001676 {NULL}
1677};
1678
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001679PyTypeObject pysqlite_ConnectionType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001680 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001681 MODULE_NAME ".Connection", /* tp_name */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001682 sizeof(pysqlite_Connection), /* tp_basicsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001683 0, /* tp_itemsize */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001684 (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001685 0, /* tp_print */
1686 0, /* tp_getattr */
1687 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001688 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001689 0, /* tp_repr */
1690 0, /* tp_as_number */
1691 0, /* tp_as_sequence */
1692 0, /* tp_as_mapping */
1693 0, /* tp_hash */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001694 (ternaryfunc)pysqlite_connection_call, /* tp_call */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001695 0, /* tp_str */
1696 0, /* tp_getattro */
1697 0, /* tp_setattro */
1698 0, /* tp_as_buffer */
1699 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1700 connection_doc, /* tp_doc */
1701 0, /* tp_traverse */
1702 0, /* tp_clear */
1703 0, /* tp_richcompare */
1704 0, /* tp_weaklistoffset */
1705 0, /* tp_iter */
1706 0, /* tp_iternext */
1707 connection_methods, /* tp_methods */
1708 connection_members, /* tp_members */
1709 connection_getset, /* tp_getset */
1710 0, /* tp_base */
1711 0, /* tp_dict */
1712 0, /* tp_descr_get */
1713 0, /* tp_descr_set */
1714 0, /* tp_dictoffset */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001715 (initproc)pysqlite_connection_init, /* tp_init */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001716 0, /* tp_alloc */
1717 0, /* tp_new */
1718 0 /* tp_free */
1719};
1720
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001721extern int pysqlite_connection_setup_types(void)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001722{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001723 pysqlite_ConnectionType.tp_new = PyType_GenericNew;
1724 return PyType_Ready(&pysqlite_ConnectionType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001725}