blob: 69203f85e05553789cc3f9df4815f90bb44a99ed [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"
Victor Stinner4a21e572020-04-15 02:35:41 +020026#include "structmember.h" // PyMemberDef
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
Gerhard Häringe7ea7452008-03-29 00:45:29 +000033#define ACTION_FINALIZE 1
34#define ACTION_RESET 2
35
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +020036#if SQLITE_VERSION_NUMBER >= 3014000
37#define HAVE_TRACE_V2
38#endif
39
Martin v. Löwise75fc142013-11-07 18:46:53 +010040_Py_IDENTIFIER(cursor);
41
Serhiy Storchaka28914922016-09-01 22:18:03 +030042static const char * const begin_statements[] = {
43 "BEGIN ",
44 "BEGIN DEFERRED",
45 "BEGIN IMMEDIATE",
46 "BEGIN EXCLUSIVE",
47 NULL
48};
49
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +020050static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored));
Gerhard Häringf9cee222010-03-05 15:20:03 +000051static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052
Thomas Wouters0e3f5912006-08-11 14:57:12 +000053
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000054int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000055{
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010056 static char *kwlist[] = {
57 "database", "timeout", "detect_types", "isolation_level",
58 "check_same_thread", "factory", "cached_statements", "uri",
59 NULL
60 };
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +030062 const char* database;
Anders Lorentsena22a1272017-11-07 01:47:43 +010063 PyObject* database_obj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000064 int detect_types = 0;
65 PyObject* isolation_level = NULL;
66 PyObject* factory = NULL;
67 int check_same_thread = 1;
68 int cached_statements = 100;
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010069 int uri = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000070 double timeout = 5.0;
71 int rc;
72
Anders Lorentsena22a1272017-11-07 01:47:43 +010073 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|diOiOip", kwlist,
74 PyUnicode_FSConverter, &database_obj, &timeout, &detect_types,
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010075 &isolation_level, &check_same_thread,
76 &factory, &cached_statements, &uri))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000077 {
Gerhard Häringe7ea7452008-03-29 00:45:29 +000078 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079 }
80
Anders Lorentsena22a1272017-11-07 01:47:43 +010081 database = PyBytes_AsString(database_obj);
82
Gerhard Häringf9cee222010-03-05 15:20:03 +000083 self->initialized = 1;
84
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000085 self->begin_statement = NULL;
86
Oren Milman93c5a5d2017-10-10 22:27:46 +030087 Py_CLEAR(self->statement_cache);
88 Py_CLEAR(self->statements);
89 Py_CLEAR(self->cursors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000090
91 Py_INCREF(Py_None);
Oren Milman93c5a5d2017-10-10 22:27:46 +030092 Py_XSETREF(self->row_factory, Py_None);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000093
94 Py_INCREF(&PyUnicode_Type);
Oren Milman93c5a5d2017-10-10 22:27:46 +030095 Py_XSETREF(self->text_factory, (PyObject*)&PyUnicode_Type);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000096
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010097#ifdef SQLITE_OPEN_URI
98 Py_BEGIN_ALLOW_THREADS
99 rc = sqlite3_open_v2(database, &self->db,
100 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
101 (uri ? SQLITE_OPEN_URI : 0), NULL);
102#else
103 if (uri) {
104 PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
105 return -1;
106 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000107 Py_BEGIN_ALLOW_THREADS
Aviv Palivoda86a67052017-03-03 12:58:17 +0200108 /* No need to use sqlite3_open_v2 as sqlite3_open(filename, db) is the
109 same as sqlite3_open_v2(filename, db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL). */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000110 rc = sqlite3_open(database, &self->db);
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100111#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000112 Py_END_ALLOW_THREADS
113
Anders Lorentsena22a1272017-11-07 01:47:43 +0100114 Py_DECREF(database_obj);
115
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000116 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000117 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118 return -1;
119 }
120
121 if (!isolation_level) {
Neal Norwitzefee9f52007-10-27 02:50:52 +0000122 isolation_level = PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123 if (!isolation_level) {
124 return -1;
125 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000126 } else {
127 Py_INCREF(isolation_level);
128 }
Oren Milman93c5a5d2017-10-10 22:27:46 +0300129 Py_CLEAR(self->isolation_level);
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200130 if (pysqlite_connection_set_isolation_level(self, isolation_level, NULL) < 0) {
Victor Stinnercb1f74e2013-12-19 16:38:03 +0100131 Py_DECREF(isolation_level);
132 return -1;
133 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000134 Py_DECREF(isolation_level);
135
Erlend Egeberg Aaslanda937ab42020-09-27 14:14:50 +0200136 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)pysqlite_CacheType, "Oi", self, cached_statements);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000137 if (PyErr_Occurred()) {
138 return -1;
139 }
140
Gerhard Häringf9cee222010-03-05 15:20:03 +0000141 self->created_statements = 0;
142 self->created_cursors = 0;
143
144 /* Create lists of weak references to statements/cursors */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000145 self->statements = PyList_New(0);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000146 self->cursors = PyList_New(0);
147 if (!self->statements || !self->cursors) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000148 return -1;
149 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000150
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000151 /* By default, the Cache class INCREFs the factory in its initializer, and
152 * decrefs it in its deallocator method. Since this would create a circular
153 * reference here, we're breaking it by decrementing self, and telling the
154 * cache class to not decref the factory (self) in its deallocator.
155 */
156 self->statement_cache->decref_factory = 0;
157 Py_DECREF(self);
158
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000159 self->detect_types = detect_types;
160 self->timeout = timeout;
161 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000162 self->thread_ident = PyThread_get_thread_ident();
163 self->check_same_thread = check_same_thread;
164
gescheitb9a03762019-07-13 06:15:49 +0300165 self->function_pinboard_trace_callback = NULL;
166 self->function_pinboard_progress_handler = NULL;
167 self->function_pinboard_authorizer_cb = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000168
Oren Milman93c5a5d2017-10-10 22:27:46 +0300169 Py_XSETREF(self->collations, PyDict_New());
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000170 if (!self->collations) {
171 return -1;
172 }
173
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000174 self->Warning = pysqlite_Warning;
175 self->Error = pysqlite_Error;
176 self->InterfaceError = pysqlite_InterfaceError;
177 self->DatabaseError = pysqlite_DatabaseError;
178 self->DataError = pysqlite_DataError;
179 self->OperationalError = pysqlite_OperationalError;
180 self->IntegrityError = pysqlite_IntegrityError;
181 self->InternalError = pysqlite_InternalError;
182 self->ProgrammingError = pysqlite_ProgrammingError;
183 self->NotSupportedError = pysqlite_NotSupportedError;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184
185 return 0;
186}
187
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000188/* action in (ACTION_RESET, ACTION_FINALIZE) */
Gerhard Häringf9cee222010-03-05 15:20:03 +0000189void pysqlite_do_all_statements(pysqlite_Connection* self, int action, int reset_cursors)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000190{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000191 int i;
192 PyObject* weakref;
193 PyObject* statement;
Gerhard Häringf9cee222010-03-05 15:20:03 +0000194 pysqlite_Cursor* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000195
Thomas Wouters477c8d52006-05-27 19:21:47 +0000196 for (i = 0; i < PyList_Size(self->statements); i++) {
197 weakref = PyList_GetItem(self->statements, i);
198 statement = PyWeakref_GetObject(weakref);
199 if (statement != Py_None) {
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500200 Py_INCREF(statement);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000201 if (action == ACTION_RESET) {
202 (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
203 } else {
204 (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
205 }
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500206 Py_DECREF(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000207 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000208 }
Gerhard Häringf9cee222010-03-05 15:20:03 +0000209
210 if (reset_cursors) {
211 for (i = 0; i < PyList_Size(self->cursors); i++) {
212 weakref = PyList_GetItem(self->cursors, i);
213 cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
214 if ((PyObject*)cursor != Py_None) {
215 cursor->reset = 1;
216 }
217 }
218 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000219}
220
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000221void pysqlite_connection_dealloc(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000222{
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200223 PyTypeObject *tp = Py_TYPE(self);
224
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000225 Py_XDECREF(self->statement_cache);
226
227 /* Clean up if user has not called .close() explicitly. */
228 if (self->db) {
Aviv Palivoda86a67052017-03-03 12:58:17 +0200229 SQLITE3_CLOSE(self->db);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000230 }
231
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000232 Py_XDECREF(self->isolation_level);
gescheitb9a03762019-07-13 06:15:49 +0300233 Py_XDECREF(self->function_pinboard_trace_callback);
234 Py_XDECREF(self->function_pinboard_progress_handler);
235 Py_XDECREF(self->function_pinboard_authorizer_cb);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000236 Py_XDECREF(self->row_factory);
237 Py_XDECREF(self->text_factory);
238 Py_XDECREF(self->collations);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000239 Py_XDECREF(self->statements);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000240 Py_XDECREF(self->cursors);
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200241
242 tp->tp_free(self);
243 Py_DECREF(tp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000244}
245
Gerhard Häringf9cee222010-03-05 15:20:03 +0000246/*
247 * Registers a cursor with the connection.
248 *
249 * 0 => error; 1 => ok
250 */
251int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
252{
253 PyObject* weakref;
254
255 weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
256 if (!weakref) {
257 goto error;
258 }
259
260 if (PyList_Append(connection->cursors, weakref) != 0) {
261 Py_CLEAR(weakref);
262 goto error;
263 }
264
265 Py_DECREF(weakref);
266
267 return 1;
268error:
269 return 0;
270}
271
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000272PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000273{
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300274 static char *kwlist[] = {"factory", NULL};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000275 PyObject* factory = NULL;
276 PyObject* cursor;
277
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000278 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
279 &factory)) {
280 return NULL;
281 }
282
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000283 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000284 return NULL;
285 }
286
287 if (factory == NULL) {
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200288 factory = (PyObject*)pysqlite_CursorType;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000289 }
290
Petr Viktorinffd97532020-02-11 17:46:57 +0100291 cursor = PyObject_CallOneArg(factory, (PyObject *)self);
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300292 if (cursor == NULL)
293 return NULL;
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200294 if (!PyObject_TypeCheck(cursor, pysqlite_CursorType)) {
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300295 PyErr_Format(PyExc_TypeError,
296 "factory must return a cursor, not %.100s",
297 Py_TYPE(cursor)->tp_name);
298 Py_DECREF(cursor);
299 return NULL;
300 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000301
Gerhard Häringf9cee222010-03-05 15:20:03 +0000302 _pysqlite_drop_unused_cursor_references(self);
303
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000304 if (cursor && self->row_factory != Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000305 Py_INCREF(self->row_factory);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300306 Py_XSETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000307 }
308
309 return cursor;
310}
311
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000312PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000313{
314 int rc;
315
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000316 if (!pysqlite_check_thread(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000317 return NULL;
318 }
319
Gerhard Häringf9cee222010-03-05 15:20:03 +0000320 pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000321
322 if (self->db) {
Aviv Palivoda86a67052017-03-03 12:58:17 +0200323 rc = SQLITE3_CLOSE(self->db);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000324
325 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000326 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000327 return NULL;
328 } else {
329 self->db = NULL;
330 }
331 }
332
Berker Peksagfe21de92016-04-09 07:34:39 +0300333 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000334}
335
336/*
337 * Checks if a connection object is usable (i. e. not closed).
338 *
339 * 0 => error; 1 => ok
340 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000341int pysqlite_check_connection(pysqlite_Connection* con)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000342{
Gerhard Häringf9cee222010-03-05 15:20:03 +0000343 if (!con->initialized) {
344 PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
345 return 0;
346 }
347
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000348 if (!con->db) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000349 PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000350 return 0;
351 } else {
352 return 1;
353 }
354}
355
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000356PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000357{
358 int rc;
359 const char* tail;
360 sqlite3_stmt* statement;
361
362 Py_BEGIN_ALLOW_THREADS
Benjamin Peterson52526942017-09-20 07:36:18 -0700363 rc = sqlite3_prepare_v2(self->db, self->begin_statement, -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000364 Py_END_ALLOW_THREADS
365
366 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000367 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000368 goto error;
369 }
370
Benjamin Petersond7b03282008-09-13 15:58:53 +0000371 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300372 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000373 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000374 }
375
376 Py_BEGIN_ALLOW_THREADS
377 rc = sqlite3_finalize(statement);
378 Py_END_ALLOW_THREADS
379
380 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000381 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000382 }
383
384error:
385 if (PyErr_Occurred()) {
386 return NULL;
387 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200388 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000389 }
390}
391
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000392PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000393{
394 int rc;
395 const char* tail;
396 sqlite3_stmt* statement;
397
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000398 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000399 return NULL;
400 }
401
Berker Peksag59da4b32016-09-12 07:16:43 +0300402 if (!sqlite3_get_autocommit(self->db)) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000403
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000404 Py_BEGIN_ALLOW_THREADS
Benjamin Peterson52526942017-09-20 07:36:18 -0700405 rc = sqlite3_prepare_v2(self->db, "COMMIT", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000406 Py_END_ALLOW_THREADS
407 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000408 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000409 goto error;
410 }
411
Benjamin Petersond7b03282008-09-13 15:58:53 +0000412 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300413 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000414 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000415 }
416
417 Py_BEGIN_ALLOW_THREADS
418 rc = sqlite3_finalize(statement);
419 Py_END_ALLOW_THREADS
420 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000421 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000422 }
423
424 }
425
426error:
427 if (PyErr_Occurred()) {
428 return NULL;
429 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200430 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000431 }
432}
433
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000434PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000435{
436 int rc;
437 const char* tail;
438 sqlite3_stmt* statement;
439
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000440 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000441 return NULL;
442 }
443
Berker Peksag59da4b32016-09-12 07:16:43 +0300444 if (!sqlite3_get_autocommit(self->db)) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000445 pysqlite_do_all_statements(self, ACTION_RESET, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000446
447 Py_BEGIN_ALLOW_THREADS
Benjamin Peterson52526942017-09-20 07:36:18 -0700448 rc = sqlite3_prepare_v2(self->db, "ROLLBACK", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000449 Py_END_ALLOW_THREADS
450 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000451 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000452 goto error;
453 }
454
Benjamin Petersond7b03282008-09-13 15:58:53 +0000455 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300456 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000457 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000458 }
459
460 Py_BEGIN_ALLOW_THREADS
461 rc = sqlite3_finalize(statement);
462 Py_END_ALLOW_THREADS
463 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000464 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000465 }
466
467 }
468
469error:
470 if (PyErr_Occurred()) {
471 return NULL;
472 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200473 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000474 }
475}
476
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200477static int
478_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000479{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200480 if (py_val == Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000481 sqlite3_result_null(context);
Christian Heimes217cfd12007-12-02 14:31:20 +0000482 } else if (PyLong_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200483 sqlite_int64 value = _pysqlite_long_as_int64(py_val);
484 if (value == -1 && PyErr_Occurred())
485 return -1;
486 sqlite3_result_int64(context, value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000487 } else if (PyFloat_Check(py_val)) {
488 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
Guido van Rossumbae07c92007-10-08 02:46:15 +0000489 } else if (PyUnicode_Check(py_val)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200490 const char *str = PyUnicode_AsUTF8(py_val);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200491 if (str == NULL)
492 return -1;
493 sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000494 } else if (PyObject_CheckBuffer(py_val)) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200495 Py_buffer view;
496 if (PyObject_GetBuffer(py_val, &view, PyBUF_SIMPLE) != 0) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100497 PyErr_SetString(PyExc_ValueError,
498 "could not convert BLOB to buffer");
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200499 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000500 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200501 if (view.len > INT_MAX) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100502 PyErr_SetString(PyExc_OverflowError,
503 "BLOB longer than INT_MAX bytes");
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200504 PyBuffer_Release(&view);
Victor Stinner83ed42b2013-11-18 01:24:31 +0100505 return -1;
506 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200507 sqlite3_result_blob(context, view.buf, (int)view.len, SQLITE_TRANSIENT);
508 PyBuffer_Release(&view);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000509 } else {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200510 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000511 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200512 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000513}
514
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000515PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000516{
517 PyObject* args;
518 int i;
519 sqlite3_value* cur_value;
520 PyObject* cur_py_value;
521 const char* val_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000522 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000523
524 args = PyTuple_New(argc);
525 if (!args) {
526 return NULL;
527 }
528
529 for (i = 0; i < argc; i++) {
530 cur_value = argv[i];
531 switch (sqlite3_value_type(argv[i])) {
532 case SQLITE_INTEGER:
Sergey Fedoseevb6f5b9d2019-10-23 13:09:01 +0500533 cur_py_value = PyLong_FromLongLong(sqlite3_value_int64(cur_value));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000534 break;
535 case SQLITE_FLOAT:
536 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
537 break;
538 case SQLITE_TEXT:
539 val_str = (const char*)sqlite3_value_text(cur_value);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000540 cur_py_value = PyUnicode_FromString(val_str);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000541 /* TODO: have a way to show errors here */
542 if (!cur_py_value) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000544 Py_INCREF(Py_None);
545 cur_py_value = Py_None;
546 }
547 break;
548 case SQLITE_BLOB:
549 buflen = sqlite3_value_bytes(cur_value);
Christian Heimes72b710a2008-05-26 13:28:38 +0000550 cur_py_value = PyBytes_FromStringAndSize(
Guido van Rossumbae07c92007-10-08 02:46:15 +0000551 sqlite3_value_blob(cur_value), buflen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000552 break;
553 case SQLITE_NULL:
554 default:
555 Py_INCREF(Py_None);
556 cur_py_value = Py_None;
557 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558
559 if (!cur_py_value) {
560 Py_DECREF(args);
561 return NULL;
562 }
563
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000564 PyTuple_SetItem(args, i, cur_py_value);
565
566 }
567
568 return args;
569}
570
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000571void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000572{
573 PyObject* args;
574 PyObject* py_func;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000575 PyObject* py_retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200576 int ok;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000577
578 PyGILState_STATE threadstate;
579
580 threadstate = PyGILState_Ensure();
581
582 py_func = (PyObject*)sqlite3_user_data(context);
583
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000584 args = _pysqlite_build_py_params(context, argc, argv);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000585 if (args) {
586 py_retval = PyObject_CallObject(py_func, args);
587 Py_DECREF(args);
588 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000589
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200590 ok = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000591 if (py_retval) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200592 ok = _pysqlite_set_result(context, py_retval) == 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000593 Py_DECREF(py_retval);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200594 }
595 if (!ok) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700596 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000597 PyErr_Print();
598 } else {
599 PyErr_Clear();
600 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200601 sqlite3_result_error(context, "user-defined function raised exception", -1);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000602 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000603
604 PyGILState_Release(threadstate);
605}
606
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000607static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000608{
609 PyObject* args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000610 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000611 PyObject* aggregate_class;
612 PyObject** aggregate_instance;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000613 PyObject* stepmethod = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000614
615 PyGILState_STATE threadstate;
616
617 threadstate = PyGILState_Ensure();
618
619 aggregate_class = (PyObject*)sqlite3_user_data(context);
620
621 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
622
Serhiy Storchaka0b3ec192017-03-23 17:53:47 +0200623 if (*aggregate_instance == NULL) {
Victor Stinner070c4d72016-12-09 12:29:18 +0100624 *aggregate_instance = _PyObject_CallNoArg(aggregate_class);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000625
Thomas Wouters477c8d52006-05-27 19:21:47 +0000626 if (PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627 *aggregate_instance = 0;
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700628 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000629 PyErr_Print();
630 } else {
631 PyErr_Clear();
632 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200633 sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000634 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000635 }
636 }
637
638 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000639 if (!stepmethod) {
640 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000641 }
642
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000643 args = _pysqlite_build_py_params(context, argc, params);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000644 if (!args) {
645 goto error;
646 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000647
648 function_result = PyObject_CallObject(stepmethod, args);
649 Py_DECREF(args);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000650
Thomas Wouters477c8d52006-05-27 19:21:47 +0000651 if (!function_result) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700652 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653 PyErr_Print();
654 } else {
655 PyErr_Clear();
656 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200657 sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000658 }
659
Thomas Wouters477c8d52006-05-27 19:21:47 +0000660error:
661 Py_XDECREF(stepmethod);
662 Py_XDECREF(function_result);
663
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000664 PyGILState_Release(threadstate);
665}
666
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000667void _pysqlite_final_callback(sqlite3_context* context)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000668{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200669 PyObject* function_result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000670 PyObject** aggregate_instance;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200671 _Py_IDENTIFIER(finalize);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200672 int ok;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200673 PyObject *exception, *value, *tb;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000674
675 PyGILState_STATE threadstate;
676
677 threadstate = PyGILState_Ensure();
678
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000679 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
680 if (!*aggregate_instance) {
681 /* this branch is executed if there was an exception in the aggregate's
682 * __init__ */
683
Thomas Wouters477c8d52006-05-27 19:21:47 +0000684 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000685 }
686
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200687 /* Keep the exception (if any) of the last call to step() */
688 PyErr_Fetch(&exception, &value, &tb);
689
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200690 function_result = _PyObject_CallMethodIdNoArgs(*aggregate_instance, &PyId_finalize);
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200691
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200692 Py_DECREF(*aggregate_instance);
693
694 ok = 0;
695 if (function_result) {
696 ok = _pysqlite_set_result(context, function_result) == 0;
697 Py_DECREF(function_result);
698 }
699 if (!ok) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700700 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000701 PyErr_Print();
702 } else {
703 PyErr_Clear();
704 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200705 sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000706 }
707
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200708 /* Restore the exception (if any) of the last call to step(),
709 but clear also the current exception if finalize() failed */
710 PyErr_Restore(exception, value, tb);
Victor Stinner3a857322013-07-22 08:34:32 +0200711
Thomas Wouters477c8d52006-05-27 19:21:47 +0000712error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000713 PyGILState_Release(threadstate);
714}
715
Gerhard Häringf9cee222010-03-05 15:20:03 +0000716static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717{
718 PyObject* new_list;
719 PyObject* weakref;
720 int i;
721
722 /* we only need to do this once in a while */
723 if (self->created_statements++ < 200) {
724 return;
725 }
726
727 self->created_statements = 0;
728
729 new_list = PyList_New(0);
730 if (!new_list) {
731 return;
732 }
733
734 for (i = 0; i < PyList_Size(self->statements); i++) {
735 weakref = PyList_GetItem(self->statements, i);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000736 if (PyWeakref_GetObject(weakref) != Py_None) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000737 if (PyList_Append(new_list, weakref) != 0) {
738 Py_DECREF(new_list);
739 return;
740 }
741 }
742 }
743
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300744 Py_SETREF(self->statements, new_list);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000745}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000746
Gerhard Häringf9cee222010-03-05 15:20:03 +0000747static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
748{
749 PyObject* new_list;
750 PyObject* weakref;
751 int i;
752
753 /* we only need to do this once in a while */
754 if (self->created_cursors++ < 200) {
755 return;
756 }
757
758 self->created_cursors = 0;
759
760 new_list = PyList_New(0);
761 if (!new_list) {
762 return;
763 }
764
765 for (i = 0; i < PyList_Size(self->cursors); i++) {
766 weakref = PyList_GetItem(self->cursors, i);
767 if (PyWeakref_GetObject(weakref) != Py_None) {
768 if (PyList_Append(new_list, weakref) != 0) {
769 Py_DECREF(new_list);
770 return;
771 }
772 }
773 }
774
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300775 Py_SETREF(self->cursors, new_list);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000776}
777
gescheitb9a03762019-07-13 06:15:49 +0300778static void _destructor(void* args)
779{
780 Py_DECREF((PyObject*)args);
781}
782
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000783PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000784{
Sergey Fedoseev08308582018-07-08 12:09:20 +0500785 static char *kwlist[] = {"name", "narg", "func", "deterministic", NULL};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786
787 PyObject* func;
788 char* name;
789 int narg;
790 int rc;
Sergey Fedoseev08308582018-07-08 12:09:20 +0500791 int deterministic = 0;
792 int flags = SQLITE_UTF8;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000793
Gerhard Häringf9cee222010-03-05 15:20:03 +0000794 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
795 return NULL;
796 }
797
Sergey Fedoseev08308582018-07-08 12:09:20 +0500798 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO|$p", kwlist,
799 &name, &narg, &func, &deterministic))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000800 {
801 return NULL;
802 }
803
Sergey Fedoseev08308582018-07-08 12:09:20 +0500804 if (deterministic) {
805#if SQLITE_VERSION_NUMBER < 3008003
806 PyErr_SetString(pysqlite_NotSupportedError,
807 "deterministic=True requires SQLite 3.8.3 or higher");
808 return NULL;
809#else
810 if (sqlite3_libversion_number() < 3008003) {
811 PyErr_SetString(pysqlite_NotSupportedError,
812 "deterministic=True requires SQLite 3.8.3 or higher");
813 return NULL;
814 }
815 flags |= SQLITE_DETERMINISTIC;
816#endif
817 }
gescheitb9a03762019-07-13 06:15:49 +0300818 Py_INCREF(func);
819 rc = sqlite3_create_function_v2(self->db,
820 name,
821 narg,
822 flags,
823 (void*)func,
824 _pysqlite_func_callback,
825 NULL,
826 NULL,
827 &_destructor); // will decref func
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000828
Thomas Wouters477c8d52006-05-27 19:21:47 +0000829 if (rc != SQLITE_OK) {
830 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000831 PyErr_SetString(pysqlite_OperationalError, "Error creating function");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000832 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000833 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +0500834 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000835}
836
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000837PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000838{
839 PyObject* aggregate_class;
840
841 int n_arg;
842 char* name;
843 static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
844 int rc;
845
Gerhard Häringf9cee222010-03-05 15:20:03 +0000846 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
847 return NULL;
848 }
849
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000850 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
851 kwlist, &name, &n_arg, &aggregate_class)) {
852 return NULL;
853 }
gescheitb9a03762019-07-13 06:15:49 +0300854 Py_INCREF(aggregate_class);
855 rc = sqlite3_create_function_v2(self->db,
856 name,
857 n_arg,
858 SQLITE_UTF8,
859 (void*)aggregate_class,
860 0,
861 &_pysqlite_step_callback,
862 &_pysqlite_final_callback,
863 &_destructor); // will decref func
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000864 if (rc != SQLITE_OK) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000865 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000866 PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000867 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000868 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +0500869 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000870}
871
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000872static 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 +0000873{
874 PyObject *ret;
875 int rc;
876 PyGILState_STATE gilstate;
877
878 gilstate = PyGILState_Ensure();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000879
Victor Stinnerd4095d92013-07-26 22:23:33 +0200880 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000881
Victor Stinnerd4095d92013-07-26 22:23:33 +0200882 if (ret == NULL) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700883 if (_pysqlite_enable_callback_tracebacks)
Victor Stinnerd4095d92013-07-26 22:23:33 +0200884 PyErr_Print();
885 else
886 PyErr_Clear();
Victor Stinner41801f52013-07-21 13:05:38 +0200887
Victor Stinnerd4095d92013-07-26 22:23:33 +0200888 rc = SQLITE_DENY;
Victor Stinner41801f52013-07-21 13:05:38 +0200889 }
890 else {
Victor Stinnerd4095d92013-07-26 22:23:33 +0200891 if (PyLong_Check(ret)) {
892 rc = _PyLong_AsInt(ret);
893 if (rc == -1 && PyErr_Occurred()) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700894 if (_pysqlite_enable_callback_tracebacks)
Victor Stinnerd4095d92013-07-26 22:23:33 +0200895 PyErr_Print();
896 else
897 PyErr_Clear();
898 rc = SQLITE_DENY;
899 }
900 }
901 else {
902 rc = SQLITE_DENY;
903 }
904 Py_DECREF(ret);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000905 }
906
907 PyGILState_Release(gilstate);
908 return rc;
909}
910
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000911static int _progress_handler(void* user_arg)
912{
913 int rc;
914 PyObject *ret;
915 PyGILState_STATE gilstate;
916
917 gilstate = PyGILState_Ensure();
Victor Stinner070c4d72016-12-09 12:29:18 +0100918 ret = _PyObject_CallNoArg((PyObject*)user_arg);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000919
920 if (!ret) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700921 if (_pysqlite_enable_callback_tracebacks) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000922 PyErr_Print();
923 } else {
924 PyErr_Clear();
925 }
926
Mark Dickinson934896d2009-02-21 20:59:32 +0000927 /* abort query if error occurred */
Victor Stinner86999502010-05-19 01:27:23 +0000928 rc = 1;
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000929 } else {
930 rc = (int)PyObject_IsTrue(ret);
931 Py_DECREF(ret);
932 }
933
934 PyGILState_Release(gilstate);
935 return rc;
936}
937
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +0200938#ifdef HAVE_TRACE_V2
939/*
940 * From https://sqlite.org/c3ref/trace_v2.html:
941 * The integer return value from the callback is currently ignored, though this
942 * may change in future releases. Callback implementations should return zero
943 * to ensure future compatibility.
944 */
945static int _trace_callback(unsigned int type, void* user_arg, void* prepared_statement, void* statement_string)
946#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200947static void _trace_callback(void* user_arg, const char* statement_string)
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +0200948#endif
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200949{
950 PyObject *py_statement = NULL;
951 PyObject *ret = NULL;
952
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200953 PyGILState_STATE gilstate;
954
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +0200955#ifdef HAVE_TRACE_V2
956 if (type != SQLITE_TRACE_STMT) {
957 return 0;
958 }
959#endif
960
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200961 gilstate = PyGILState_Ensure();
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200962 py_statement = PyUnicode_DecodeUTF8(statement_string,
963 strlen(statement_string), "replace");
964 if (py_statement) {
Petr Viktorinffd97532020-02-11 17:46:57 +0100965 ret = PyObject_CallOneArg((PyObject*)user_arg, py_statement);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200966 Py_DECREF(py_statement);
967 }
968
969 if (ret) {
970 Py_DECREF(ret);
971 } else {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700972 if (_pysqlite_enable_callback_tracebacks) {
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200973 PyErr_Print();
974 } else {
975 PyErr_Clear();
976 }
977 }
978
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200979 PyGILState_Release(gilstate);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +0200980#ifdef HAVE_TRACE_V2
981 return 0;
982#endif
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200983}
984
Gerhard Häringf9cee222010-03-05 15:20:03 +0000985static PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000986{
987 PyObject* authorizer_cb;
988
989 static char *kwlist[] = { "authorizer_callback", NULL };
990 int rc;
991
Gerhard Häringf9cee222010-03-05 15:20:03 +0000992 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
993 return NULL;
994 }
995
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000996 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
997 kwlist, &authorizer_cb)) {
998 return NULL;
999 }
1000
1001 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001002 if (rc != SQLITE_OK) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001003 PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
gescheitb9a03762019-07-13 06:15:49 +03001004 Py_XSETREF(self->function_pinboard_authorizer_cb, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001005 return NULL;
gescheitb9a03762019-07-13 06:15:49 +03001006 } else {
1007 Py_INCREF(authorizer_cb);
1008 Py_XSETREF(self->function_pinboard_authorizer_cb, authorizer_cb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001009 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +05001010 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001011}
1012
Gerhard Häringf9cee222010-03-05 15:20:03 +00001013static PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001014{
1015 PyObject* progress_handler;
1016 int n;
1017
1018 static char *kwlist[] = { "progress_handler", "n", NULL };
1019
Gerhard Häringf9cee222010-03-05 15:20:03 +00001020 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1021 return NULL;
1022 }
1023
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001024 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
1025 kwlist, &progress_handler, &n)) {
1026 return NULL;
1027 }
1028
1029 if (progress_handler == Py_None) {
1030 /* None clears the progress handler previously set */
1031 sqlite3_progress_handler(self->db, 0, 0, (void*)0);
gescheitb9a03762019-07-13 06:15:49 +03001032 Py_XSETREF(self->function_pinboard_progress_handler, NULL);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001033 } else {
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +05001034 sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
gescheitb9a03762019-07-13 06:15:49 +03001035 Py_INCREF(progress_handler);
1036 Py_XSETREF(self->function_pinboard_progress_handler, progress_handler);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001037 }
Berker Peksagfe21de92016-04-09 07:34:39 +03001038 Py_RETURN_NONE;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001039}
1040
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001041/*
1042 * Ref.
1043 * - https://sqlite.org/c3ref/c_trace.html
1044 * - https://sqlite.org/c3ref/trace_v2.html
1045 */
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001046static PyObject* pysqlite_connection_set_trace_callback(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1047{
1048 PyObject* trace_callback;
1049
1050 static char *kwlist[] = { "trace_callback", NULL };
1051
1052 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1053 return NULL;
1054 }
1055
1056 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_trace_callback",
1057 kwlist, &trace_callback)) {
1058 return NULL;
1059 }
1060
1061 if (trace_callback == Py_None) {
1062 /* None clears the trace callback previously set */
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001063#ifdef HAVE_TRACE_V2
1064 sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, 0, 0);
1065#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001066 sqlite3_trace(self->db, 0, (void*)0);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001067#endif
gescheitb9a03762019-07-13 06:15:49 +03001068 Py_XSETREF(self->function_pinboard_trace_callback, NULL);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001069 } else {
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001070#ifdef HAVE_TRACE_V2
1071 sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, _trace_callback, trace_callback);
1072#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001073 sqlite3_trace(self->db, _trace_callback, trace_callback);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001074#endif
gescheitb9a03762019-07-13 06:15:49 +03001075 Py_INCREF(trace_callback);
1076 Py_XSETREF(self->function_pinboard_trace_callback, trace_callback);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001077 }
1078
Berker Peksagfe21de92016-04-09 07:34:39 +03001079 Py_RETURN_NONE;
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001080}
1081
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +02001082#ifndef SQLITE_OMIT_LOAD_EXTENSION
Gerhard Häringf9cee222010-03-05 15:20:03 +00001083static PyObject* pysqlite_enable_load_extension(pysqlite_Connection* self, PyObject* args)
1084{
1085 int rc;
1086 int onoff;
1087
1088 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1089 return NULL;
1090 }
1091
1092 if (!PyArg_ParseTuple(args, "i", &onoff)) {
1093 return NULL;
1094 }
1095
1096 rc = sqlite3_enable_load_extension(self->db, onoff);
1097
1098 if (rc != SQLITE_OK) {
1099 PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
1100 return NULL;
1101 } else {
Berker Peksagfe21de92016-04-09 07:34:39 +03001102 Py_RETURN_NONE;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001103 }
1104}
1105
1106static PyObject* pysqlite_load_extension(pysqlite_Connection* self, PyObject* args)
1107{
1108 int rc;
1109 char* extension_name;
1110 char* errmsg;
1111
1112 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1113 return NULL;
1114 }
1115
1116 if (!PyArg_ParseTuple(args, "s", &extension_name)) {
1117 return NULL;
1118 }
1119
1120 rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1121 if (rc != 0) {
1122 PyErr_SetString(pysqlite_OperationalError, errmsg);
1123 return NULL;
1124 } else {
Berker Peksagfe21de92016-04-09 07:34:39 +03001125 Py_RETURN_NONE;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001126 }
1127}
1128#endif
1129
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001130int pysqlite_check_thread(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001131{
1132 if (self->check_same_thread) {
1133 if (PyThread_get_thread_ident() != self->thread_ident) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001134 PyErr_Format(pysqlite_ProgrammingError,
Takuya Akiba030345c2018-03-27 00:14:00 +09001135 "SQLite objects created in a thread can only be used in that same thread. "
1136 "The object was created in thread id %lu and this is thread id %lu.",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001137 self->thread_ident, PyThread_get_thread_ident());
1138 return 0;
1139 }
1140
1141 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001142 return 1;
1143}
1144
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001145static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001146{
1147 Py_INCREF(self->isolation_level);
1148 return self->isolation_level;
1149}
1150
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001151static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001152{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001153 if (!pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001154 return NULL;
1155 } else {
1156 return Py_BuildValue("i", sqlite3_total_changes(self->db));
1157 }
1158}
1159
Berker Peksag59da4b32016-09-12 07:16:43 +03001160static PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
1161{
1162 if (!pysqlite_check_connection(self)) {
1163 return NULL;
1164 }
1165 if (!sqlite3_get_autocommit(self->db)) {
1166 Py_RETURN_TRUE;
1167 }
1168 Py_RETURN_FALSE;
1169}
1170
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +02001171static int
1172pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001173{
Zackery Spytz842acaa2018-12-17 07:52:45 -07001174 if (isolation_level == NULL) {
1175 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
1176 return -1;
1177 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001178 if (isolation_level == Py_None) {
Serhiy Storchaka28914922016-09-01 22:18:03 +03001179 PyObject *res = pysqlite_connection_commit(self, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001180 if (!res) {
1181 return -1;
1182 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001183 Py_DECREF(res);
1184
Serhiy Storchaka28914922016-09-01 22:18:03 +03001185 self->begin_statement = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001186 } else {
Serhiy Storchaka28914922016-09-01 22:18:03 +03001187 const char * const *candidate;
1188 PyObject *uppercase_level;
1189 _Py_IDENTIFIER(upper);
Neal Norwitzefee9f52007-10-27 02:50:52 +00001190
Serhiy Storchaka28914922016-09-01 22:18:03 +03001191 if (!PyUnicode_Check(isolation_level)) {
1192 PyErr_Format(PyExc_TypeError,
1193 "isolation_level must be a string or None, not %.100s",
1194 Py_TYPE(isolation_level)->tp_name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001195 return -1;
1196 }
1197
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001198 uppercase_level = _PyObject_CallMethodIdOneArg(
Serhiy Storchaka28914922016-09-01 22:18:03 +03001199 (PyObject *)&PyUnicode_Type, &PyId_upper,
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001200 isolation_level);
Serhiy Storchaka28914922016-09-01 22:18:03 +03001201 if (!uppercase_level) {
Georg Brandl3dbca812008-07-23 16:10:53 +00001202 return -1;
1203 }
Serhiy Storchaka28914922016-09-01 22:18:03 +03001204 for (candidate = begin_statements; *candidate; candidate++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001205 if (_PyUnicode_EqualToASCIIString(uppercase_level, *candidate + 6))
Serhiy Storchaka28914922016-09-01 22:18:03 +03001206 break;
1207 }
1208 Py_DECREF(uppercase_level);
1209 if (!*candidate) {
1210 PyErr_SetString(PyExc_ValueError,
1211 "invalid value for isolation_level");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001212 return -1;
1213 }
Serhiy Storchaka28914922016-09-01 22:18:03 +03001214 self->begin_statement = *candidate;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001215 }
1216
Serhiy Storchaka28914922016-09-01 22:18:03 +03001217 Py_INCREF(isolation_level);
1218 Py_XSETREF(self->isolation_level, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001219 return 0;
1220}
1221
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001222PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001223{
1224 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001225 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001226 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001227 int rc;
1228
Gerhard Häringf9cee222010-03-05 15:20:03 +00001229 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1230 return NULL;
1231 }
1232
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001233 if (!_PyArg_NoKeywords(MODULE_NAME ".Connection", kwargs))
Larry Hastings3b12e952015-05-08 07:45:10 -07001234 return NULL;
1235
Victor Stinnerc6a23202019-06-26 03:16:24 +02001236 if (!PyArg_ParseTuple(args, "U", &sql))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001237 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001238
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001239 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001240
Erlend Egeberg Aasland9031bd42020-10-01 15:24:31 +02001241 statement = PyObject_New(pysqlite_Statement, pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001242 if (!statement) {
1243 return NULL;
1244 }
1245
Victor Stinner0201f442010-03-13 03:28:34 +00001246 statement->db = NULL;
1247 statement->st = NULL;
1248 statement->sql = NULL;
1249 statement->in_use = 0;
1250 statement->in_weakreflist = NULL;
1251
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001252 rc = pysqlite_statement_create(statement, self, sql);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001253 if (rc != SQLITE_OK) {
1254 if (rc == PYSQLITE_TOO_MUCH_SQL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001255 PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001256 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
Serhiy Storchaka42d67af2014-09-11 13:29:05 +03001257 if (PyErr_ExceptionMatches(PyExc_TypeError))
1258 PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001259 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001260 (void)pysqlite_statement_reset(statement);
1261 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001262 }
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001263 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001264 }
1265
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001266 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
1267 if (weakref == NULL)
1268 goto error;
1269 if (PyList_Append(self->statements, weakref) != 0) {
1270 Py_DECREF(weakref);
1271 goto error;
1272 }
1273 Py_DECREF(weakref);
1274
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001275 return (PyObject*)statement;
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001276
1277error:
1278 Py_DECREF(statement);
1279 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001280}
1281
Larry Hastings01b08832015-05-08 07:37:49 -07001282PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001283{
1284 PyObject* cursor = 0;
1285 PyObject* result = 0;
1286 PyObject* method = 0;
1287
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001288 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001289 if (!cursor) {
1290 goto error;
1291 }
1292
1293 method = PyObject_GetAttrString(cursor, "execute");
1294 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001295 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001296 goto error;
1297 }
1298
1299 result = PyObject_CallObject(method, args);
1300 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001301 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001302 }
1303
1304error:
1305 Py_XDECREF(result);
1306 Py_XDECREF(method);
1307
1308 return cursor;
1309}
1310
Larry Hastings01b08832015-05-08 07:37:49 -07001311PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001312{
1313 PyObject* cursor = 0;
1314 PyObject* result = 0;
1315 PyObject* method = 0;
1316
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001317 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001318 if (!cursor) {
1319 goto error;
1320 }
1321
1322 method = PyObject_GetAttrString(cursor, "executemany");
1323 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001324 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001325 goto error;
1326 }
1327
1328 result = PyObject_CallObject(method, args);
1329 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001330 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001331 }
1332
1333error:
1334 Py_XDECREF(result);
1335 Py_XDECREF(method);
1336
1337 return cursor;
1338}
1339
Larry Hastings01b08832015-05-08 07:37:49 -07001340PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001341{
1342 PyObject* cursor = 0;
1343 PyObject* result = 0;
1344 PyObject* method = 0;
1345
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001346 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001347 if (!cursor) {
1348 goto error;
1349 }
1350
1351 method = PyObject_GetAttrString(cursor, "executescript");
1352 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001353 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001354 goto error;
1355 }
1356
1357 result = PyObject_CallObject(method, args);
1358 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001359 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001360 }
1361
1362error:
1363 Py_XDECREF(result);
1364 Py_XDECREF(method);
1365
1366 return cursor;
1367}
1368
1369/* ------------------------- COLLATION CODE ------------------------ */
1370
1371static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001372pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001373 void* context,
1374 int text1_length, const void* text1_data,
1375 int text2_length, const void* text2_data)
1376{
1377 PyObject* callback = (PyObject*)context;
1378 PyObject* string1 = 0;
1379 PyObject* string2 = 0;
1380 PyGILState_STATE gilstate;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001381 PyObject* retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001382 long longval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001383 int result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001384 gilstate = PyGILState_Ensure();
1385
1386 if (PyErr_Occurred()) {
1387 goto finally;
1388 }
1389
Guido van Rossum98297ee2007-11-06 21:34:58 +00001390 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1391 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001392
1393 if (!string1 || !string2) {
1394 goto finally; /* failed to allocate strings */
1395 }
1396
1397 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1398
1399 if (!retval) {
1400 /* execution failed */
1401 goto finally;
1402 }
1403
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001404 longval = PyLong_AsLongAndOverflow(retval, &result);
1405 if (longval == -1 && PyErr_Occurred()) {
1406 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001407 result = 0;
1408 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001409 else if (!result) {
1410 if (longval > 0)
1411 result = 1;
1412 else if (longval < 0)
1413 result = -1;
1414 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001415
1416finally:
1417 Py_XDECREF(string1);
1418 Py_XDECREF(string2);
1419 Py_XDECREF(retval);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001420 PyGILState_Release(gilstate);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001421 return result;
1422}
1423
1424static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001425pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001426{
1427 PyObject* retval = NULL;
1428
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001429 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001430 goto finally;
1431 }
1432
1433 sqlite3_interrupt(self->db);
1434
1435 Py_INCREF(Py_None);
1436 retval = Py_None;
1437
1438finally:
1439 return retval;
1440}
1441
Christian Heimesbbe741d2008-03-28 10:53:29 +00001442/* Function author: Paul Kippes <kippesp@gmail.com>
1443 * Class method of Connection to call the Python function _iterdump
1444 * of the sqlite3 module.
1445 */
1446static PyObject *
1447pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1448{
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001449 _Py_IDENTIFIER(_iterdump);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001450 PyObject* retval = NULL;
1451 PyObject* module = NULL;
1452 PyObject* module_dict;
1453 PyObject* pyfn_iterdump;
1454
1455 if (!pysqlite_check_connection(self)) {
1456 goto finally;
1457 }
1458
1459 module = PyImport_ImportModule(MODULE_NAME ".dump");
1460 if (!module) {
1461 goto finally;
1462 }
1463
1464 module_dict = PyModule_GetDict(module);
1465 if (!module_dict) {
1466 goto finally;
1467 }
1468
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001469 pyfn_iterdump = _PyDict_GetItemIdWithError(module_dict, &PyId__iterdump);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001470 if (!pyfn_iterdump) {
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001471 if (!PyErr_Occurred()) {
1472 PyErr_SetString(pysqlite_OperationalError,
1473 "Failed to obtain _iterdump() reference");
1474 }
Christian Heimesbbe741d2008-03-28 10:53:29 +00001475 goto finally;
1476 }
1477
Petr Viktorinffd97532020-02-11 17:46:57 +01001478 retval = PyObject_CallOneArg(pyfn_iterdump, (PyObject *)self);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001479
1480finally:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001481 Py_XDECREF(module);
1482 return retval;
1483}
1484
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001485static PyObject *
1486pysqlite_connection_backup(pysqlite_Connection *self, PyObject *args, PyObject *kwds)
1487{
1488 PyObject *target = NULL;
1489 int pages = -1;
1490 PyObject *progress = Py_None;
1491 const char *name = "main";
1492 int rc;
1493 int callback_error = 0;
Victor Stinnerca405012018-04-30 12:22:17 +02001494 PyObject *sleep_obj = NULL;
1495 int sleep_ms = 250;
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001496 sqlite3 *bck_conn;
1497 sqlite3_backup *bck_handle;
1498 static char *keywords[] = {"target", "pages", "progress", "name", "sleep", NULL};
1499
Victor Stinnerca405012018-04-30 12:22:17 +02001500 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|$iOsO:backup", keywords,
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001501 pysqlite_ConnectionType, &target,
Victor Stinnerca405012018-04-30 12:22:17 +02001502 &pages, &progress, &name, &sleep_obj)) {
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001503 return NULL;
1504 }
1505
Victor Stinnerca405012018-04-30 12:22:17 +02001506 if (sleep_obj != NULL) {
1507 _PyTime_t sleep_secs;
1508 if (_PyTime_FromSecondsObject(&sleep_secs, sleep_obj,
1509 _PyTime_ROUND_TIMEOUT)) {
1510 return NULL;
1511 }
1512 _PyTime_t ms = _PyTime_AsMilliseconds(sleep_secs,
1513 _PyTime_ROUND_TIMEOUT);
1514 if (ms < INT_MIN || ms > INT_MAX) {
1515 PyErr_SetString(PyExc_OverflowError, "sleep is too large");
1516 return NULL;
1517 }
1518 sleep_ms = (int)ms;
1519 }
1520
Peter McCormickbfee9fa2020-09-19 23:40:46 -04001521 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1522 return NULL;
1523 }
1524
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001525 if (!pysqlite_check_connection((pysqlite_Connection *)target)) {
1526 return NULL;
1527 }
1528
1529 if ((pysqlite_Connection *)target == self) {
1530 PyErr_SetString(PyExc_ValueError, "target cannot be the same connection instance");
1531 return NULL;
1532 }
1533
Aviv Palivodabbf7bb72018-03-18 02:48:55 +02001534#if SQLITE_VERSION_NUMBER < 3008008
1535 /* Since 3.8.8 this is already done, per commit
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001536 https://www.sqlite.org/src/info/169b5505498c0a7e */
1537 if (!sqlite3_get_autocommit(((pysqlite_Connection *)target)->db)) {
1538 PyErr_SetString(pysqlite_OperationalError, "target is in transaction");
1539 return NULL;
1540 }
1541#endif
1542
1543 if (progress != Py_None && !PyCallable_Check(progress)) {
1544 PyErr_SetString(PyExc_TypeError, "progress argument must be a callable");
1545 return NULL;
1546 }
1547
1548 if (pages == 0) {
1549 pages = -1;
1550 }
1551
1552 bck_conn = ((pysqlite_Connection *)target)->db;
1553
1554 Py_BEGIN_ALLOW_THREADS
1555 bck_handle = sqlite3_backup_init(bck_conn, "main", self->db, name);
1556 Py_END_ALLOW_THREADS
1557
1558 if (bck_handle) {
1559 do {
1560 Py_BEGIN_ALLOW_THREADS
1561 rc = sqlite3_backup_step(bck_handle, pages);
1562 Py_END_ALLOW_THREADS
1563
1564 if (progress != Py_None) {
1565 PyObject *res;
1566
1567 res = PyObject_CallFunction(progress, "iii", rc,
1568 sqlite3_backup_remaining(bck_handle),
1569 sqlite3_backup_pagecount(bck_handle));
1570 if (res == NULL) {
1571 /* User's callback raised an error: interrupt the loop and
1572 propagate it. */
1573 callback_error = 1;
1574 rc = -1;
1575 } else {
1576 Py_DECREF(res);
1577 }
1578 }
1579
1580 /* Sleep for a while if there are still further pages to copy and
1581 the engine could not make any progress */
1582 if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) {
1583 Py_BEGIN_ALLOW_THREADS
Victor Stinnerca405012018-04-30 12:22:17 +02001584 sqlite3_sleep(sleep_ms);
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001585 Py_END_ALLOW_THREADS
1586 }
1587 } while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);
1588
1589 Py_BEGIN_ALLOW_THREADS
1590 rc = sqlite3_backup_finish(bck_handle);
1591 Py_END_ALLOW_THREADS
1592 } else {
1593 rc = _pysqlite_seterror(bck_conn, NULL);
1594 }
1595
1596 if (!callback_error && rc != SQLITE_OK) {
1597 /* We cannot use _pysqlite_seterror() here because the backup APIs do
1598 not set the error status on the connection object, but rather on
1599 the backup handle. */
1600 if (rc == SQLITE_NOMEM) {
1601 (void)PyErr_NoMemory();
1602 } else {
1603#if SQLITE_VERSION_NUMBER > 3007015
1604 PyErr_SetString(pysqlite_OperationalError, sqlite3_errstr(rc));
1605#else
1606 switch (rc) {
Berker Peksagb10a64d2018-09-20 14:14:33 +03001607 case SQLITE_ERROR:
1608 /* Description of SQLITE_ERROR in SQLite 3.7.14 and older
1609 releases. */
1610 PyErr_SetString(pysqlite_OperationalError,
1611 "SQL logic error or missing database");
1612 break;
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001613 case SQLITE_READONLY:
1614 PyErr_SetString(pysqlite_OperationalError,
1615 "attempt to write a readonly database");
1616 break;
1617 case SQLITE_BUSY:
1618 PyErr_SetString(pysqlite_OperationalError, "database is locked");
1619 break;
1620 case SQLITE_LOCKED:
1621 PyErr_SetString(pysqlite_OperationalError,
1622 "database table is locked");
1623 break;
1624 default:
1625 PyErr_Format(pysqlite_OperationalError,
1626 "unrecognized error code: %d", rc);
1627 break;
1628 }
1629#endif
1630 }
1631 }
1632
1633 if (!callback_error && rc == SQLITE_OK) {
1634 Py_RETURN_NONE;
1635 } else {
1636 return NULL;
1637 }
1638}
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001639
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001640static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001641pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001642{
1643 PyObject* callable;
1644 PyObject* uppercase_name = 0;
1645 PyObject* name;
1646 PyObject* retval;
Victor Stinner35466c52010-04-22 11:23:23 +00001647 Py_ssize_t i, len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001648 _Py_IDENTIFIER(upper);
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001649 const char *uppercase_name_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001650 int rc;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001651 unsigned int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001652 const void *data;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001653
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001654 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001655 goto finally;
1656 }
1657
Serhiy Storchaka407ac472016-09-27 00:10:03 +03001658 if (!PyArg_ParseTuple(args, "UO:create_collation(name, callback)",
1659 &name, &callable)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001660 goto finally;
1661 }
1662
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001663 uppercase_name = _PyObject_CallMethodIdOneArg((PyObject *)&PyUnicode_Type,
1664 &PyId_upper, name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001665 if (!uppercase_name) {
1666 goto finally;
1667 }
1668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001669 if (PyUnicode_READY(uppercase_name))
1670 goto finally;
1671 len = PyUnicode_GET_LENGTH(uppercase_name);
1672 kind = PyUnicode_KIND(uppercase_name);
1673 data = PyUnicode_DATA(uppercase_name);
1674 for (i=0; i<len; i++) {
1675 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1676 if ((ch >= '0' && ch <= '9')
1677 || (ch >= 'A' && ch <= 'Z')
1678 || (ch == '_'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001679 {
Victor Stinner35466c52010-04-22 11:23:23 +00001680 continue;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001681 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001682 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001683 goto finally;
1684 }
1685 }
1686
Serhiy Storchaka06515832016-11-20 09:13:07 +02001687 uppercase_name_str = PyUnicode_AsUTF8(uppercase_name);
Victor Stinner35466c52010-04-22 11:23:23 +00001688 if (!uppercase_name_str)
1689 goto finally;
1690
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001691 if (callable != Py_None && !PyCallable_Check(callable)) {
1692 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1693 goto finally;
1694 }
1695
1696 if (callable != Py_None) {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001697 if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
1698 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001699 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001700 if (PyDict_DelItem(self->collations, uppercase_name) == -1)
1701 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001702 }
1703
1704 rc = sqlite3_create_collation(self->db,
Victor Stinner35466c52010-04-22 11:23:23 +00001705 uppercase_name_str,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001706 SQLITE_UTF8,
1707 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001708 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001709 if (rc != SQLITE_OK) {
1710 PyDict_DelItem(self->collations, uppercase_name);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001711 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001712 goto finally;
1713 }
1714
1715finally:
1716 Py_XDECREF(uppercase_name);
1717
1718 if (PyErr_Occurred()) {
1719 retval = NULL;
1720 } else {
1721 Py_INCREF(Py_None);
1722 retval = Py_None;
1723 }
1724
1725 return retval;
1726}
1727
Christian Heimesbbe741d2008-03-28 10:53:29 +00001728/* Called when the connection is used as a context manager. Returns itself as a
1729 * convenience to the caller. */
1730static PyObject *
1731pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1732{
1733 Py_INCREF(self);
1734 return (PyObject*)self;
1735}
1736
1737/** Called when the connection is used as a context manager. If there was any
1738 * exception, a rollback takes place; otherwise we commit. */
1739static PyObject *
1740pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1741{
1742 PyObject* exc_type, *exc_value, *exc_tb;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001743 const char* method_name;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001744 PyObject* result;
1745
1746 if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1747 return NULL;
1748 }
1749
1750 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1751 method_name = "commit";
1752 } else {
1753 method_name = "rollback";
1754 }
1755
Victor Stinner3466bde2016-09-05 18:16:01 -07001756 result = PyObject_CallMethod((PyObject*)self, method_name, NULL);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001757 if (!result) {
1758 return NULL;
1759 }
1760 Py_DECREF(result);
1761
1762 Py_RETURN_FALSE;
1763}
1764
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001765static const char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001766PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001767
1768static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001769 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1770 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Berker Peksag59da4b32016-09-12 07:16:43 +03001771 {"in_transaction", (getter)pysqlite_connection_get_in_transaction, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001772 {NULL}
1773};
1774
1775static PyMethodDef connection_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001776 {"cursor", (PyCFunction)(void(*)(void))pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001777 PyDoc_STR("Return a cursor for the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001778 {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001779 PyDoc_STR("Closes the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001780 {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001781 PyDoc_STR("Commit the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001782 {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001783 PyDoc_STR("Roll back the current transaction.")},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001784 {"create_function", (PyCFunction)(void(*)(void))pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001785 PyDoc_STR("Creates a new function. Non-standard.")},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001786 {"create_aggregate", (PyCFunction)(void(*)(void))pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001787 PyDoc_STR("Creates a new aggregate. Non-standard.")},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001788 {"set_authorizer", (PyCFunction)(void(*)(void))pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001789 PyDoc_STR("Sets authorizer callback. Non-standard.")},
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +02001790 #ifndef SQLITE_OMIT_LOAD_EXTENSION
Gerhard Häringf9cee222010-03-05 15:20:03 +00001791 {"enable_load_extension", (PyCFunction)pysqlite_enable_load_extension, METH_VARARGS,
1792 PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
1793 {"load_extension", (PyCFunction)pysqlite_load_extension, METH_VARARGS,
1794 PyDoc_STR("Load SQLite extension module. Non-standard.")},
1795 #endif
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001796 {"set_progress_handler", (PyCFunction)(void(*)(void))pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001797 PyDoc_STR("Sets progress handler callback. Non-standard.")},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001798 {"set_trace_callback", (PyCFunction)(void(*)(void))pysqlite_connection_set_trace_callback, METH_VARARGS|METH_KEYWORDS,
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001799 PyDoc_STR("Sets a trace callback called for each SQL statement (passed as unicode). Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001800 {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001801 PyDoc_STR("Executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001802 {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001803 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001804 {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001805 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001806 {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001807 PyDoc_STR("Creates a collation function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001808 {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001809 PyDoc_STR("Abort any pending database operation. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001810 {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
Benjamin Petersond7b03282008-09-13 15:58:53 +00001811 PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001812 {"backup", (PyCFunction)(void(*)(void))pysqlite_connection_backup, METH_VARARGS | METH_KEYWORDS,
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001813 PyDoc_STR("Makes a backup of the database. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001814 {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1815 PyDoc_STR("For context manager. Non-standard.")},
1816 {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1817 PyDoc_STR("For context manager. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001818 {NULL, NULL}
1819};
1820
1821static struct PyMemberDef connection_members[] =
1822{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001823 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1824 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1825 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1826 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1827 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1828 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1829 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1830 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1831 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1832 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001833 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1834 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001835 {NULL}
1836};
1837
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001838static PyType_Slot connection_slots[] = {
1839 {Py_tp_dealloc, pysqlite_connection_dealloc},
1840 {Py_tp_doc, (void *)connection_doc},
1841 {Py_tp_methods, connection_methods},
1842 {Py_tp_members, connection_members},
1843 {Py_tp_getset, connection_getset},
1844 {Py_tp_new, PyType_GenericNew},
1845 {Py_tp_init, pysqlite_connection_init},
1846 {Py_tp_call, pysqlite_connection_call},
1847 {0, NULL},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001848};
1849
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001850static PyType_Spec connection_spec = {
1851 .name = MODULE_NAME ".Connection",
1852 .basicsize = sizeof(pysqlite_Connection),
1853 .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1854 .slots = connection_slots,
1855};
1856
1857PyTypeObject *pysqlite_ConnectionType = NULL;
1858
1859extern int pysqlite_connection_setup_types(PyObject *module)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001860{
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001861 pysqlite_ConnectionType = (PyTypeObject *)PyType_FromModuleAndSpec(module, &connection_spec, NULL);
1862 if (pysqlite_ConnectionType == NULL) {
1863 return -1;
1864 }
1865 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001866}