blob: f596bcf7acac43a9fc826b19c0883433ef27be2d [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
Serhiy Storchaka28914922016-09-01 22:18:03 +030046static const char * const begin_statements[] = {
47 "BEGIN ",
48 "BEGIN DEFERRED",
49 "BEGIN IMMEDIATE",
50 "BEGIN EXCLUSIVE",
51 NULL
52};
53
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000054static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level);
Gerhard Häringf9cee222010-03-05 15:20:03 +000055static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000056
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057
Benjamin Petersond7b03282008-09-13 15:58:53 +000058static void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059{
60 /* in older SQLite versions, calling sqlite3_result_error in callbacks
61 * triggers a bug in SQLite that leads either to irritating results or
62 * segfaults, depending on the SQLite version */
63#if SQLITE_VERSION_NUMBER >= 3003003
64 sqlite3_result_error(ctx, errmsg, len);
65#else
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000066 PyErr_SetString(pysqlite_OperationalError, errmsg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067#endif
68}
69
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000070int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000071{
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010072 static char *kwlist[] = {
73 "database", "timeout", "detect_types", "isolation_level",
74 "check_same_thread", "factory", "cached_statements", "uri",
75 NULL
76 };
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000077
78 char* database;
79 int detect_types = 0;
80 PyObject* isolation_level = NULL;
81 PyObject* factory = NULL;
82 int check_same_thread = 1;
83 int cached_statements = 100;
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010084 int uri = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000085 double timeout = 5.0;
86 int rc;
87
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010088 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOip", kwlist,
89 &database, &timeout, &detect_types,
90 &isolation_level, &check_same_thread,
91 &factory, &cached_statements, &uri))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000092 {
Gerhard Häringe7ea7452008-03-29 00:45:29 +000093 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000094 }
95
Gerhard Häringf9cee222010-03-05 15:20:03 +000096 self->initialized = 1;
97
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000098 self->begin_statement = NULL;
99
100 self->statement_cache = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000101 self->statements = NULL;
Gerhard Häringf9cee222010-03-05 15:20:03 +0000102 self->cursors = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000103
104 Py_INCREF(Py_None);
105 self->row_factory = Py_None;
106
107 Py_INCREF(&PyUnicode_Type);
108 self->text_factory = (PyObject*)&PyUnicode_Type;
109
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100110#ifdef SQLITE_OPEN_URI
111 Py_BEGIN_ALLOW_THREADS
112 rc = sqlite3_open_v2(database, &self->db,
113 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
114 (uri ? SQLITE_OPEN_URI : 0), NULL);
115#else
116 if (uri) {
117 PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
118 return -1;
119 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000120 Py_BEGIN_ALLOW_THREADS
Aviv Palivoda86a67052017-03-03 12:58:17 +0200121 /* No need to use sqlite3_open_v2 as sqlite3_open(filename, db) is the
122 same as sqlite3_open_v2(filename, db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL). */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000123 rc = sqlite3_open(database, &self->db);
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100124#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000125 Py_END_ALLOW_THREADS
126
127 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000128 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000129 return -1;
130 }
131
132 if (!isolation_level) {
Neal Norwitzefee9f52007-10-27 02:50:52 +0000133 isolation_level = PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000134 if (!isolation_level) {
135 return -1;
136 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000137 } else {
138 Py_INCREF(isolation_level);
139 }
140 self->isolation_level = NULL;
Victor Stinnercb1f74e2013-12-19 16:38:03 +0100141 if (pysqlite_connection_set_isolation_level(self, isolation_level) < 0) {
142 Py_DECREF(isolation_level);
143 return -1;
144 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000145 Py_DECREF(isolation_level);
146
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000147 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000148 if (PyErr_Occurred()) {
149 return -1;
150 }
151
Gerhard Häringf9cee222010-03-05 15:20:03 +0000152 self->created_statements = 0;
153 self->created_cursors = 0;
154
155 /* Create lists of weak references to statements/cursors */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000156 self->statements = PyList_New(0);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000157 self->cursors = PyList_New(0);
158 if (!self->statements || !self->cursors) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000159 return -1;
160 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000161
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000162 /* By default, the Cache class INCREFs the factory in its initializer, and
163 * decrefs it in its deallocator method. Since this would create a circular
164 * reference here, we're breaking it by decrementing self, and telling the
165 * cache class to not decref the factory (self) in its deallocator.
166 */
167 self->statement_cache->decref_factory = 0;
168 Py_DECREF(self);
169
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000170 self->detect_types = detect_types;
171 self->timeout = timeout;
172 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000173 self->thread_ident = PyThread_get_thread_ident();
Berker Peksag7bea2342016-06-12 14:09:51 +0300174 if (!check_same_thread && sqlite3_libversion_number() < 3003001) {
175 PyErr_SetString(pysqlite_NotSupportedError, "shared connections not available");
176 return -1;
177 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000178 self->check_same_thread = check_same_thread;
179
180 self->function_pinboard = PyDict_New();
181 if (!self->function_pinboard) {
182 return -1;
183 }
184
185 self->collations = PyDict_New();
186 if (!self->collations) {
187 return -1;
188 }
189
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000190 self->Warning = pysqlite_Warning;
191 self->Error = pysqlite_Error;
192 self->InterfaceError = pysqlite_InterfaceError;
193 self->DatabaseError = pysqlite_DatabaseError;
194 self->DataError = pysqlite_DataError;
195 self->OperationalError = pysqlite_OperationalError;
196 self->IntegrityError = pysqlite_IntegrityError;
197 self->InternalError = pysqlite_InternalError;
198 self->ProgrammingError = pysqlite_ProgrammingError;
199 self->NotSupportedError = pysqlite_NotSupportedError;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000200
201 return 0;
202}
203
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000204/* action in (ACTION_RESET, ACTION_FINALIZE) */
Gerhard Häringf9cee222010-03-05 15:20:03 +0000205void pysqlite_do_all_statements(pysqlite_Connection* self, int action, int reset_cursors)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000206{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000207 int i;
208 PyObject* weakref;
209 PyObject* statement;
Gerhard Häringf9cee222010-03-05 15:20:03 +0000210 pysqlite_Cursor* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211
Thomas Wouters477c8d52006-05-27 19:21:47 +0000212 for (i = 0; i < PyList_Size(self->statements); i++) {
213 weakref = PyList_GetItem(self->statements, i);
214 statement = PyWeakref_GetObject(weakref);
215 if (statement != Py_None) {
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500216 Py_INCREF(statement);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000217 if (action == ACTION_RESET) {
218 (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
219 } else {
220 (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
221 }
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500222 Py_DECREF(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000223 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000224 }
Gerhard Häringf9cee222010-03-05 15:20:03 +0000225
226 if (reset_cursors) {
227 for (i = 0; i < PyList_Size(self->cursors); i++) {
228 weakref = PyList_GetItem(self->cursors, i);
229 cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
230 if ((PyObject*)cursor != Py_None) {
231 cursor->reset = 1;
232 }
233 }
234 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000235}
236
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000237void pysqlite_connection_dealloc(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000238{
239 Py_XDECREF(self->statement_cache);
240
241 /* Clean up if user has not called .close() explicitly. */
242 if (self->db) {
243 Py_BEGIN_ALLOW_THREADS
Aviv Palivoda86a67052017-03-03 12:58:17 +0200244 SQLITE3_CLOSE(self->db);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000245 Py_END_ALLOW_THREADS
246 }
247
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000248 Py_XDECREF(self->isolation_level);
249 Py_XDECREF(self->function_pinboard);
250 Py_XDECREF(self->row_factory);
251 Py_XDECREF(self->text_factory);
252 Py_XDECREF(self->collations);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000253 Py_XDECREF(self->statements);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000254 Py_XDECREF(self->cursors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000255
Christian Heimes90aa7642007-12-19 02:45:37 +0000256 Py_TYPE(self)->tp_free((PyObject*)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000257}
258
Gerhard Häringf9cee222010-03-05 15:20:03 +0000259/*
260 * Registers a cursor with the connection.
261 *
262 * 0 => error; 1 => ok
263 */
264int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
265{
266 PyObject* weakref;
267
268 weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
269 if (!weakref) {
270 goto error;
271 }
272
273 if (PyList_Append(connection->cursors, weakref) != 0) {
274 Py_CLEAR(weakref);
275 goto error;
276 }
277
278 Py_DECREF(weakref);
279
280 return 1;
281error:
282 return 0;
283}
284
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000285PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286{
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300287 static char *kwlist[] = {"factory", NULL};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000288 PyObject* factory = NULL;
289 PyObject* cursor;
290
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000291 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
292 &factory)) {
293 return NULL;
294 }
295
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000296 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000297 return NULL;
298 }
299
300 if (factory == NULL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000301 factory = (PyObject*)&pysqlite_CursorType;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000302 }
303
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300304 cursor = PyObject_CallFunctionObjArgs(factory, (PyObject *)self, NULL);
305 if (cursor == NULL)
306 return NULL;
307 if (!PyObject_TypeCheck(cursor, &pysqlite_CursorType)) {
308 PyErr_Format(PyExc_TypeError,
309 "factory must return a cursor, not %.100s",
310 Py_TYPE(cursor)->tp_name);
311 Py_DECREF(cursor);
312 return NULL;
313 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000314
Gerhard Häringf9cee222010-03-05 15:20:03 +0000315 _pysqlite_drop_unused_cursor_references(self);
316
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000317 if (cursor && self->row_factory != Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000318 Py_INCREF(self->row_factory);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300319 Py_XSETREF(((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
Aviv Palivoda86a67052017-03-03 12:58:17 +0200337 rc = SQLITE3_CLOSE(self->db);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000338 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
Berker Peksagfe21de92016-04-09 07:34:39 +0300348 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000349}
350
351/*
352 * Checks if a connection object is usable (i. e. not closed).
353 *
354 * 0 => error; 1 => ok
355 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000356int pysqlite_check_connection(pysqlite_Connection* con)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000357{
Gerhard Häringf9cee222010-03-05 15:20:03 +0000358 if (!con->initialized) {
359 PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
360 return 0;
361 }
362
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000363 if (!con->db) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000364 PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000365 return 0;
366 } else {
367 return 1;
368 }
369}
370
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000371PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000372{
373 int rc;
374 const char* tail;
375 sqlite3_stmt* statement;
376
377 Py_BEGIN_ALLOW_THREADS
Aviv Palivoda86a67052017-03-03 12:58:17 +0200378 rc = SQLITE3_PREPARE(self->db, self->begin_statement, -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000379 Py_END_ALLOW_THREADS
380
381 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000382 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000383 goto error;
384 }
385
Benjamin Petersond7b03282008-09-13 15:58:53 +0000386 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300387 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000388 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000389 }
390
391 Py_BEGIN_ALLOW_THREADS
392 rc = sqlite3_finalize(statement);
393 Py_END_ALLOW_THREADS
394
395 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000396 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000397 }
398
399error:
400 if (PyErr_Occurred()) {
401 return NULL;
402 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200403 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000404 }
405}
406
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000407PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000408{
409 int rc;
410 const char* tail;
411 sqlite3_stmt* statement;
412
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000413 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000414 return NULL;
415 }
416
Berker Peksag59da4b32016-09-12 07:16:43 +0300417 if (!sqlite3_get_autocommit(self->db)) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000418
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000419 Py_BEGIN_ALLOW_THREADS
Aviv Palivoda86a67052017-03-03 12:58:17 +0200420 rc = SQLITE3_PREPARE(self->db, "COMMIT", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000421 Py_END_ALLOW_THREADS
422 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000423 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000424 goto error;
425 }
426
Benjamin Petersond7b03282008-09-13 15:58:53 +0000427 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300428 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000429 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000430 }
431
432 Py_BEGIN_ALLOW_THREADS
433 rc = sqlite3_finalize(statement);
434 Py_END_ALLOW_THREADS
435 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000436 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000437 }
438
439 }
440
441error:
442 if (PyErr_Occurred()) {
443 return NULL;
444 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200445 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000446 }
447}
448
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000449PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000450{
451 int rc;
452 const char* tail;
453 sqlite3_stmt* statement;
454
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000455 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000456 return NULL;
457 }
458
Berker Peksag59da4b32016-09-12 07:16:43 +0300459 if (!sqlite3_get_autocommit(self->db)) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000460 pysqlite_do_all_statements(self, ACTION_RESET, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000461
462 Py_BEGIN_ALLOW_THREADS
Aviv Palivoda86a67052017-03-03 12:58:17 +0200463 rc = SQLITE3_PREPARE(self->db, "ROLLBACK", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000464 Py_END_ALLOW_THREADS
465 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000466 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000467 goto error;
468 }
469
Benjamin Petersond7b03282008-09-13 15:58:53 +0000470 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300471 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000472 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000473 }
474
475 Py_BEGIN_ALLOW_THREADS
476 rc = sqlite3_finalize(statement);
477 Py_END_ALLOW_THREADS
478 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000479 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000480 }
481
482 }
483
484error:
485 if (PyErr_Occurred()) {
486 return NULL;
487 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200488 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000489 }
490}
491
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200492static int
493_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000494{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200495 if (py_val == Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000496 sqlite3_result_null(context);
Christian Heimes217cfd12007-12-02 14:31:20 +0000497 } else if (PyLong_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200498 sqlite_int64 value = _pysqlite_long_as_int64(py_val);
499 if (value == -1 && PyErr_Occurred())
500 return -1;
501 sqlite3_result_int64(context, value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000502 } else if (PyFloat_Check(py_val)) {
503 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
Guido van Rossumbae07c92007-10-08 02:46:15 +0000504 } else if (PyUnicode_Check(py_val)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200505 const char *str = PyUnicode_AsUTF8(py_val);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200506 if (str == NULL)
507 return -1;
508 sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000509 } else if (PyObject_CheckBuffer(py_val)) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200510 Py_buffer view;
511 if (PyObject_GetBuffer(py_val, &view, PyBUF_SIMPLE) != 0) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100512 PyErr_SetString(PyExc_ValueError,
513 "could not convert BLOB to buffer");
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200514 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000515 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200516 if (view.len > INT_MAX) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100517 PyErr_SetString(PyExc_OverflowError,
518 "BLOB longer than INT_MAX bytes");
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200519 PyBuffer_Release(&view);
Victor Stinner83ed42b2013-11-18 01:24:31 +0100520 return -1;
521 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200522 sqlite3_result_blob(context, view.buf, (int)view.len, SQLITE_TRANSIENT);
523 PyBuffer_Release(&view);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000524 } else {
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 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000528}
529
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000530PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000531{
532 PyObject* args;
533 int i;
534 sqlite3_value* cur_value;
535 PyObject* cur_py_value;
536 const char* val_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000537 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000538
539 args = PyTuple_New(argc);
540 if (!args) {
541 return NULL;
542 }
543
544 for (i = 0; i < argc; i++) {
545 cur_value = argv[i];
546 switch (sqlite3_value_type(argv[i])) {
547 case SQLITE_INTEGER:
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200548 cur_py_value = _pysqlite_long_from_int64(sqlite3_value_int64(cur_value));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000549 break;
550 case SQLITE_FLOAT:
551 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
552 break;
553 case SQLITE_TEXT:
554 val_str = (const char*)sqlite3_value_text(cur_value);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000555 cur_py_value = PyUnicode_FromString(val_str);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000556 /* TODO: have a way to show errors here */
557 if (!cur_py_value) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000559 Py_INCREF(Py_None);
560 cur_py_value = Py_None;
561 }
562 break;
563 case SQLITE_BLOB:
564 buflen = sqlite3_value_bytes(cur_value);
Christian Heimes72b710a2008-05-26 13:28:38 +0000565 cur_py_value = PyBytes_FromStringAndSize(
Guido van Rossumbae07c92007-10-08 02:46:15 +0000566 sqlite3_value_blob(cur_value), buflen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000567 break;
568 case SQLITE_NULL:
569 default:
570 Py_INCREF(Py_None);
571 cur_py_value = Py_None;
572 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000573
574 if (!cur_py_value) {
575 Py_DECREF(args);
576 return NULL;
577 }
578
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000579 PyTuple_SetItem(args, i, cur_py_value);
580
581 }
582
583 return args;
584}
585
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000586void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000587{
588 PyObject* args;
589 PyObject* py_func;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590 PyObject* py_retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200591 int ok;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000592
593 PyGILState_STATE threadstate;
594
595 threadstate = PyGILState_Ensure();
596
597 py_func = (PyObject*)sqlite3_user_data(context);
598
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000599 args = _pysqlite_build_py_params(context, argc, argv);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000600 if (args) {
601 py_retval = PyObject_CallObject(py_func, args);
602 Py_DECREF(args);
603 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000604
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200605 ok = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000606 if (py_retval) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200607 ok = _pysqlite_set_result(context, py_retval) == 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000608 Py_DECREF(py_retval);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200609 }
610 if (!ok) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000611 if (_enable_callback_tracebacks) {
612 PyErr_Print();
613 } else {
614 PyErr_Clear();
615 }
616 _sqlite3_result_error(context, "user-defined function raised exception", -1);
617 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000618
619 PyGILState_Release(threadstate);
620}
621
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000622static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000623{
624 PyObject* args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000625 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000626 PyObject* aggregate_class;
627 PyObject** aggregate_instance;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000628 PyObject* stepmethod = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000629
630 PyGILState_STATE threadstate;
631
632 threadstate = PyGILState_Ensure();
633
634 aggregate_class = (PyObject*)sqlite3_user_data(context);
635
636 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
637
Serhiy Storchaka0b3ec192017-03-23 17:53:47 +0200638 if (*aggregate_instance == NULL) {
Victor Stinner070c4d72016-12-09 12:29:18 +0100639 *aggregate_instance = _PyObject_CallNoArg(aggregate_class);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000640
Thomas Wouters477c8d52006-05-27 19:21:47 +0000641 if (PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000642 *aggregate_instance = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000643 if (_enable_callback_tracebacks) {
644 PyErr_Print();
645 } else {
646 PyErr_Clear();
647 }
648 _sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000649 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000650 }
651 }
652
653 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000654 if (!stepmethod) {
655 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000656 }
657
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000658 args = _pysqlite_build_py_params(context, argc, params);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000659 if (!args) {
660 goto error;
661 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000662
663 function_result = PyObject_CallObject(stepmethod, args);
664 Py_DECREF(args);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000665
Thomas Wouters477c8d52006-05-27 19:21:47 +0000666 if (!function_result) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000667 if (_enable_callback_tracebacks) {
668 PyErr_Print();
669 } else {
670 PyErr_Clear();
671 }
672 _sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000673 }
674
Thomas Wouters477c8d52006-05-27 19:21:47 +0000675error:
676 Py_XDECREF(stepmethod);
677 Py_XDECREF(function_result);
678
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000679 PyGILState_Release(threadstate);
680}
681
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000682void _pysqlite_final_callback(sqlite3_context* context)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000683{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200684 PyObject* function_result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000685 PyObject** aggregate_instance;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200686 _Py_IDENTIFIER(finalize);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200687 int ok;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200688 PyObject *exception, *value, *tb;
Victor Stinnerffff7632013-08-02 01:48:10 +0200689 int restore;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000690
691 PyGILState_STATE threadstate;
692
693 threadstate = PyGILState_Ensure();
694
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000695 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
696 if (!*aggregate_instance) {
697 /* this branch is executed if there was an exception in the aggregate's
698 * __init__ */
699
Thomas Wouters477c8d52006-05-27 19:21:47 +0000700 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000701 }
702
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200703 /* Keep the exception (if any) of the last call to step() */
704 PyErr_Fetch(&exception, &value, &tb);
Victor Stinnerffff7632013-08-02 01:48:10 +0200705 restore = 1;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200706
Victor Stinner3466bde2016-09-05 18:16:01 -0700707 function_result = _PyObject_CallMethodId(*aggregate_instance, &PyId_finalize, NULL);
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200708
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200709 Py_DECREF(*aggregate_instance);
710
711 ok = 0;
712 if (function_result) {
713 ok = _pysqlite_set_result(context, function_result) == 0;
714 Py_DECREF(function_result);
715 }
716 if (!ok) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000717 if (_enable_callback_tracebacks) {
718 PyErr_Print();
719 } else {
720 PyErr_Clear();
721 }
722 _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
Victor Stinnerffff7632013-08-02 01:48:10 +0200723#if SQLITE_VERSION_NUMBER < 3003003
724 /* with old SQLite versions, _sqlite3_result_error() sets a new Python
725 exception, so don't restore the previous exception */
726 restore = 0;
727#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000728 }
729
Victor Stinnerffff7632013-08-02 01:48:10 +0200730 if (restore) {
731 /* Restore the exception (if any) of the last call to step(),
732 but clear also the current exception if finalize() failed */
733 PyErr_Restore(exception, value, tb);
734 }
Victor Stinner3a857322013-07-22 08:34:32 +0200735
Thomas Wouters477c8d52006-05-27 19:21:47 +0000736error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000737 PyGILState_Release(threadstate);
738}
739
Gerhard Häringf9cee222010-03-05 15:20:03 +0000740static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741{
742 PyObject* new_list;
743 PyObject* weakref;
744 int i;
745
746 /* we only need to do this once in a while */
747 if (self->created_statements++ < 200) {
748 return;
749 }
750
751 self->created_statements = 0;
752
753 new_list = PyList_New(0);
754 if (!new_list) {
755 return;
756 }
757
758 for (i = 0; i < PyList_Size(self->statements); i++) {
759 weakref = PyList_GetItem(self->statements, i);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000760 if (PyWeakref_GetObject(weakref) != Py_None) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761 if (PyList_Append(new_list, weakref) != 0) {
762 Py_DECREF(new_list);
763 return;
764 }
765 }
766 }
767
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300768 Py_SETREF(self->statements, new_list);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000769}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000770
Gerhard Häringf9cee222010-03-05 15:20:03 +0000771static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
772{
773 PyObject* new_list;
774 PyObject* weakref;
775 int i;
776
777 /* we only need to do this once in a while */
778 if (self->created_cursors++ < 200) {
779 return;
780 }
781
782 self->created_cursors = 0;
783
784 new_list = PyList_New(0);
785 if (!new_list) {
786 return;
787 }
788
789 for (i = 0; i < PyList_Size(self->cursors); i++) {
790 weakref = PyList_GetItem(self->cursors, i);
791 if (PyWeakref_GetObject(weakref) != Py_None) {
792 if (PyList_Append(new_list, weakref) != 0) {
793 Py_DECREF(new_list);
794 return;
795 }
796 }
797 }
798
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300799 Py_SETREF(self->cursors, new_list);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000800}
801
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000802PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000803{
804 static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
805
806 PyObject* func;
807 char* name;
808 int narg;
809 int rc;
810
Gerhard Häringf9cee222010-03-05 15:20:03 +0000811 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
812 return NULL;
813 }
814
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000815 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
816 &name, &narg, &func))
817 {
818 return NULL;
819 }
820
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000821 rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000822
Thomas Wouters477c8d52006-05-27 19:21:47 +0000823 if (rc != SQLITE_OK) {
824 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000825 PyErr_SetString(pysqlite_OperationalError, "Error creating function");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000826 return NULL;
827 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000828 if (PyDict_SetItem(self->function_pinboard, func, Py_None) == -1)
829 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000830
Berker Peksagfe21de92016-04-09 07:34:39 +0300831 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000832 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000833}
834
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000835PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000836{
837 PyObject* aggregate_class;
838
839 int n_arg;
840 char* name;
841 static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
842 int rc;
843
Gerhard Häringf9cee222010-03-05 15:20:03 +0000844 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
845 return NULL;
846 }
847
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
849 kwlist, &name, &n_arg, &aggregate_class)) {
850 return NULL;
851 }
852
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000853 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 +0000854 if (rc != SQLITE_OK) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000855 /* 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 aggregate");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857 return NULL;
858 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000859 if (PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None) == -1)
860 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000861
Berker Peksagfe21de92016-04-09 07:34:39 +0300862 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000863 }
864}
865
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000866static 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 +0000867{
868 PyObject *ret;
869 int rc;
870 PyGILState_STATE gilstate;
871
872 gilstate = PyGILState_Ensure();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000873
Victor Stinnerd4095d92013-07-26 22:23:33 +0200874 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000875
Victor Stinnerd4095d92013-07-26 22:23:33 +0200876 if (ret == NULL) {
877 if (_enable_callback_tracebacks)
878 PyErr_Print();
879 else
880 PyErr_Clear();
Victor Stinner41801f52013-07-21 13:05:38 +0200881
Victor Stinnerd4095d92013-07-26 22:23:33 +0200882 rc = SQLITE_DENY;
Victor Stinner41801f52013-07-21 13:05:38 +0200883 }
884 else {
Victor Stinnerd4095d92013-07-26 22:23:33 +0200885 if (PyLong_Check(ret)) {
886 rc = _PyLong_AsInt(ret);
887 if (rc == -1 && PyErr_Occurred()) {
888 if (_enable_callback_tracebacks)
889 PyErr_Print();
890 else
891 PyErr_Clear();
892 rc = SQLITE_DENY;
893 }
894 }
895 else {
896 rc = SQLITE_DENY;
897 }
898 Py_DECREF(ret);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000899 }
900
901 PyGILState_Release(gilstate);
902 return rc;
903}
904
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000905static int _progress_handler(void* user_arg)
906{
907 int rc;
908 PyObject *ret;
909 PyGILState_STATE gilstate;
910
911 gilstate = PyGILState_Ensure();
Victor Stinner070c4d72016-12-09 12:29:18 +0100912 ret = _PyObject_CallNoArg((PyObject*)user_arg);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000913
914 if (!ret) {
915 if (_enable_callback_tracebacks) {
916 PyErr_Print();
917 } else {
918 PyErr_Clear();
919 }
920
Mark Dickinson934896d2009-02-21 20:59:32 +0000921 /* abort query if error occurred */
Victor Stinner86999502010-05-19 01:27:23 +0000922 rc = 1;
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000923 } else {
924 rc = (int)PyObject_IsTrue(ret);
925 Py_DECREF(ret);
926 }
927
928 PyGILState_Release(gilstate);
929 return rc;
930}
931
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200932static void _trace_callback(void* user_arg, const char* statement_string)
933{
934 PyObject *py_statement = NULL;
935 PyObject *ret = NULL;
936
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200937 PyGILState_STATE gilstate;
938
939 gilstate = PyGILState_Ensure();
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200940 py_statement = PyUnicode_DecodeUTF8(statement_string,
941 strlen(statement_string), "replace");
942 if (py_statement) {
943 ret = PyObject_CallFunctionObjArgs((PyObject*)user_arg, py_statement, NULL);
944 Py_DECREF(py_statement);
945 }
946
947 if (ret) {
948 Py_DECREF(ret);
949 } else {
950 if (_enable_callback_tracebacks) {
951 PyErr_Print();
952 } else {
953 PyErr_Clear();
954 }
955 }
956
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200957 PyGILState_Release(gilstate);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200958}
959
Gerhard Häringf9cee222010-03-05 15:20:03 +0000960static PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000961{
962 PyObject* authorizer_cb;
963
964 static char *kwlist[] = { "authorizer_callback", NULL };
965 int rc;
966
Gerhard Häringf9cee222010-03-05 15:20:03 +0000967 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
968 return NULL;
969 }
970
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000971 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
972 kwlist, &authorizer_cb)) {
973 return NULL;
974 }
975
976 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
977
978 if (rc != SQLITE_OK) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000979 PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000980 return NULL;
981 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000982 if (PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None) == -1)
983 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000984
Berker Peksagfe21de92016-04-09 07:34:39 +0300985 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000986 }
987}
988
Gerhard Häringf9cee222010-03-05 15:20:03 +0000989static PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000990{
991 PyObject* progress_handler;
992 int n;
993
994 static char *kwlist[] = { "progress_handler", "n", NULL };
995
Gerhard Häringf9cee222010-03-05 15:20:03 +0000996 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
997 return NULL;
998 }
999
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001000 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
1001 kwlist, &progress_handler, &n)) {
1002 return NULL;
1003 }
1004
1005 if (progress_handler == Py_None) {
1006 /* None clears the progress handler previously set */
1007 sqlite3_progress_handler(self->db, 0, 0, (void*)0);
1008 } else {
1009 sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
Gerhard Häringf9cee222010-03-05 15:20:03 +00001010 if (PyDict_SetItem(self->function_pinboard, progress_handler, Py_None) == -1)
1011 return NULL;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001012 }
1013
Berker Peksagfe21de92016-04-09 07:34:39 +03001014 Py_RETURN_NONE;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001015}
1016
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001017static PyObject* pysqlite_connection_set_trace_callback(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1018{
1019 PyObject* trace_callback;
1020
1021 static char *kwlist[] = { "trace_callback", NULL };
1022
1023 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1024 return NULL;
1025 }
1026
1027 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_trace_callback",
1028 kwlist, &trace_callback)) {
1029 return NULL;
1030 }
1031
1032 if (trace_callback == Py_None) {
1033 /* None clears the trace callback previously set */
1034 sqlite3_trace(self->db, 0, (void*)0);
1035 } else {
1036 if (PyDict_SetItem(self->function_pinboard, trace_callback, Py_None) == -1)
1037 return NULL;
1038 sqlite3_trace(self->db, _trace_callback, trace_callback);
1039 }
1040
Berker Peksagfe21de92016-04-09 07:34:39 +03001041 Py_RETURN_NONE;
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001042}
1043
Gerhard Häringf9cee222010-03-05 15:20:03 +00001044#ifdef HAVE_LOAD_EXTENSION
1045static PyObject* pysqlite_enable_load_extension(pysqlite_Connection* self, PyObject* args)
1046{
1047 int rc;
1048 int onoff;
1049
1050 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1051 return NULL;
1052 }
1053
1054 if (!PyArg_ParseTuple(args, "i", &onoff)) {
1055 return NULL;
1056 }
1057
1058 rc = sqlite3_enable_load_extension(self->db, onoff);
1059
1060 if (rc != SQLITE_OK) {
1061 PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
1062 return NULL;
1063 } else {
Berker Peksagfe21de92016-04-09 07:34:39 +03001064 Py_RETURN_NONE;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001065 }
1066}
1067
1068static PyObject* pysqlite_load_extension(pysqlite_Connection* self, PyObject* args)
1069{
1070 int rc;
1071 char* extension_name;
1072 char* errmsg;
1073
1074 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1075 return NULL;
1076 }
1077
1078 if (!PyArg_ParseTuple(args, "s", &extension_name)) {
1079 return NULL;
1080 }
1081
1082 rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1083 if (rc != 0) {
1084 PyErr_SetString(pysqlite_OperationalError, errmsg);
1085 return NULL;
1086 } else {
Berker Peksagfe21de92016-04-09 07:34:39 +03001087 Py_RETURN_NONE;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001088 }
1089}
1090#endif
1091
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001092int pysqlite_check_thread(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001093{
1094 if (self->check_same_thread) {
1095 if (PyThread_get_thread_ident() != self->thread_ident) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001096 PyErr_Format(pysqlite_ProgrammingError,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001097 "SQLite objects created in a thread can only be used in that same thread."
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001098 "The object was created in thread id %lu and this is thread id %lu",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001099 self->thread_ident, PyThread_get_thread_ident());
1100 return 0;
1101 }
1102
1103 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001104 return 1;
1105}
1106
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001107static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001108{
1109 Py_INCREF(self->isolation_level);
1110 return self->isolation_level;
1111}
1112
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001113static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001114{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001115 if (!pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001116 return NULL;
1117 } else {
1118 return Py_BuildValue("i", sqlite3_total_changes(self->db));
1119 }
1120}
1121
Berker Peksag59da4b32016-09-12 07:16:43 +03001122static PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
1123{
1124 if (!pysqlite_check_connection(self)) {
1125 return NULL;
1126 }
1127 if (!sqlite3_get_autocommit(self->db)) {
1128 Py_RETURN_TRUE;
1129 }
1130 Py_RETURN_FALSE;
1131}
1132
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001133static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001134{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001135 if (isolation_level == Py_None) {
Serhiy Storchaka28914922016-09-01 22:18:03 +03001136 PyObject *res = pysqlite_connection_commit(self, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001137 if (!res) {
1138 return -1;
1139 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001140 Py_DECREF(res);
1141
Serhiy Storchaka28914922016-09-01 22:18:03 +03001142 self->begin_statement = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001143 } else {
Serhiy Storchaka28914922016-09-01 22:18:03 +03001144 const char * const *candidate;
1145 PyObject *uppercase_level;
1146 _Py_IDENTIFIER(upper);
Neal Norwitzefee9f52007-10-27 02:50:52 +00001147
Serhiy Storchaka28914922016-09-01 22:18:03 +03001148 if (!PyUnicode_Check(isolation_level)) {
1149 PyErr_Format(PyExc_TypeError,
1150 "isolation_level must be a string or None, not %.100s",
1151 Py_TYPE(isolation_level)->tp_name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001152 return -1;
1153 }
1154
Serhiy Storchaka28914922016-09-01 22:18:03 +03001155 uppercase_level = _PyObject_CallMethodIdObjArgs(
1156 (PyObject *)&PyUnicode_Type, &PyId_upper,
1157 isolation_level, NULL);
1158 if (!uppercase_level) {
Georg Brandl3dbca812008-07-23 16:10:53 +00001159 return -1;
1160 }
Serhiy Storchaka28914922016-09-01 22:18:03 +03001161 for (candidate = begin_statements; *candidate; candidate++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001162 if (_PyUnicode_EqualToASCIIString(uppercase_level, *candidate + 6))
Serhiy Storchaka28914922016-09-01 22:18:03 +03001163 break;
1164 }
1165 Py_DECREF(uppercase_level);
1166 if (!*candidate) {
1167 PyErr_SetString(PyExc_ValueError,
1168 "invalid value for isolation_level");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001169 return -1;
1170 }
Serhiy Storchaka28914922016-09-01 22:18:03 +03001171 self->begin_statement = *candidate;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001172 }
1173
Serhiy Storchaka28914922016-09-01 22:18:03 +03001174 Py_INCREF(isolation_level);
1175 Py_XSETREF(self->isolation_level, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001176 return 0;
1177}
1178
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001179PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001180{
1181 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001182 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001183 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001184 int rc;
1185
Gerhard Häringf9cee222010-03-05 15:20:03 +00001186 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1187 return NULL;
1188 }
1189
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001190 if (!_PyArg_NoKeywords(MODULE_NAME ".Connection", kwargs))
Larry Hastings3b12e952015-05-08 07:45:10 -07001191 return NULL;
1192
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001193 if (!PyArg_ParseTuple(args, "O", &sql))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001194 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001195
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001196 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001197
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001198 statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001199 if (!statement) {
1200 return NULL;
1201 }
1202
Victor Stinner0201f442010-03-13 03:28:34 +00001203 statement->db = NULL;
1204 statement->st = NULL;
1205 statement->sql = NULL;
1206 statement->in_use = 0;
1207 statement->in_weakreflist = NULL;
1208
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001209 rc = pysqlite_statement_create(statement, self, sql);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001210 if (rc != SQLITE_OK) {
1211 if (rc == PYSQLITE_TOO_MUCH_SQL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001212 PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001213 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
Serhiy Storchaka42d67af2014-09-11 13:29:05 +03001214 if (PyErr_ExceptionMatches(PyExc_TypeError))
1215 PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001216 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001217 (void)pysqlite_statement_reset(statement);
1218 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001219 }
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001220 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001221 }
1222
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001223 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
1224 if (weakref == NULL)
1225 goto error;
1226 if (PyList_Append(self->statements, weakref) != 0) {
1227 Py_DECREF(weakref);
1228 goto error;
1229 }
1230 Py_DECREF(weakref);
1231
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001232 return (PyObject*)statement;
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001233
1234error:
1235 Py_DECREF(statement);
1236 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001237}
1238
Larry Hastings01b08832015-05-08 07:37:49 -07001239PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001240{
1241 PyObject* cursor = 0;
1242 PyObject* result = 0;
1243 PyObject* method = 0;
1244
Victor Stinner3466bde2016-09-05 18:16:01 -07001245 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001246 if (!cursor) {
1247 goto error;
1248 }
1249
1250 method = PyObject_GetAttrString(cursor, "execute");
1251 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001252 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001253 goto error;
1254 }
1255
1256 result = PyObject_CallObject(method, args);
1257 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001258 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001259 }
1260
1261error:
1262 Py_XDECREF(result);
1263 Py_XDECREF(method);
1264
1265 return cursor;
1266}
1267
Larry Hastings01b08832015-05-08 07:37:49 -07001268PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001269{
1270 PyObject* cursor = 0;
1271 PyObject* result = 0;
1272 PyObject* method = 0;
1273
Victor Stinner3466bde2016-09-05 18:16:01 -07001274 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001275 if (!cursor) {
1276 goto error;
1277 }
1278
1279 method = PyObject_GetAttrString(cursor, "executemany");
1280 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001281 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001282 goto error;
1283 }
1284
1285 result = PyObject_CallObject(method, args);
1286 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001287 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001288 }
1289
1290error:
1291 Py_XDECREF(result);
1292 Py_XDECREF(method);
1293
1294 return cursor;
1295}
1296
Larry Hastings01b08832015-05-08 07:37:49 -07001297PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001298{
1299 PyObject* cursor = 0;
1300 PyObject* result = 0;
1301 PyObject* method = 0;
1302
Victor Stinner3466bde2016-09-05 18:16:01 -07001303 cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001304 if (!cursor) {
1305 goto error;
1306 }
1307
1308 method = PyObject_GetAttrString(cursor, "executescript");
1309 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001310 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001311 goto error;
1312 }
1313
1314 result = PyObject_CallObject(method, args);
1315 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001316 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001317 }
1318
1319error:
1320 Py_XDECREF(result);
1321 Py_XDECREF(method);
1322
1323 return cursor;
1324}
1325
1326/* ------------------------- COLLATION CODE ------------------------ */
1327
1328static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001329pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001330 void* context,
1331 int text1_length, const void* text1_data,
1332 int text2_length, const void* text2_data)
1333{
1334 PyObject* callback = (PyObject*)context;
1335 PyObject* string1 = 0;
1336 PyObject* string2 = 0;
1337 PyGILState_STATE gilstate;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001338 PyObject* retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001339 long longval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001340 int result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001341 gilstate = PyGILState_Ensure();
1342
1343 if (PyErr_Occurred()) {
1344 goto finally;
1345 }
1346
Guido van Rossum98297ee2007-11-06 21:34:58 +00001347 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1348 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001349
1350 if (!string1 || !string2) {
1351 goto finally; /* failed to allocate strings */
1352 }
1353
1354 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1355
1356 if (!retval) {
1357 /* execution failed */
1358 goto finally;
1359 }
1360
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001361 longval = PyLong_AsLongAndOverflow(retval, &result);
1362 if (longval == -1 && PyErr_Occurred()) {
1363 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001364 result = 0;
1365 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001366 else if (!result) {
1367 if (longval > 0)
1368 result = 1;
1369 else if (longval < 0)
1370 result = -1;
1371 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001372
1373finally:
1374 Py_XDECREF(string1);
1375 Py_XDECREF(string2);
1376 Py_XDECREF(retval);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001377 PyGILState_Release(gilstate);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001378 return result;
1379}
1380
1381static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001382pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001383{
1384 PyObject* retval = NULL;
1385
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001386 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001387 goto finally;
1388 }
1389
1390 sqlite3_interrupt(self->db);
1391
1392 Py_INCREF(Py_None);
1393 retval = Py_None;
1394
1395finally:
1396 return retval;
1397}
1398
Christian Heimesbbe741d2008-03-28 10:53:29 +00001399/* Function author: Paul Kippes <kippesp@gmail.com>
1400 * Class method of Connection to call the Python function _iterdump
1401 * of the sqlite3 module.
1402 */
1403static PyObject *
1404pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1405{
1406 PyObject* retval = NULL;
1407 PyObject* module = NULL;
1408 PyObject* module_dict;
1409 PyObject* pyfn_iterdump;
1410
1411 if (!pysqlite_check_connection(self)) {
1412 goto finally;
1413 }
1414
1415 module = PyImport_ImportModule(MODULE_NAME ".dump");
1416 if (!module) {
1417 goto finally;
1418 }
1419
1420 module_dict = PyModule_GetDict(module);
1421 if (!module_dict) {
1422 goto finally;
1423 }
1424
1425 pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
1426 if (!pyfn_iterdump) {
1427 PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
1428 goto finally;
1429 }
1430
1431 args = PyTuple_New(1);
1432 if (!args) {
1433 goto finally;
1434 }
1435 Py_INCREF(self);
1436 PyTuple_SetItem(args, 0, (PyObject*)self);
1437 retval = PyObject_CallObject(pyfn_iterdump, args);
1438
1439finally:
1440 Py_XDECREF(args);
1441 Py_XDECREF(module);
1442 return retval;
1443}
1444
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001445static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001446pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001447{
1448 PyObject* callable;
1449 PyObject* uppercase_name = 0;
1450 PyObject* name;
1451 PyObject* retval;
Victor Stinner35466c52010-04-22 11:23:23 +00001452 Py_ssize_t i, len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001453 _Py_IDENTIFIER(upper);
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001454 const char *uppercase_name_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001455 int rc;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456 unsigned int kind;
1457 void *data;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001458
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001459 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001460 goto finally;
1461 }
1462
Serhiy Storchaka407ac472016-09-27 00:10:03 +03001463 if (!PyArg_ParseTuple(args, "UO:create_collation(name, callback)",
1464 &name, &callable)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001465 goto finally;
1466 }
1467
Serhiy Storchaka407ac472016-09-27 00:10:03 +03001468 uppercase_name = _PyObject_CallMethodIdObjArgs((PyObject *)&PyUnicode_Type,
1469 &PyId_upper, name, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001470 if (!uppercase_name) {
1471 goto finally;
1472 }
1473
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474 if (PyUnicode_READY(uppercase_name))
1475 goto finally;
1476 len = PyUnicode_GET_LENGTH(uppercase_name);
1477 kind = PyUnicode_KIND(uppercase_name);
1478 data = PyUnicode_DATA(uppercase_name);
1479 for (i=0; i<len; i++) {
1480 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1481 if ((ch >= '0' && ch <= '9')
1482 || (ch >= 'A' && ch <= 'Z')
1483 || (ch == '_'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001484 {
Victor Stinner35466c52010-04-22 11:23:23 +00001485 continue;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001486 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001487 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001488 goto finally;
1489 }
1490 }
1491
Serhiy Storchaka06515832016-11-20 09:13:07 +02001492 uppercase_name_str = PyUnicode_AsUTF8(uppercase_name);
Victor Stinner35466c52010-04-22 11:23:23 +00001493 if (!uppercase_name_str)
1494 goto finally;
1495
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001496 if (callable != Py_None && !PyCallable_Check(callable)) {
1497 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1498 goto finally;
1499 }
1500
1501 if (callable != Py_None) {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001502 if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
1503 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001504 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001505 if (PyDict_DelItem(self->collations, uppercase_name) == -1)
1506 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001507 }
1508
1509 rc = sqlite3_create_collation(self->db,
Victor Stinner35466c52010-04-22 11:23:23 +00001510 uppercase_name_str,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001511 SQLITE_UTF8,
1512 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001513 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001514 if (rc != SQLITE_OK) {
1515 PyDict_DelItem(self->collations, uppercase_name);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001516 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001517 goto finally;
1518 }
1519
1520finally:
1521 Py_XDECREF(uppercase_name);
1522
1523 if (PyErr_Occurred()) {
1524 retval = NULL;
1525 } else {
1526 Py_INCREF(Py_None);
1527 retval = Py_None;
1528 }
1529
1530 return retval;
1531}
1532
Christian Heimesbbe741d2008-03-28 10:53:29 +00001533/* Called when the connection is used as a context manager. Returns itself as a
1534 * convenience to the caller. */
1535static PyObject *
1536pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1537{
1538 Py_INCREF(self);
1539 return (PyObject*)self;
1540}
1541
1542/** Called when the connection is used as a context manager. If there was any
1543 * exception, a rollback takes place; otherwise we commit. */
1544static PyObject *
1545pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1546{
1547 PyObject* exc_type, *exc_value, *exc_tb;
1548 char* method_name;
1549 PyObject* result;
1550
1551 if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1552 return NULL;
1553 }
1554
1555 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1556 method_name = "commit";
1557 } else {
1558 method_name = "rollback";
1559 }
1560
Victor Stinner3466bde2016-09-05 18:16:01 -07001561 result = PyObject_CallMethod((PyObject*)self, method_name, NULL);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001562 if (!result) {
1563 return NULL;
1564 }
1565 Py_DECREF(result);
1566
1567 Py_RETURN_FALSE;
1568}
1569
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001570static const char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001571PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001572
1573static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001574 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1575 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Berker Peksag59da4b32016-09-12 07:16:43 +03001576 {"in_transaction", (getter)pysqlite_connection_get_in_transaction, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001577 {NULL}
1578};
1579
1580static PyMethodDef connection_methods[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001581 {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001582 PyDoc_STR("Return a cursor for the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001583 {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001584 PyDoc_STR("Closes the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001585 {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001586 PyDoc_STR("Commit the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001587 {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001588 PyDoc_STR("Roll back the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001589 {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001590 PyDoc_STR("Creates a new function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001591 {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001592 PyDoc_STR("Creates a new aggregate. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001593 {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001594 PyDoc_STR("Sets authorizer callback. Non-standard.")},
Gerhard Häringf9cee222010-03-05 15:20:03 +00001595 #ifdef HAVE_LOAD_EXTENSION
1596 {"enable_load_extension", (PyCFunction)pysqlite_enable_load_extension, METH_VARARGS,
1597 PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
1598 {"load_extension", (PyCFunction)pysqlite_load_extension, METH_VARARGS,
1599 PyDoc_STR("Load SQLite extension module. Non-standard.")},
1600 #endif
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001601 {"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
1602 PyDoc_STR("Sets progress handler callback. Non-standard.")},
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001603 {"set_trace_callback", (PyCFunction)pysqlite_connection_set_trace_callback, METH_VARARGS|METH_KEYWORDS,
1604 PyDoc_STR("Sets a trace callback called for each SQL statement (passed as unicode). Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001605 {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001606 PyDoc_STR("Executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001607 {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001608 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001609 {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001610 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001611 {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001612 PyDoc_STR("Creates a collation function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001613 {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001614 PyDoc_STR("Abort any pending database operation. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001615 {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
Benjamin Petersond7b03282008-09-13 15:58:53 +00001616 PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001617 {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1618 PyDoc_STR("For context manager. Non-standard.")},
1619 {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1620 PyDoc_STR("For context manager. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001621 {NULL, NULL}
1622};
1623
1624static struct PyMemberDef connection_members[] =
1625{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001626 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1627 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1628 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1629 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1630 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1631 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1632 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1633 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1634 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1635 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001636 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1637 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001638 {NULL}
1639};
1640
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001641PyTypeObject pysqlite_ConnectionType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001642 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001643 MODULE_NAME ".Connection", /* tp_name */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001644 sizeof(pysqlite_Connection), /* tp_basicsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001645 0, /* tp_itemsize */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001646 (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001647 0, /* tp_print */
1648 0, /* tp_getattr */
1649 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001650 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001651 0, /* tp_repr */
1652 0, /* tp_as_number */
1653 0, /* tp_as_sequence */
1654 0, /* tp_as_mapping */
1655 0, /* tp_hash */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001656 (ternaryfunc)pysqlite_connection_call, /* tp_call */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001657 0, /* tp_str */
1658 0, /* tp_getattro */
1659 0, /* tp_setattro */
1660 0, /* tp_as_buffer */
1661 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1662 connection_doc, /* tp_doc */
1663 0, /* tp_traverse */
1664 0, /* tp_clear */
1665 0, /* tp_richcompare */
1666 0, /* tp_weaklistoffset */
1667 0, /* tp_iter */
1668 0, /* tp_iternext */
1669 connection_methods, /* tp_methods */
1670 connection_members, /* tp_members */
1671 connection_getset, /* tp_getset */
1672 0, /* tp_base */
1673 0, /* tp_dict */
1674 0, /* tp_descr_get */
1675 0, /* tp_descr_set */
1676 0, /* tp_dictoffset */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001677 (initproc)pysqlite_connection_init, /* tp_init */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001678 0, /* tp_alloc */
1679 0, /* tp_new */
1680 0 /* tp_free */
1681};
1682
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001683extern int pysqlite_connection_setup_types(void)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001684{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001685 pysqlite_ConnectionType.tp_new = PyType_GenericNew;
1686 return PyType_Ready(&pysqlite_ConnectionType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001687}