blob: 535464dbf1703d5b592b92b1637c6e883dc36815 [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;
Victor Stinnercb1f74e2013-12-19 16:38:03 +0100131 if (pysqlite_connection_set_isolation_level(self, isolation_level) < 0) {
132 Py_DECREF(isolation_level);
133 return -1;
134 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000135 Py_DECREF(isolation_level);
136
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000137 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000138 if (PyErr_Occurred()) {
139 return -1;
140 }
141
Gerhard Häringf9cee222010-03-05 15:20:03 +0000142 self->created_statements = 0;
143 self->created_cursors = 0;
144
145 /* Create lists of weak references to statements/cursors */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000146 self->statements = PyList_New(0);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000147 self->cursors = PyList_New(0);
148 if (!self->statements || !self->cursors) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000149 return -1;
150 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000151
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000152 /* By default, the Cache class INCREFs the factory in its initializer, and
153 * decrefs it in its deallocator method. Since this would create a circular
154 * reference here, we're breaking it by decrementing self, and telling the
155 * cache class to not decref the factory (self) in its deallocator.
156 */
157 self->statement_cache->decref_factory = 0;
158 Py_DECREF(self);
159
160 self->inTransaction = 0;
161 self->detect_types = detect_types;
162 self->timeout = timeout;
163 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
Georg Brandldfd73442009-04-05 11:47:34 +0000164#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000165 self->thread_ident = PyThread_get_thread_ident();
Georg Brandldfd73442009-04-05 11:47:34 +0000166#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000167 self->check_same_thread = check_same_thread;
168
169 self->function_pinboard = PyDict_New();
170 if (!self->function_pinboard) {
171 return -1;
172 }
173
174 self->collations = PyDict_New();
175 if (!self->collations) {
176 return -1;
177 }
178
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000179 self->Warning = pysqlite_Warning;
180 self->Error = pysqlite_Error;
181 self->InterfaceError = pysqlite_InterfaceError;
182 self->DatabaseError = pysqlite_DatabaseError;
183 self->DataError = pysqlite_DataError;
184 self->OperationalError = pysqlite_OperationalError;
185 self->IntegrityError = pysqlite_IntegrityError;
186 self->InternalError = pysqlite_InternalError;
187 self->ProgrammingError = pysqlite_ProgrammingError;
188 self->NotSupportedError = pysqlite_NotSupportedError;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000189
190 return 0;
191}
192
Thomas Wouters477c8d52006-05-27 19:21:47 +0000193/* Empty the entire statement cache of this connection */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000194void pysqlite_flush_statement_cache(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000195{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000196 pysqlite_Node* node;
197 pysqlite_Statement* statement;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000198
199 node = self->statement_cache->first;
200
201 while (node) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000202 statement = (pysqlite_Statement*)(node->data);
203 (void)pysqlite_statement_finalize(statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000204 node = node->next;
205 }
206
207 Py_DECREF(self->statement_cache);
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000208 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000209 Py_DECREF(self);
210 self->statement_cache->decref_factory = 0;
211}
212
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000213/* action in (ACTION_RESET, ACTION_FINALIZE) */
Gerhard Häringf9cee222010-03-05 15:20:03 +0000214void pysqlite_do_all_statements(pysqlite_Connection* self, int action, int reset_cursors)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000215{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000216 int i;
217 PyObject* weakref;
218 PyObject* statement;
Gerhard Häringf9cee222010-03-05 15:20:03 +0000219 pysqlite_Cursor* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220
Thomas Wouters477c8d52006-05-27 19:21:47 +0000221 for (i = 0; i < PyList_Size(self->statements); i++) {
222 weakref = PyList_GetItem(self->statements, i);
223 statement = PyWeakref_GetObject(weakref);
224 if (statement != Py_None) {
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500225 Py_INCREF(statement);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000226 if (action == ACTION_RESET) {
227 (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
228 } else {
229 (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
230 }
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500231 Py_DECREF(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000232 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000233 }
Gerhard Häringf9cee222010-03-05 15:20:03 +0000234
235 if (reset_cursors) {
236 for (i = 0; i < PyList_Size(self->cursors); i++) {
237 weakref = PyList_GetItem(self->cursors, i);
238 cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
239 if ((PyObject*)cursor != Py_None) {
240 cursor->reset = 1;
241 }
242 }
243 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000244}
245
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000246void pysqlite_connection_dealloc(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000247{
248 Py_XDECREF(self->statement_cache);
249
250 /* Clean up if user has not called .close() explicitly. */
251 if (self->db) {
252 Py_BEGIN_ALLOW_THREADS
253 sqlite3_close(self->db);
254 Py_END_ALLOW_THREADS
255 }
256
257 if (self->begin_statement) {
258 PyMem_Free(self->begin_statement);
259 }
260 Py_XDECREF(self->isolation_level);
261 Py_XDECREF(self->function_pinboard);
262 Py_XDECREF(self->row_factory);
263 Py_XDECREF(self->text_factory);
264 Py_XDECREF(self->collations);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000265 Py_XDECREF(self->statements);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000266 Py_XDECREF(self->cursors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000267
Christian Heimes90aa7642007-12-19 02:45:37 +0000268 Py_TYPE(self)->tp_free((PyObject*)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000269}
270
Gerhard Häringf9cee222010-03-05 15:20:03 +0000271/*
272 * Registers a cursor with the connection.
273 *
274 * 0 => error; 1 => ok
275 */
276int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
277{
278 PyObject* weakref;
279
280 weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
281 if (!weakref) {
282 goto error;
283 }
284
285 if (PyList_Append(connection->cursors, weakref) != 0) {
286 Py_CLEAR(weakref);
287 goto error;
288 }
289
290 Py_DECREF(weakref);
291
292 return 1;
293error:
294 return 0;
295}
296
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000297PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000298{
299 static char *kwlist[] = {"factory", NULL, NULL};
300 PyObject* factory = NULL;
301 PyObject* cursor;
302
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000303 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
304 &factory)) {
305 return NULL;
306 }
307
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000308 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000309 return NULL;
310 }
311
312 if (factory == NULL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000313 factory = (PyObject*)&pysqlite_CursorType;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000314 }
315
316 cursor = PyObject_CallFunction(factory, "O", self);
317
Gerhard Häringf9cee222010-03-05 15:20:03 +0000318 _pysqlite_drop_unused_cursor_references(self);
319
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 if (cursor && self->row_factory != Py_None) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000321 Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000322 Py_INCREF(self->row_factory);
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000323 ((pysqlite_Cursor*)cursor)->row_factory = self->row_factory;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000324 }
325
326 return cursor;
327}
328
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000329PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000330{
331 int rc;
332
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000333 if (!pysqlite_check_thread(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000334 return NULL;
335 }
336
Gerhard Häringf9cee222010-03-05 15:20:03 +0000337 pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000338
339 if (self->db) {
340 Py_BEGIN_ALLOW_THREADS
341 rc = sqlite3_close(self->db);
342 Py_END_ALLOW_THREADS
343
344 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000345 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000346 return NULL;
347 } else {
348 self->db = NULL;
349 }
350 }
351
352 Py_INCREF(Py_None);
353 return Py_None;
354}
355
356/*
357 * Checks if a connection object is usable (i. e. not closed).
358 *
359 * 0 => error; 1 => ok
360 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000361int pysqlite_check_connection(pysqlite_Connection* con)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000362{
Gerhard Häringf9cee222010-03-05 15:20:03 +0000363 if (!con->initialized) {
364 PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
365 return 0;
366 }
367
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000368 if (!con->db) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000369 PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000370 return 0;
371 } else {
372 return 1;
373 }
374}
375
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000376PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000377{
378 int rc;
379 const char* tail;
380 sqlite3_stmt* statement;
381
382 Py_BEGIN_ALLOW_THREADS
383 rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
384 Py_END_ALLOW_THREADS
385
386 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000387 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000388 goto error;
389 }
390
Benjamin Petersond7b03282008-09-13 15:58:53 +0000391 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000392 if (rc == SQLITE_DONE) {
393 self->inTransaction = 1;
394 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000395 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000396 }
397
398 Py_BEGIN_ALLOW_THREADS
399 rc = sqlite3_finalize(statement);
400 Py_END_ALLOW_THREADS
401
402 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000403 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000404 }
405
406error:
407 if (PyErr_Occurred()) {
408 return NULL;
409 } else {
410 Py_INCREF(Py_None);
411 return Py_None;
412 }
413}
414
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000415PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000416{
417 int rc;
418 const char* tail;
419 sqlite3_stmt* statement;
420
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000421 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000422 return NULL;
423 }
424
425 if (self->inTransaction) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000426 pysqlite_do_all_statements(self, ACTION_RESET, 0);
427
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000428 Py_BEGIN_ALLOW_THREADS
429 rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
430 Py_END_ALLOW_THREADS
431 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000432 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000433 goto error;
434 }
435
Benjamin Petersond7b03282008-09-13 15:58:53 +0000436 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000437 if (rc == SQLITE_DONE) {
438 self->inTransaction = 0;
439 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000440 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000441 }
442
443 Py_BEGIN_ALLOW_THREADS
444 rc = sqlite3_finalize(statement);
445 Py_END_ALLOW_THREADS
446 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000447 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000448 }
449
450 }
451
452error:
453 if (PyErr_Occurred()) {
454 return NULL;
455 } else {
456 Py_INCREF(Py_None);
457 return Py_None;
458 }
459}
460
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000461PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000462{
463 int rc;
464 const char* tail;
465 sqlite3_stmt* statement;
466
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000467 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000468 return NULL;
469 }
470
471 if (self->inTransaction) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000472 pysqlite_do_all_statements(self, ACTION_RESET, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000473
474 Py_BEGIN_ALLOW_THREADS
Georg Brandl0eaa9402007-08-11 15:39:18 +0000475 rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000476 Py_END_ALLOW_THREADS
477 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000478 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000479 goto error;
480 }
481
Benjamin Petersond7b03282008-09-13 15:58:53 +0000482 rc = pysqlite_step(statement, self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000483 if (rc == SQLITE_DONE) {
484 self->inTransaction = 0;
485 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000486 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000487 }
488
489 Py_BEGIN_ALLOW_THREADS
490 rc = sqlite3_finalize(statement);
491 Py_END_ALLOW_THREADS
492 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000493 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000494 }
495
496 }
497
498error:
499 if (PyErr_Occurred()) {
500 return NULL;
501 } else {
502 Py_INCREF(Py_None);
503 return Py_None;
504 }
505}
506
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200507static int
508_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000509{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200510 if (py_val == Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000511 sqlite3_result_null(context);
Christian Heimes217cfd12007-12-02 14:31:20 +0000512 } else if (PyLong_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200513 sqlite_int64 value = _pysqlite_long_as_int64(py_val);
514 if (value == -1 && PyErr_Occurred())
515 return -1;
516 sqlite3_result_int64(context, value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000517 } else if (PyFloat_Check(py_val)) {
518 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
Guido van Rossumbae07c92007-10-08 02:46:15 +0000519 } else if (PyUnicode_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200520 const char *str = _PyUnicode_AsString(py_val);
521 if (str == NULL)
522 return -1;
523 sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000524 } else if (PyObject_CheckBuffer(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200525 const char* buffer;
526 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000527 if (PyObject_AsCharBuffer(py_val, &buffer, &buflen) != 0) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100528 PyErr_SetString(PyExc_ValueError,
529 "could not convert BLOB to buffer");
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200530 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000531 }
Victor Stinner83ed42b2013-11-18 01:24:31 +0100532 if (buflen > INT_MAX) {
533 PyErr_SetString(PyExc_OverflowError,
534 "BLOB longer than INT_MAX bytes");
535 return -1;
536 }
537 sqlite3_result_blob(context, buffer, (int)buflen, SQLITE_TRANSIENT);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000538 } else {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200539 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000540 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200541 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000542}
543
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000544PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000545{
546 PyObject* args;
547 int i;
548 sqlite3_value* cur_value;
549 PyObject* cur_py_value;
550 const char* val_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000551 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000552
553 args = PyTuple_New(argc);
554 if (!args) {
555 return NULL;
556 }
557
558 for (i = 0; i < argc; i++) {
559 cur_value = argv[i];
560 switch (sqlite3_value_type(argv[i])) {
561 case SQLITE_INTEGER:
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200562 cur_py_value = _pysqlite_long_from_int64(sqlite3_value_int64(cur_value));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000563 break;
564 case SQLITE_FLOAT:
565 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
566 break;
567 case SQLITE_TEXT:
568 val_str = (const char*)sqlite3_value_text(cur_value);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000569 cur_py_value = PyUnicode_FromString(val_str);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000570 /* TODO: have a way to show errors here */
571 if (!cur_py_value) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000573 Py_INCREF(Py_None);
574 cur_py_value = Py_None;
575 }
576 break;
577 case SQLITE_BLOB:
578 buflen = sqlite3_value_bytes(cur_value);
Christian Heimes72b710a2008-05-26 13:28:38 +0000579 cur_py_value = PyBytes_FromStringAndSize(
Guido van Rossumbae07c92007-10-08 02:46:15 +0000580 sqlite3_value_blob(cur_value), buflen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000581 break;
582 case SQLITE_NULL:
583 default:
584 Py_INCREF(Py_None);
585 cur_py_value = Py_None;
586 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587
588 if (!cur_py_value) {
589 Py_DECREF(args);
590 return NULL;
591 }
592
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000593 PyTuple_SetItem(args, i, cur_py_value);
594
595 }
596
597 return args;
598}
599
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000600void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601{
602 PyObject* args;
603 PyObject* py_func;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000604 PyObject* py_retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200605 int ok;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000606
Georg Brandldfd73442009-04-05 11:47:34 +0000607#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000608 PyGILState_STATE threadstate;
609
610 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000611#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000612
613 py_func = (PyObject*)sqlite3_user_data(context);
614
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000615 args = _pysqlite_build_py_params(context, argc, argv);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000616 if (args) {
617 py_retval = PyObject_CallObject(py_func, args);
618 Py_DECREF(args);
619 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000620
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200621 ok = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000622 if (py_retval) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200623 ok = _pysqlite_set_result(context, py_retval) == 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000624 Py_DECREF(py_retval);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200625 }
626 if (!ok) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000627 if (_enable_callback_tracebacks) {
628 PyErr_Print();
629 } else {
630 PyErr_Clear();
631 }
632 _sqlite3_result_error(context, "user-defined function raised exception", -1);
633 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000634
Georg Brandldfd73442009-04-05 11:47:34 +0000635#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000636 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000637#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000638}
639
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000640static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000641{
642 PyObject* args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000643 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000644 PyObject* aggregate_class;
645 PyObject** aggregate_instance;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000646 PyObject* stepmethod = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000647
Georg Brandldfd73442009-04-05 11:47:34 +0000648#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000649 PyGILState_STATE threadstate;
650
651 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000652#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000653
654 aggregate_class = (PyObject*)sqlite3_user_data(context);
655
656 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
657
658 if (*aggregate_instance == 0) {
659 *aggregate_instance = PyObject_CallFunction(aggregate_class, "");
660
Thomas Wouters477c8d52006-05-27 19:21:47 +0000661 if (PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000662 *aggregate_instance = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000663 if (_enable_callback_tracebacks) {
664 PyErr_Print();
665 } else {
666 PyErr_Clear();
667 }
668 _sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000669 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000670 }
671 }
672
673 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000674 if (!stepmethod) {
675 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676 }
677
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000678 args = _pysqlite_build_py_params(context, argc, params);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000679 if (!args) {
680 goto error;
681 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000682
683 function_result = PyObject_CallObject(stepmethod, args);
684 Py_DECREF(args);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000685
Thomas Wouters477c8d52006-05-27 19:21:47 +0000686 if (!function_result) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000687 if (_enable_callback_tracebacks) {
688 PyErr_Print();
689 } else {
690 PyErr_Clear();
691 }
692 _sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000693 }
694
Thomas Wouters477c8d52006-05-27 19:21:47 +0000695error:
696 Py_XDECREF(stepmethod);
697 Py_XDECREF(function_result);
698
Georg Brandldfd73442009-04-05 11:47:34 +0000699#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000700 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000701#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000702}
703
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000704void _pysqlite_final_callback(sqlite3_context* context)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000705{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200706 PyObject* function_result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000707 PyObject** aggregate_instance;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200708 _Py_IDENTIFIER(finalize);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200709 int ok;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200710 PyObject *exception, *value, *tb;
Victor Stinnerffff7632013-08-02 01:48:10 +0200711 int restore;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000712
Georg Brandldfd73442009-04-05 11:47:34 +0000713#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000714 PyGILState_STATE threadstate;
715
716 threadstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000717#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000718
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000719 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
720 if (!*aggregate_instance) {
721 /* this branch is executed if there was an exception in the aggregate's
722 * __init__ */
723
Thomas Wouters477c8d52006-05-27 19:21:47 +0000724 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000725 }
726
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200727 /* Keep the exception (if any) of the last call to step() */
728 PyErr_Fetch(&exception, &value, &tb);
Victor Stinnerffff7632013-08-02 01:48:10 +0200729 restore = 1;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200730
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200731 function_result = _PyObject_CallMethodId(*aggregate_instance, &PyId_finalize, "");
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200732
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200733 Py_DECREF(*aggregate_instance);
734
735 ok = 0;
736 if (function_result) {
737 ok = _pysqlite_set_result(context, function_result) == 0;
738 Py_DECREF(function_result);
739 }
740 if (!ok) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000741 if (_enable_callback_tracebacks) {
742 PyErr_Print();
743 } else {
744 PyErr_Clear();
745 }
746 _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
Victor Stinnerffff7632013-08-02 01:48:10 +0200747#if SQLITE_VERSION_NUMBER < 3003003
748 /* with old SQLite versions, _sqlite3_result_error() sets a new Python
749 exception, so don't restore the previous exception */
750 restore = 0;
751#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000752 }
753
Victor Stinnerffff7632013-08-02 01:48:10 +0200754 if (restore) {
755 /* Restore the exception (if any) of the last call to step(),
756 but clear also the current exception if finalize() failed */
757 PyErr_Restore(exception, value, tb);
758 }
Victor Stinner3a857322013-07-22 08:34:32 +0200759
Thomas Wouters477c8d52006-05-27 19:21:47 +0000760error:
Georg Brandldfd73442009-04-05 11:47:34 +0000761#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762 PyGILState_Release(threadstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000763#endif
Victor Stinnerb84fc0f2013-08-28 01:44:42 +0200764 /* explicit return to avoid a compilation error if WITH_THREAD
765 is not defined */
766 return;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000767}
768
Gerhard Häringf9cee222010-03-05 15:20:03 +0000769static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000770{
771 PyObject* new_list;
772 PyObject* weakref;
773 int i;
774
775 /* we only need to do this once in a while */
776 if (self->created_statements++ < 200) {
777 return;
778 }
779
780 self->created_statements = 0;
781
782 new_list = PyList_New(0);
783 if (!new_list) {
784 return;
785 }
786
787 for (i = 0; i < PyList_Size(self->statements); i++) {
788 weakref = PyList_GetItem(self->statements, i);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000789 if (PyWeakref_GetObject(weakref) != Py_None) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000790 if (PyList_Append(new_list, weakref) != 0) {
791 Py_DECREF(new_list);
792 return;
793 }
794 }
795 }
796
797 Py_DECREF(self->statements);
798 self->statements = new_list;
799}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000800
Gerhard Häringf9cee222010-03-05 15:20:03 +0000801static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
802{
803 PyObject* new_list;
804 PyObject* weakref;
805 int i;
806
807 /* we only need to do this once in a while */
808 if (self->created_cursors++ < 200) {
809 return;
810 }
811
812 self->created_cursors = 0;
813
814 new_list = PyList_New(0);
815 if (!new_list) {
816 return;
817 }
818
819 for (i = 0; i < PyList_Size(self->cursors); i++) {
820 weakref = PyList_GetItem(self->cursors, i);
821 if (PyWeakref_GetObject(weakref) != Py_None) {
822 if (PyList_Append(new_list, weakref) != 0) {
823 Py_DECREF(new_list);
824 return;
825 }
826 }
827 }
828
829 Py_DECREF(self->cursors);
830 self->cursors = new_list;
831}
832
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000833PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000834{
835 static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
836
837 PyObject* func;
838 char* name;
839 int narg;
840 int rc;
841
Gerhard Häringf9cee222010-03-05 15:20:03 +0000842 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
843 return NULL;
844 }
845
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000846 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
847 &name, &narg, &func))
848 {
849 return NULL;
850 }
851
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000852 rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000853
Thomas Wouters477c8d52006-05-27 19:21:47 +0000854 if (rc != SQLITE_OK) {
855 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000856 PyErr_SetString(pysqlite_OperationalError, "Error creating function");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000857 return NULL;
858 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000859 if (PyDict_SetItem(self->function_pinboard, func, Py_None) == -1)
860 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000861
Thomas Wouters477c8d52006-05-27 19:21:47 +0000862 Py_INCREF(Py_None);
863 return Py_None;
864 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000865}
866
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000867PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000868{
869 PyObject* aggregate_class;
870
871 int n_arg;
872 char* name;
873 static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
874 int rc;
875
Gerhard Häringf9cee222010-03-05 15:20:03 +0000876 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
877 return NULL;
878 }
879
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000880 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
881 kwlist, &name, &n_arg, &aggregate_class)) {
882 return NULL;
883 }
884
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000885 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 +0000886 if (rc != SQLITE_OK) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000887 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000888 PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000889 return NULL;
890 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000891 if (PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None) == -1)
892 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000893
894 Py_INCREF(Py_None);
895 return Py_None;
896 }
897}
898
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000899static 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 +0000900{
901 PyObject *ret;
902 int rc;
Georg Brandldfd73442009-04-05 11:47:34 +0000903#ifdef WITH_THREAD
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000904 PyGILState_STATE gilstate;
905
906 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000907#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000908
Victor Stinnerd4095d92013-07-26 22:23:33 +0200909 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000910
Victor Stinnerd4095d92013-07-26 22:23:33 +0200911 if (ret == NULL) {
912 if (_enable_callback_tracebacks)
913 PyErr_Print();
914 else
915 PyErr_Clear();
Victor Stinner41801f52013-07-21 13:05:38 +0200916
Victor Stinnerd4095d92013-07-26 22:23:33 +0200917 rc = SQLITE_DENY;
Victor Stinner41801f52013-07-21 13:05:38 +0200918 }
919 else {
Victor Stinnerd4095d92013-07-26 22:23:33 +0200920 if (PyLong_Check(ret)) {
921 rc = _PyLong_AsInt(ret);
922 if (rc == -1 && PyErr_Occurred()) {
923 if (_enable_callback_tracebacks)
924 PyErr_Print();
925 else
926 PyErr_Clear();
927 rc = SQLITE_DENY;
928 }
929 }
930 else {
931 rc = SQLITE_DENY;
932 }
933 Py_DECREF(ret);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000934 }
935
Georg Brandldfd73442009-04-05 11:47:34 +0000936#ifdef WITH_THREAD
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000937 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000938#endif
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000939 return rc;
940}
941
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000942static int _progress_handler(void* user_arg)
943{
944 int rc;
945 PyObject *ret;
Georg Brandldfd73442009-04-05 11:47:34 +0000946#ifdef WITH_THREAD
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000947 PyGILState_STATE gilstate;
948
949 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000950#endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000951 ret = PyObject_CallFunction((PyObject*)user_arg, "");
952
953 if (!ret) {
954 if (_enable_callback_tracebacks) {
955 PyErr_Print();
956 } else {
957 PyErr_Clear();
958 }
959
Mark Dickinson934896d2009-02-21 20:59:32 +0000960 /* abort query if error occurred */
Victor Stinner86999502010-05-19 01:27:23 +0000961 rc = 1;
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000962 } else {
963 rc = (int)PyObject_IsTrue(ret);
964 Py_DECREF(ret);
965 }
966
Georg Brandldfd73442009-04-05 11:47:34 +0000967#ifdef WITH_THREAD
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000968 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +0000969#endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000970 return rc;
971}
972
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200973static void _trace_callback(void* user_arg, const char* statement_string)
974{
975 PyObject *py_statement = NULL;
976 PyObject *ret = NULL;
977
978#ifdef WITH_THREAD
979 PyGILState_STATE gilstate;
980
981 gilstate = PyGILState_Ensure();
982#endif
983 py_statement = PyUnicode_DecodeUTF8(statement_string,
984 strlen(statement_string), "replace");
985 if (py_statement) {
986 ret = PyObject_CallFunctionObjArgs((PyObject*)user_arg, py_statement, NULL);
987 Py_DECREF(py_statement);
988 }
989
990 if (ret) {
991 Py_DECREF(ret);
992 } else {
993 if (_enable_callback_tracebacks) {
994 PyErr_Print();
995 } else {
996 PyErr_Clear();
997 }
998 }
999
1000#ifdef WITH_THREAD
1001 PyGILState_Release(gilstate);
1002#endif
1003}
1004
Gerhard Häringf9cee222010-03-05 15:20:03 +00001005static PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001006{
1007 PyObject* authorizer_cb;
1008
1009 static char *kwlist[] = { "authorizer_callback", NULL };
1010 int rc;
1011
Gerhard Häringf9cee222010-03-05 15:20:03 +00001012 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1013 return NULL;
1014 }
1015
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001016 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
1017 kwlist, &authorizer_cb)) {
1018 return NULL;
1019 }
1020
1021 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
1022
1023 if (rc != SQLITE_OK) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001024 PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001025 return NULL;
1026 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001027 if (PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None) == -1)
1028 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001029
1030 Py_INCREF(Py_None);
1031 return Py_None;
1032 }
1033}
1034
Gerhard Häringf9cee222010-03-05 15:20:03 +00001035static PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001036{
1037 PyObject* progress_handler;
1038 int n;
1039
1040 static char *kwlist[] = { "progress_handler", "n", NULL };
1041
Gerhard Häringf9cee222010-03-05 15:20:03 +00001042 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1043 return NULL;
1044 }
1045
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001046 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
1047 kwlist, &progress_handler, &n)) {
1048 return NULL;
1049 }
1050
1051 if (progress_handler == Py_None) {
1052 /* None clears the progress handler previously set */
1053 sqlite3_progress_handler(self->db, 0, 0, (void*)0);
1054 } else {
1055 sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
Gerhard Häringf9cee222010-03-05 15:20:03 +00001056 if (PyDict_SetItem(self->function_pinboard, progress_handler, Py_None) == -1)
1057 return NULL;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001058 }
1059
1060 Py_INCREF(Py_None);
1061 return Py_None;
1062}
1063
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001064static PyObject* pysqlite_connection_set_trace_callback(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1065{
1066 PyObject* trace_callback;
1067
1068 static char *kwlist[] = { "trace_callback", NULL };
1069
1070 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1071 return NULL;
1072 }
1073
1074 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_trace_callback",
1075 kwlist, &trace_callback)) {
1076 return NULL;
1077 }
1078
1079 if (trace_callback == Py_None) {
1080 /* None clears the trace callback previously set */
1081 sqlite3_trace(self->db, 0, (void*)0);
1082 } else {
1083 if (PyDict_SetItem(self->function_pinboard, trace_callback, Py_None) == -1)
1084 return NULL;
1085 sqlite3_trace(self->db, _trace_callback, trace_callback);
1086 }
1087
1088 Py_INCREF(Py_None);
1089 return Py_None;
1090}
1091
Gerhard Häringf9cee222010-03-05 15:20:03 +00001092#ifdef HAVE_LOAD_EXTENSION
1093static PyObject* pysqlite_enable_load_extension(pysqlite_Connection* self, PyObject* args)
1094{
1095 int rc;
1096 int onoff;
1097
1098 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1099 return NULL;
1100 }
1101
1102 if (!PyArg_ParseTuple(args, "i", &onoff)) {
1103 return NULL;
1104 }
1105
1106 rc = sqlite3_enable_load_extension(self->db, onoff);
1107
1108 if (rc != SQLITE_OK) {
1109 PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
1110 return NULL;
1111 } else {
1112 Py_INCREF(Py_None);
1113 return Py_None;
1114 }
1115}
1116
1117static PyObject* pysqlite_load_extension(pysqlite_Connection* self, PyObject* args)
1118{
1119 int rc;
1120 char* extension_name;
1121 char* errmsg;
1122
1123 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1124 return NULL;
1125 }
1126
1127 if (!PyArg_ParseTuple(args, "s", &extension_name)) {
1128 return NULL;
1129 }
1130
1131 rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1132 if (rc != 0) {
1133 PyErr_SetString(pysqlite_OperationalError, errmsg);
1134 return NULL;
1135 } else {
1136 Py_INCREF(Py_None);
1137 return Py_None;
1138 }
1139}
1140#endif
1141
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001142int pysqlite_check_thread(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001143{
Georg Brandldfd73442009-04-05 11:47:34 +00001144#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001145 if (self->check_same_thread) {
1146 if (PyThread_get_thread_ident() != self->thread_ident) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001147 PyErr_Format(pysqlite_ProgrammingError,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001148 "SQLite objects created in a thread can only be used in that same thread."
1149 "The object was created in thread id %ld and this is thread id %ld",
1150 self->thread_ident, PyThread_get_thread_ident());
1151 return 0;
1152 }
1153
1154 }
Georg Brandldfd73442009-04-05 11:47:34 +00001155#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001156 return 1;
1157}
1158
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001159static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001160{
1161 Py_INCREF(self->isolation_level);
1162 return self->isolation_level;
1163}
1164
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001165static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001166{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001167 if (!pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001168 return NULL;
1169 } else {
1170 return Py_BuildValue("i", sqlite3_total_changes(self->db));
1171 }
1172}
1173
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001174static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001175{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001176 PyObject* res;
1177 PyObject* begin_statement;
Georg Brandlceab6102007-11-25 00:45:05 +00001178 static PyObject* begin_word;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001179
1180 Py_XDECREF(self->isolation_level);
1181
1182 if (self->begin_statement) {
1183 PyMem_Free(self->begin_statement);
1184 self->begin_statement = NULL;
1185 }
1186
1187 if (isolation_level == Py_None) {
1188 Py_INCREF(Py_None);
1189 self->isolation_level = Py_None;
1190
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001191 res = pysqlite_connection_commit(self, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001192 if (!res) {
1193 return -1;
1194 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001195 Py_DECREF(res);
1196
1197 self->inTransaction = 0;
1198 } else {
Neal Norwitzefee9f52007-10-27 02:50:52 +00001199 const char *statement;
1200 Py_ssize_t size;
1201
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001202 Py_INCREF(isolation_level);
1203 self->isolation_level = isolation_level;
1204
Georg Brandlceab6102007-11-25 00:45:05 +00001205 if (!begin_word) {
1206 begin_word = PyUnicode_FromString("BEGIN ");
1207 if (!begin_word) return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001208 }
Georg Brandlceab6102007-11-25 00:45:05 +00001209 begin_statement = PyUnicode_Concat(begin_word, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001210 if (!begin_statement) {
1211 return -1;
1212 }
1213
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001214 statement = _PyUnicode_AsStringAndSize(begin_statement, &size);
Georg Brandl3dbca812008-07-23 16:10:53 +00001215 if (!statement) {
Victor Stinnerff27d6b2010-03-13 00:57:22 +00001216 Py_DECREF(begin_statement);
Georg Brandl3dbca812008-07-23 16:10:53 +00001217 return -1;
1218 }
Neal Norwitzefee9f52007-10-27 02:50:52 +00001219 self->begin_statement = PyMem_Malloc(size + 2);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001220 if (!self->begin_statement) {
Georg Brandl3dbca812008-07-23 16:10:53 +00001221 Py_DECREF(begin_statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001222 return -1;
1223 }
1224
Neal Norwitzefee9f52007-10-27 02:50:52 +00001225 strcpy(self->begin_statement, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001226 Py_DECREF(begin_statement);
1227 }
1228
1229 return 0;
1230}
1231
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001232PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001233{
1234 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001235 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001236 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001237 int rc;
1238
Gerhard Häringf9cee222010-03-05 15:20:03 +00001239 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1240 return NULL;
1241 }
1242
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001243 if (!PyArg_ParseTuple(args, "O", &sql))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001244 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001245
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001246 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001247
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001248 statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001249 if (!statement) {
1250 return NULL;
1251 }
1252
Victor Stinner0201f442010-03-13 03:28:34 +00001253 statement->db = NULL;
1254 statement->st = NULL;
1255 statement->sql = NULL;
1256 statement->in_use = 0;
1257 statement->in_weakreflist = NULL;
1258
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001259 rc = pysqlite_statement_create(statement, self, sql);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001260 if (rc != SQLITE_OK) {
1261 if (rc == PYSQLITE_TOO_MUCH_SQL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001262 PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001263 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
Serhiy Storchaka42d67af2014-09-11 13:29:05 +03001264 if (PyErr_ExceptionMatches(PyExc_TypeError))
1265 PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001266 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001267 (void)pysqlite_statement_reset(statement);
1268 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001269 }
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001270 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001271 }
1272
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001273 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
1274 if (weakref == NULL)
1275 goto error;
1276 if (PyList_Append(self->statements, weakref) != 0) {
1277 Py_DECREF(weakref);
1278 goto error;
1279 }
1280 Py_DECREF(weakref);
1281
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001282 return (PyObject*)statement;
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001283
1284error:
1285 Py_DECREF(statement);
1286 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001287}
1288
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001289PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001290{
1291 PyObject* cursor = 0;
1292 PyObject* result = 0;
1293 PyObject* method = 0;
1294
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001295 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001296 if (!cursor) {
1297 goto error;
1298 }
1299
1300 method = PyObject_GetAttrString(cursor, "execute");
1301 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001302 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001303 goto error;
1304 }
1305
1306 result = PyObject_CallObject(method, args);
1307 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001308 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001309 }
1310
1311error:
1312 Py_XDECREF(result);
1313 Py_XDECREF(method);
1314
1315 return cursor;
1316}
1317
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001318PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001319{
1320 PyObject* cursor = 0;
1321 PyObject* result = 0;
1322 PyObject* method = 0;
1323
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001324 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001325 if (!cursor) {
1326 goto error;
1327 }
1328
1329 method = PyObject_GetAttrString(cursor, "executemany");
1330 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001331 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001332 goto error;
1333 }
1334
1335 result = PyObject_CallObject(method, args);
1336 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001337 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001338 }
1339
1340error:
1341 Py_XDECREF(result);
1342 Py_XDECREF(method);
1343
1344 return cursor;
1345}
1346
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001347PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001348{
1349 PyObject* cursor = 0;
1350 PyObject* result = 0;
1351 PyObject* method = 0;
1352
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001353 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001354 if (!cursor) {
1355 goto error;
1356 }
1357
1358 method = PyObject_GetAttrString(cursor, "executescript");
1359 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001360 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001361 goto error;
1362 }
1363
1364 result = PyObject_CallObject(method, args);
1365 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001366 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001367 }
1368
1369error:
1370 Py_XDECREF(result);
1371 Py_XDECREF(method);
1372
1373 return cursor;
1374}
1375
1376/* ------------------------- COLLATION CODE ------------------------ */
1377
1378static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001379pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001380 void* context,
1381 int text1_length, const void* text1_data,
1382 int text2_length, const void* text2_data)
1383{
1384 PyObject* callback = (PyObject*)context;
1385 PyObject* string1 = 0;
1386 PyObject* string2 = 0;
Georg Brandldfd73442009-04-05 11:47:34 +00001387#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001388 PyGILState_STATE gilstate;
Georg Brandldfd73442009-04-05 11:47:34 +00001389#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001390 PyObject* retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001391 long longval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001392 int result = 0;
Georg Brandldfd73442009-04-05 11:47:34 +00001393#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001394 gilstate = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +00001395#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001396
1397 if (PyErr_Occurred()) {
1398 goto finally;
1399 }
1400
Guido van Rossum98297ee2007-11-06 21:34:58 +00001401 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1402 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001403
1404 if (!string1 || !string2) {
1405 goto finally; /* failed to allocate strings */
1406 }
1407
1408 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1409
1410 if (!retval) {
1411 /* execution failed */
1412 goto finally;
1413 }
1414
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001415 longval = PyLong_AsLongAndOverflow(retval, &result);
1416 if (longval == -1 && PyErr_Occurred()) {
1417 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001418 result = 0;
1419 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001420 else if (!result) {
1421 if (longval > 0)
1422 result = 1;
1423 else if (longval < 0)
1424 result = -1;
1425 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001426
1427finally:
1428 Py_XDECREF(string1);
1429 Py_XDECREF(string2);
1430 Py_XDECREF(retval);
Georg Brandldfd73442009-04-05 11:47:34 +00001431#ifdef WITH_THREAD
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001432 PyGILState_Release(gilstate);
Georg Brandldfd73442009-04-05 11:47:34 +00001433#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001434 return result;
1435}
1436
1437static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001438pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001439{
1440 PyObject* retval = NULL;
1441
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001442 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001443 goto finally;
1444 }
1445
1446 sqlite3_interrupt(self->db);
1447
1448 Py_INCREF(Py_None);
1449 retval = Py_None;
1450
1451finally:
1452 return retval;
1453}
1454
Christian Heimesbbe741d2008-03-28 10:53:29 +00001455/* Function author: Paul Kippes <kippesp@gmail.com>
1456 * Class method of Connection to call the Python function _iterdump
1457 * of the sqlite3 module.
1458 */
1459static PyObject *
1460pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1461{
1462 PyObject* retval = NULL;
1463 PyObject* module = NULL;
1464 PyObject* module_dict;
1465 PyObject* pyfn_iterdump;
1466
1467 if (!pysqlite_check_connection(self)) {
1468 goto finally;
1469 }
1470
1471 module = PyImport_ImportModule(MODULE_NAME ".dump");
1472 if (!module) {
1473 goto finally;
1474 }
1475
1476 module_dict = PyModule_GetDict(module);
1477 if (!module_dict) {
1478 goto finally;
1479 }
1480
1481 pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
1482 if (!pyfn_iterdump) {
1483 PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
1484 goto finally;
1485 }
1486
1487 args = PyTuple_New(1);
1488 if (!args) {
1489 goto finally;
1490 }
1491 Py_INCREF(self);
1492 PyTuple_SetItem(args, 0, (PyObject*)self);
1493 retval = PyObject_CallObject(pyfn_iterdump, args);
1494
1495finally:
1496 Py_XDECREF(args);
1497 Py_XDECREF(module);
1498 return retval;
1499}
1500
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001501static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001502pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001503{
1504 PyObject* callable;
1505 PyObject* uppercase_name = 0;
1506 PyObject* name;
1507 PyObject* retval;
Victor Stinner35466c52010-04-22 11:23:23 +00001508 Py_ssize_t i, len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001509 _Py_IDENTIFIER(upper);
Victor Stinner35466c52010-04-22 11:23:23 +00001510 char *uppercase_name_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001511 int rc;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 unsigned int kind;
1513 void *data;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001514
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001515 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001516 goto finally;
1517 }
1518
Gerhard Häring6d214562007-08-10 18:15:11 +00001519 if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyUnicode_Type, &name, &callable)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001520 goto finally;
1521 }
1522
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001523 uppercase_name = _PyObject_CallMethodId(name, &PyId_upper, "");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001524 if (!uppercase_name) {
1525 goto finally;
1526 }
1527
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001528 if (PyUnicode_READY(uppercase_name))
1529 goto finally;
1530 len = PyUnicode_GET_LENGTH(uppercase_name);
1531 kind = PyUnicode_KIND(uppercase_name);
1532 data = PyUnicode_DATA(uppercase_name);
1533 for (i=0; i<len; i++) {
1534 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1535 if ((ch >= '0' && ch <= '9')
1536 || (ch >= 'A' && ch <= 'Z')
1537 || (ch == '_'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001538 {
Victor Stinner35466c52010-04-22 11:23:23 +00001539 continue;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001540 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001541 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001542 goto finally;
1543 }
1544 }
1545
Victor Stinner35466c52010-04-22 11:23:23 +00001546 uppercase_name_str = _PyUnicode_AsString(uppercase_name);
1547 if (!uppercase_name_str)
1548 goto finally;
1549
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001550 if (callable != Py_None && !PyCallable_Check(callable)) {
1551 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1552 goto finally;
1553 }
1554
1555 if (callable != Py_None) {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001556 if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
1557 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001558 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001559 if (PyDict_DelItem(self->collations, uppercase_name) == -1)
1560 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001561 }
1562
1563 rc = sqlite3_create_collation(self->db,
Victor Stinner35466c52010-04-22 11:23:23 +00001564 uppercase_name_str,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001565 SQLITE_UTF8,
1566 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001567 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001568 if (rc != SQLITE_OK) {
1569 PyDict_DelItem(self->collations, uppercase_name);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001570 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001571 goto finally;
1572 }
1573
1574finally:
1575 Py_XDECREF(uppercase_name);
1576
1577 if (PyErr_Occurred()) {
1578 retval = NULL;
1579 } else {
1580 Py_INCREF(Py_None);
1581 retval = Py_None;
1582 }
1583
1584 return retval;
1585}
1586
Christian Heimesbbe741d2008-03-28 10:53:29 +00001587/* Called when the connection is used as a context manager. Returns itself as a
1588 * convenience to the caller. */
1589static PyObject *
1590pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1591{
1592 Py_INCREF(self);
1593 return (PyObject*)self;
1594}
1595
1596/** Called when the connection is used as a context manager. If there was any
1597 * exception, a rollback takes place; otherwise we commit. */
1598static PyObject *
1599pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1600{
1601 PyObject* exc_type, *exc_value, *exc_tb;
1602 char* method_name;
1603 PyObject* result;
1604
1605 if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1606 return NULL;
1607 }
1608
1609 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1610 method_name = "commit";
1611 } else {
1612 method_name = "rollback";
1613 }
1614
1615 result = PyObject_CallMethod((PyObject*)self, method_name, "");
1616 if (!result) {
1617 return NULL;
1618 }
1619 Py_DECREF(result);
1620
1621 Py_RETURN_FALSE;
1622}
1623
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001624static char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001625PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001626
1627static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001628 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1629 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001630 {NULL}
1631};
1632
1633static PyMethodDef connection_methods[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001634 {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001635 PyDoc_STR("Return a cursor for the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001636 {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001637 PyDoc_STR("Closes the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001638 {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001639 PyDoc_STR("Commit the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001640 {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001641 PyDoc_STR("Roll back the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001642 {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001643 PyDoc_STR("Creates a new function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001644 {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001645 PyDoc_STR("Creates a new aggregate. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001646 {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001647 PyDoc_STR("Sets authorizer callback. Non-standard.")},
Gerhard Häringf9cee222010-03-05 15:20:03 +00001648 #ifdef HAVE_LOAD_EXTENSION
1649 {"enable_load_extension", (PyCFunction)pysqlite_enable_load_extension, METH_VARARGS,
1650 PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
1651 {"load_extension", (PyCFunction)pysqlite_load_extension, METH_VARARGS,
1652 PyDoc_STR("Load SQLite extension module. Non-standard.")},
1653 #endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001654 {"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
1655 PyDoc_STR("Sets progress handler callback. Non-standard.")},
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001656 {"set_trace_callback", (PyCFunction)pysqlite_connection_set_trace_callback, METH_VARARGS|METH_KEYWORDS,
1657 PyDoc_STR("Sets a trace callback called for each SQL statement (passed as unicode). Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001658 {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001659 PyDoc_STR("Executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001660 {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001661 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001662 {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001663 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001664 {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001665 PyDoc_STR("Creates a collation function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001666 {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001667 PyDoc_STR("Abort any pending database operation. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001668 {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
Benjamin Petersond7b03282008-09-13 15:58:53 +00001669 PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001670 {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1671 PyDoc_STR("For context manager. Non-standard.")},
1672 {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1673 PyDoc_STR("For context manager. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001674 {NULL, NULL}
1675};
1676
1677static struct PyMemberDef connection_members[] =
1678{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001679 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1680 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1681 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1682 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1683 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1684 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1685 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1686 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1687 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1688 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001689 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1690 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
R. David Murrayd35251d2010-06-01 01:32:12 +00001691 {"in_transaction", T_BOOL, offsetof(pysqlite_Connection, inTransaction), READONLY},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001692 {NULL}
1693};
1694
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001695PyTypeObject pysqlite_ConnectionType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001696 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001697 MODULE_NAME ".Connection", /* tp_name */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001698 sizeof(pysqlite_Connection), /* tp_basicsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001699 0, /* tp_itemsize */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001700 (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001701 0, /* tp_print */
1702 0, /* tp_getattr */
1703 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001704 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001705 0, /* tp_repr */
1706 0, /* tp_as_number */
1707 0, /* tp_as_sequence */
1708 0, /* tp_as_mapping */
1709 0, /* tp_hash */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001710 (ternaryfunc)pysqlite_connection_call, /* tp_call */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001711 0, /* tp_str */
1712 0, /* tp_getattro */
1713 0, /* tp_setattro */
1714 0, /* tp_as_buffer */
1715 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1716 connection_doc, /* tp_doc */
1717 0, /* tp_traverse */
1718 0, /* tp_clear */
1719 0, /* tp_richcompare */
1720 0, /* tp_weaklistoffset */
1721 0, /* tp_iter */
1722 0, /* tp_iternext */
1723 connection_methods, /* tp_methods */
1724 connection_members, /* tp_members */
1725 connection_getset, /* tp_getset */
1726 0, /* tp_base */
1727 0, /* tp_dict */
1728 0, /* tp_descr_get */
1729 0, /* tp_descr_set */
1730 0, /* tp_dictoffset */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001731 (initproc)pysqlite_connection_init, /* tp_init */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001732 0, /* tp_alloc */
1733 0, /* tp_new */
1734 0 /* tp_free */
1735};
1736
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001737extern int pysqlite_connection_setup_types(void)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001738{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001739 pysqlite_ConnectionType.tp_new = PyType_GenericNew;
1740 return PyType_Ready(&pysqlite_ConnectionType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001741}