blob: 2cc5f53a30bc0c8f3231cd22205ff73e5a29010c [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
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +010040#include "clinic/connection.c.h"
41/*[clinic input]
42module _sqlite3
43class _sqlite3.Connection "pysqlite_Connection *" "pysqlite_ConnectionType"
44[clinic start generated code]*/
45/*[clinic end generated code: output=da39a3ee5e6b4b0d input=aa796073bd8f69db]*/
46
Martin v. Löwise75fc142013-11-07 18:46:53 +010047_Py_IDENTIFIER(cursor);
48
Serhiy Storchaka28914922016-09-01 22:18:03 +030049static const char * const begin_statements[] = {
50 "BEGIN ",
51 "BEGIN DEFERRED",
52 "BEGIN IMMEDIATE",
53 "BEGIN EXCLUSIVE",
54 NULL
55};
56
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +020057static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored));
Gerhard Häringf9cee222010-03-05 15:20:03 +000058static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000059
Erlend Egeberg Aaslandbf838a62021-02-21 01:29:19 +010060static int
61pysqlite_connection_init(pysqlite_Connection *self, PyObject *args,
62 PyObject *kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063{
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010064 static char *kwlist[] = {
65 "database", "timeout", "detect_types", "isolation_level",
66 "check_same_thread", "factory", "cached_statements", "uri",
67 NULL
68 };
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000069
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +030070 const char* database;
Anders Lorentsena22a1272017-11-07 01:47:43 +010071 PyObject* database_obj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000072 int detect_types = 0;
73 PyObject* isolation_level = NULL;
74 PyObject* factory = NULL;
75 int check_same_thread = 1;
76 int cached_statements = 100;
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010077 int uri = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078 double timeout = 5.0;
79 int rc;
80
Anders Lorentsena22a1272017-11-07 01:47:43 +010081 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|diOiOip", kwlist,
82 PyUnicode_FSConverter, &database_obj, &timeout, &detect_types,
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010083 &isolation_level, &check_same_thread,
84 &factory, &cached_statements, &uri))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000085 {
Gerhard Häringe7ea7452008-03-29 00:45:29 +000086 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000087 }
88
Erlend Egeberg Aaslandc96cc082021-05-02 23:25:17 +020089 if (PySys_Audit("sqlite3.connect", "O", database_obj) < 0) {
Erlend Egeberg Aaslandaa6dd542021-09-13 05:16:01 +020090 Py_DECREF(database_obj);
Erlend Egeberg Aaslandc96cc082021-05-02 23:25:17 +020091 return -1;
92 }
93
Anders Lorentsena22a1272017-11-07 01:47:43 +010094 database = PyBytes_AsString(database_obj);
95
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000096 self->begin_statement = NULL;
97
Oren Milman93c5a5d2017-10-10 22:27:46 +030098 Py_CLEAR(self->statement_cache);
99 Py_CLEAR(self->statements);
100 Py_CLEAR(self->cursors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000101
102 Py_INCREF(Py_None);
Oren Milman93c5a5d2017-10-10 22:27:46 +0300103 Py_XSETREF(self->row_factory, Py_None);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000104
105 Py_INCREF(&PyUnicode_Type);
Oren Milman93c5a5d2017-10-10 22:27:46 +0300106 Py_XSETREF(self->text_factory, (PyObject*)&PyUnicode_Type);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000107
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100108 Py_BEGIN_ALLOW_THREADS
109 rc = sqlite3_open_v2(database, &self->db,
110 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
111 (uri ? SQLITE_OPEN_URI : 0), NULL);
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);
Erlend Egeberg Aasland0cb470e2021-07-30 14:01:22 +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
Erlend Egeberg Aaslandc96cc082021-05-02 23:25:17 +0200185 if (PySys_Audit("sqlite3.connect/handle", "O", self) < 0) {
186 return -1;
187 }
188
Erlend Egeberg Aasland0cb470e2021-07-30 14:01:22 +0200189 self->initialized = 1;
190
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000191 return 0;
192}
193
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000194/* action in (ACTION_RESET, ACTION_FINALIZE) */
Erlend Egeberg Aaslandbf838a62021-02-21 01:29:19 +0100195static void
196pysqlite_do_all_statements(pysqlite_Connection *self, int action,
197 int reset_cursors)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000198{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000199 int i;
200 PyObject* weakref;
201 PyObject* statement;
Gerhard Häringf9cee222010-03-05 15:20:03 +0000202 pysqlite_Cursor* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000203
Thomas Wouters477c8d52006-05-27 19:21:47 +0000204 for (i = 0; i < PyList_Size(self->statements); i++) {
205 weakref = PyList_GetItem(self->statements, i);
206 statement = PyWeakref_GetObject(weakref);
207 if (statement != Py_None) {
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500208 Py_INCREF(statement);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000209 if (action == ACTION_RESET) {
210 (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
211 } else {
212 (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
213 }
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500214 Py_DECREF(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000215 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216 }
Gerhard Häringf9cee222010-03-05 15:20:03 +0000217
218 if (reset_cursors) {
219 for (i = 0; i < PyList_Size(self->cursors); i++) {
220 weakref = PyList_GetItem(self->cursors, i);
221 cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
222 if ((PyObject*)cursor != Py_None) {
223 cursor->reset = 1;
224 }
225 }
226 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000227}
228
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700229static int
230connection_traverse(pysqlite_Connection *self, visitproc visit, void *arg)
231{
Miss Islington (bot)ff359d72021-05-31 02:12:27 -0700232 Py_VISIT(Py_TYPE(self));
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700233 Py_VISIT(self->isolation_level);
Miss Islington (bot)ff359d72021-05-31 02:12:27 -0700234 Py_VISIT(self->statement_cache);
235 Py_VISIT(self->statements);
236 Py_VISIT(self->cursors);
237 Py_VISIT(self->row_factory);
238 Py_VISIT(self->text_factory);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700239 Py_VISIT(self->function_pinboard_trace_callback);
240 Py_VISIT(self->function_pinboard_progress_handler);
241 Py_VISIT(self->function_pinboard_authorizer_cb);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700242 Py_VISIT(self->collations);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700243 return 0;
244}
245
246static int
247connection_clear(pysqlite_Connection *self)
248{
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700249 Py_CLEAR(self->isolation_level);
Miss Islington (bot)ff359d72021-05-31 02:12:27 -0700250 Py_CLEAR(self->statement_cache);
251 Py_CLEAR(self->statements);
252 Py_CLEAR(self->cursors);
253 Py_CLEAR(self->row_factory);
254 Py_CLEAR(self->text_factory);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700255 Py_CLEAR(self->function_pinboard_trace_callback);
256 Py_CLEAR(self->function_pinboard_progress_handler);
257 Py_CLEAR(self->function_pinboard_authorizer_cb);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700258 Py_CLEAR(self->collations);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700259 return 0;
260}
261
Erlend Egeberg Aaslandbf838a62021-02-21 01:29:19 +0100262static void
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700263connection_dealloc(pysqlite_Connection *self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000264{
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200265 PyTypeObject *tp = Py_TYPE(self);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700266 PyObject_GC_UnTrack(self);
267 tp->tp_clear((PyObject *)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000268
269 /* Clean up if user has not called .close() explicitly. */
270 if (self->db) {
Erlend Egeberg Aaslandcf0b2392021-01-06 01:02:43 +0100271 sqlite3_close_v2(self->db);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000272 }
273
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200274 tp->tp_free(self);
275 Py_DECREF(tp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000276}
277
Gerhard Häringf9cee222010-03-05 15:20:03 +0000278/*
279 * Registers a cursor with the connection.
280 *
281 * 0 => error; 1 => ok
282 */
283int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
284{
285 PyObject* weakref;
286
287 weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
288 if (!weakref) {
289 goto error;
290 }
291
292 if (PyList_Append(connection->cursors, weakref) != 0) {
293 Py_CLEAR(weakref);
294 goto error;
295 }
296
297 Py_DECREF(weakref);
298
299 return 1;
300error:
301 return 0;
302}
303
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100304/*[clinic input]
305_sqlite3.Connection.cursor as pysqlite_connection_cursor
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000306
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100307 factory: object = NULL
308
309Return a cursor for the connection.
310[clinic start generated code]*/
311
312static PyObject *
313pysqlite_connection_cursor_impl(pysqlite_Connection *self, PyObject *factory)
314/*[clinic end generated code: output=562432a9e6af2aa1 input=4127345aa091b650]*/
315{
316 PyObject* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000317
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000318 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000319 return NULL;
320 }
321
322 if (factory == NULL) {
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200323 factory = (PyObject*)pysqlite_CursorType;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000324 }
325
Petr Viktorinffd97532020-02-11 17:46:57 +0100326 cursor = PyObject_CallOneArg(factory, (PyObject *)self);
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300327 if (cursor == NULL)
328 return NULL;
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200329 if (!PyObject_TypeCheck(cursor, pysqlite_CursorType)) {
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300330 PyErr_Format(PyExc_TypeError,
331 "factory must return a cursor, not %.100s",
332 Py_TYPE(cursor)->tp_name);
333 Py_DECREF(cursor);
334 return NULL;
335 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000336
Gerhard Häringf9cee222010-03-05 15:20:03 +0000337 _pysqlite_drop_unused_cursor_references(self);
338
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000339 if (cursor && self->row_factory != Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000340 Py_INCREF(self->row_factory);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300341 Py_XSETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000342 }
343
344 return cursor;
345}
346
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100347/*[clinic input]
348_sqlite3.Connection.close as pysqlite_connection_close
349
350Closes the connection.
351[clinic start generated code]*/
352
353static PyObject *
354pysqlite_connection_close_impl(pysqlite_Connection *self)
355/*[clinic end generated code: output=a546a0da212c9b97 input=3d58064bbffaa3d3]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000356{
357 int rc;
358
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000359 if (!pysqlite_check_thread(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000360 return NULL;
361 }
362
Erlend Egeberg Aasland0cb470e2021-07-30 14:01:22 +0200363 if (!self->initialized) {
364 PyErr_SetString(pysqlite_ProgrammingError,
365 "Base Connection.__init__ not called.");
366 return NULL;
367 }
368
Gerhard Häringf9cee222010-03-05 15:20:03 +0000369 pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000370
371 if (self->db) {
Erlend Egeberg Aaslandcf0b2392021-01-06 01:02:43 +0100372 rc = sqlite3_close_v2(self->db);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000373
374 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000375 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000376 return NULL;
377 } else {
378 self->db = NULL;
379 }
380 }
381
Berker Peksagfe21de92016-04-09 07:34:39 +0300382 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000383}
384
385/*
386 * Checks if a connection object is usable (i. e. not closed).
387 *
388 * 0 => error; 1 => ok
389 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000390int pysqlite_check_connection(pysqlite_Connection* con)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000391{
Gerhard Häringf9cee222010-03-05 15:20:03 +0000392 if (!con->initialized) {
393 PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
394 return 0;
395 }
396
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000397 if (!con->db) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000398 PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000399 return 0;
400 } else {
401 return 1;
402 }
403}
404
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000405PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000406{
407 int rc;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000408 sqlite3_stmt* statement;
409
410 Py_BEGIN_ALLOW_THREADS
Erlend Egeberg Aasland5e48e832021-02-26 15:30:22 +0100411 rc = sqlite3_prepare_v2(self->db, self->begin_statement, -1, &statement,
412 NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000413 Py_END_ALLOW_THREADS
414
415 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000416 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417 goto error;
418 }
419
Benjamin Petersond7b03282008-09-13 15:58:53 +0000420 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300421 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000422 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000423 }
424
425 Py_BEGIN_ALLOW_THREADS
426 rc = sqlite3_finalize(statement);
427 Py_END_ALLOW_THREADS
428
429 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000430 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000431 }
432
433error:
434 if (PyErr_Occurred()) {
435 return NULL;
436 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200437 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000438 }
439}
440
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +0100441/*[clinic input]
442_sqlite3.Connection.commit as pysqlite_connection_commit
443
444Commit the current transaction.
445[clinic start generated code]*/
446
447static PyObject *
448pysqlite_connection_commit_impl(pysqlite_Connection *self)
449/*[clinic end generated code: output=3da45579e89407f2 input=39c12c04dda276a8]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000450{
451 int rc;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000452 sqlite3_stmt* statement;
453
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000454 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000455 return NULL;
456 }
457
Berker Peksag59da4b32016-09-12 07:16:43 +0300458 if (!sqlite3_get_autocommit(self->db)) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000459
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000460 Py_BEGIN_ALLOW_THREADS
Erlend Egeberg Aasland5e48e832021-02-26 15:30:22 +0100461 rc = sqlite3_prepare_v2(self->db, "COMMIT", -1, &statement, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000462 Py_END_ALLOW_THREADS
463 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000464 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000465 goto error;
466 }
467
Benjamin Petersond7b03282008-09-13 15:58:53 +0000468 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300469 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000470 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000471 }
472
473 Py_BEGIN_ALLOW_THREADS
474 rc = sqlite3_finalize(statement);
475 Py_END_ALLOW_THREADS
476 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000477 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000478 }
479
480 }
481
482error:
483 if (PyErr_Occurred()) {
484 return NULL;
485 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200486 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000487 }
488}
489
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100490/*[clinic input]
491_sqlite3.Connection.rollback as pysqlite_connection_rollback
492
493Roll back the current transaction.
494[clinic start generated code]*/
495
496static PyObject *
497pysqlite_connection_rollback_impl(pysqlite_Connection *self)
498/*[clinic end generated code: output=b66fa0d43e7ef305 input=12d4e8d068942830]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000499{
500 int rc;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000501 sqlite3_stmt* statement;
502
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000503 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000504 return NULL;
505 }
506
Berker Peksag59da4b32016-09-12 07:16:43 +0300507 if (!sqlite3_get_autocommit(self->db)) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000508 pysqlite_do_all_statements(self, ACTION_RESET, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000509
510 Py_BEGIN_ALLOW_THREADS
Erlend Egeberg Aasland5e48e832021-02-26 15:30:22 +0100511 rc = sqlite3_prepare_v2(self->db, "ROLLBACK", -1, &statement, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000512 Py_END_ALLOW_THREADS
513 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000514 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000515 goto error;
516 }
517
Benjamin Petersond7b03282008-09-13 15:58:53 +0000518 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300519 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000520 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000521 }
522
523 Py_BEGIN_ALLOW_THREADS
524 rc = sqlite3_finalize(statement);
525 Py_END_ALLOW_THREADS
526 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000527 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000528 }
529
530 }
531
532error:
533 if (PyErr_Occurred()) {
534 return NULL;
535 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200536 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000537 }
538}
539
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200540static int
541_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000542{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200543 if (py_val == Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000544 sqlite3_result_null(context);
Christian Heimes217cfd12007-12-02 14:31:20 +0000545 } else if (PyLong_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200546 sqlite_int64 value = _pysqlite_long_as_int64(py_val);
547 if (value == -1 && PyErr_Occurred())
548 return -1;
549 sqlite3_result_int64(context, value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000550 } else if (PyFloat_Check(py_val)) {
551 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
Guido van Rossumbae07c92007-10-08 02:46:15 +0000552 } else if (PyUnicode_Check(py_val)) {
Miss Islington (bot)2b1e7132021-08-06 10:59:51 -0700553 Py_ssize_t sz;
554 const char *str = PyUnicode_AsUTF8AndSize(py_val, &sz);
555 if (str == NULL) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200556 return -1;
Miss Islington (bot)2b1e7132021-08-06 10:59:51 -0700557 }
558 if (sz > INT_MAX) {
559 PyErr_SetString(PyExc_OverflowError,
560 "string is longer than INT_MAX bytes");
561 return -1;
562 }
563 sqlite3_result_text(context, str, (int)sz, SQLITE_TRANSIENT);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000564 } else if (PyObject_CheckBuffer(py_val)) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200565 Py_buffer view;
566 if (PyObject_GetBuffer(py_val, &view, PyBUF_SIMPLE) != 0) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100567 PyErr_SetString(PyExc_ValueError,
568 "could not convert BLOB to buffer");
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200569 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000570 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200571 if (view.len > INT_MAX) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100572 PyErr_SetString(PyExc_OverflowError,
573 "BLOB longer than INT_MAX bytes");
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200574 PyBuffer_Release(&view);
Victor Stinner83ed42b2013-11-18 01:24:31 +0100575 return -1;
576 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200577 sqlite3_result_blob(context, view.buf, (int)view.len, SQLITE_TRANSIENT);
578 PyBuffer_Release(&view);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000579 } else {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200580 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000581 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200582 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000583}
584
Erlend Egeberg Aaslandbf838a62021-02-21 01:29:19 +0100585static PyObject *
586_pysqlite_build_py_params(sqlite3_context *context, int argc,
587 sqlite3_value **argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000588{
589 PyObject* args;
590 int i;
591 sqlite3_value* cur_value;
592 PyObject* cur_py_value;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000593
594 args = PyTuple_New(argc);
595 if (!args) {
596 return NULL;
597 }
598
599 for (i = 0; i < argc; i++) {
600 cur_value = argv[i];
601 switch (sqlite3_value_type(argv[i])) {
602 case SQLITE_INTEGER:
Sergey Fedoseevb6f5b9d2019-10-23 13:09:01 +0500603 cur_py_value = PyLong_FromLongLong(sqlite3_value_int64(cur_value));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000604 break;
605 case SQLITE_FLOAT:
606 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
607 break;
Miss Islington (bot)067d6d42021-06-04 11:54:39 -0700608 case SQLITE_TEXT: {
609 sqlite3 *db = sqlite3_context_db_handle(context);
610 const char *text = (const char *)sqlite3_value_text(cur_value);
611
612 if (text == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
613 PyErr_NoMemory();
614 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000615 }
Miss Islington (bot)067d6d42021-06-04 11:54:39 -0700616
617 Py_ssize_t size = sqlite3_value_bytes(cur_value);
618 cur_py_value = PyUnicode_FromStringAndSize(text, size);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000619 break;
Miss Islington (bot)067d6d42021-06-04 11:54:39 -0700620 }
Erlend Egeberg Aasland5cb601f2021-04-14 23:09:11 +0200621 case SQLITE_BLOB: {
622 sqlite3 *db = sqlite3_context_db_handle(context);
623 const void *blob = sqlite3_value_blob(cur_value);
624
625 if (blob == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
626 PyErr_NoMemory();
627 goto error;
628 }
629
630 Py_ssize_t size = sqlite3_value_bytes(cur_value);
631 cur_py_value = PyBytes_FromStringAndSize(blob, size);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000632 break;
Erlend Egeberg Aasland5cb601f2021-04-14 23:09:11 +0200633 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000634 case SQLITE_NULL:
635 default:
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +0100636 cur_py_value = Py_NewRef(Py_None);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000637 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000638
639 if (!cur_py_value) {
Erlend Egeberg Aasland5cb601f2021-04-14 23:09:11 +0200640 goto error;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000641 }
642
Erlend Egeberg Aaslande9194ea2021-04-23 13:21:08 +0200643 PyTuple_SET_ITEM(args, i, cur_py_value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000644 }
645
646 return args;
Erlend Egeberg Aasland5cb601f2021-04-14 23:09:11 +0200647
648error:
649 Py_DECREF(args);
650 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000651}
652
Erlend Egeberg Aasland2bb0bf42021-02-19 12:59:24 +0100653static void
654_pysqlite_func_callback(sqlite3_context *context, int argc, sqlite3_value **argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000655{
656 PyObject* args;
657 PyObject* py_func;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000658 PyObject* py_retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200659 int ok;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000660
661 PyGILState_STATE threadstate;
662
663 threadstate = PyGILState_Ensure();
664
665 py_func = (PyObject*)sqlite3_user_data(context);
666
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000667 args = _pysqlite_build_py_params(context, argc, argv);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000668 if (args) {
669 py_retval = PyObject_CallObject(py_func, args);
670 Py_DECREF(args);
671 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000672
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200673 ok = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000674 if (py_retval) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200675 ok = _pysqlite_set_result(context, py_retval) == 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000676 Py_DECREF(py_retval);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200677 }
678 if (!ok) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700679 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000680 PyErr_Print();
681 } else {
682 PyErr_Clear();
683 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200684 sqlite3_result_error(context, "user-defined function raised exception", -1);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000685 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000686
687 PyGILState_Release(threadstate);
688}
689
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000690static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000691{
692 PyObject* args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000693 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694 PyObject* aggregate_class;
695 PyObject** aggregate_instance;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000696 PyObject* stepmethod = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000697
698 PyGILState_STATE threadstate;
699
700 threadstate = PyGILState_Ensure();
701
702 aggregate_class = (PyObject*)sqlite3_user_data(context);
703
704 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
705
Serhiy Storchaka0b3ec192017-03-23 17:53:47 +0200706 if (*aggregate_instance == NULL) {
Victor Stinner070c4d72016-12-09 12:29:18 +0100707 *aggregate_instance = _PyObject_CallNoArg(aggregate_class);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000708
Thomas Wouters477c8d52006-05-27 19:21:47 +0000709 if (PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000710 *aggregate_instance = 0;
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700711 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000712 PyErr_Print();
713 } else {
714 PyErr_Clear();
715 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200716 sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000718 }
719 }
720
721 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000722 if (!stepmethod) {
723 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000724 }
725
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000726 args = _pysqlite_build_py_params(context, argc, params);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000727 if (!args) {
728 goto error;
729 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000730
731 function_result = PyObject_CallObject(stepmethod, args);
732 Py_DECREF(args);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000733
Thomas Wouters477c8d52006-05-27 19:21:47 +0000734 if (!function_result) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700735 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000736 PyErr_Print();
737 } else {
738 PyErr_Clear();
739 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200740 sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000741 }
742
Thomas Wouters477c8d52006-05-27 19:21:47 +0000743error:
744 Py_XDECREF(stepmethod);
745 Py_XDECREF(function_result);
746
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000747 PyGILState_Release(threadstate);
748}
749
Erlend Egeberg Aasland2bb0bf42021-02-19 12:59:24 +0100750static void
751_pysqlite_final_callback(sqlite3_context *context)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000752{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200753 PyObject* function_result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000754 PyObject** aggregate_instance;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200755 _Py_IDENTIFIER(finalize);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200756 int ok;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200757 PyObject *exception, *value, *tb;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000758
759 PyGILState_STATE threadstate;
760
761 threadstate = PyGILState_Ensure();
762
Erlend Egeberg Aasland979b23c2021-02-19 12:20:32 +0100763 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, 0);
764 if (aggregate_instance == NULL) {
765 /* No rows matched the query; the step handler was never called. */
766 goto error;
767 }
768 else if (!*aggregate_instance) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000769 /* this branch is executed if there was an exception in the aggregate's
770 * __init__ */
771
Thomas Wouters477c8d52006-05-27 19:21:47 +0000772 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000773 }
774
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200775 /* Keep the exception (if any) of the last call to step() */
776 PyErr_Fetch(&exception, &value, &tb);
777
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200778 function_result = _PyObject_CallMethodIdNoArgs(*aggregate_instance, &PyId_finalize);
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200779
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200780 Py_DECREF(*aggregate_instance);
781
782 ok = 0;
783 if (function_result) {
784 ok = _pysqlite_set_result(context, function_result) == 0;
785 Py_DECREF(function_result);
786 }
787 if (!ok) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700788 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000789 PyErr_Print();
790 } else {
791 PyErr_Clear();
792 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200793 sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000794 }
795
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200796 /* Restore the exception (if any) of the last call to step(),
797 but clear also the current exception if finalize() failed */
798 PyErr_Restore(exception, value, tb);
Victor Stinner3a857322013-07-22 08:34:32 +0200799
Thomas Wouters477c8d52006-05-27 19:21:47 +0000800error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000801 PyGILState_Release(threadstate);
802}
803
Gerhard Häringf9cee222010-03-05 15:20:03 +0000804static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805{
806 PyObject* new_list;
807 PyObject* weakref;
808 int i;
809
810 /* we only need to do this once in a while */
811 if (self->created_statements++ < 200) {
812 return;
813 }
814
815 self->created_statements = 0;
816
817 new_list = PyList_New(0);
818 if (!new_list) {
819 return;
820 }
821
822 for (i = 0; i < PyList_Size(self->statements); i++) {
823 weakref = PyList_GetItem(self->statements, i);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000824 if (PyWeakref_GetObject(weakref) != Py_None) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000825 if (PyList_Append(new_list, weakref) != 0) {
826 Py_DECREF(new_list);
827 return;
828 }
829 }
830 }
831
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300832 Py_SETREF(self->statements, new_list);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000833}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000834
Gerhard Häringf9cee222010-03-05 15:20:03 +0000835static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
836{
837 PyObject* new_list;
838 PyObject* weakref;
839 int i;
840
841 /* we only need to do this once in a while */
842 if (self->created_cursors++ < 200) {
843 return;
844 }
845
846 self->created_cursors = 0;
847
848 new_list = PyList_New(0);
849 if (!new_list) {
850 return;
851 }
852
853 for (i = 0; i < PyList_Size(self->cursors); i++) {
854 weakref = PyList_GetItem(self->cursors, i);
855 if (PyWeakref_GetObject(weakref) != Py_None) {
856 if (PyList_Append(new_list, weakref) != 0) {
857 Py_DECREF(new_list);
858 return;
859 }
860 }
861 }
862
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300863 Py_SETREF(self->cursors, new_list);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000864}
865
gescheitb9a03762019-07-13 06:15:49 +0300866static void _destructor(void* args)
867{
Miss Islington (bot)317e9ed2021-06-05 16:13:27 -0700868 // This function may be called without the GIL held, so we need to ensure
869 // that we destroy 'args' with the GIL
870 PyGILState_STATE gstate;
871 gstate = PyGILState_Ensure();
gescheitb9a03762019-07-13 06:15:49 +0300872 Py_DECREF((PyObject*)args);
Miss Islington (bot)317e9ed2021-06-05 16:13:27 -0700873 PyGILState_Release(gstate);
gescheitb9a03762019-07-13 06:15:49 +0300874}
875
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100876/*[clinic input]
877_sqlite3.Connection.create_function as pysqlite_connection_create_function
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000878
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100879 name: str
880 narg: int
881 func: object
882 *
883 deterministic: bool = False
884
885Creates a new function. Non-standard.
886[clinic start generated code]*/
887
888static PyObject *
889pysqlite_connection_create_function_impl(pysqlite_Connection *self,
890 const char *name, int narg,
891 PyObject *func, int deterministic)
892/*[clinic end generated code: output=07d1877dd98c0308 input=f2edcf073e815beb]*/
893{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000894 int rc;
Sergey Fedoseev08308582018-07-08 12:09:20 +0500895 int flags = SQLITE_UTF8;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000896
Gerhard Häringf9cee222010-03-05 15:20:03 +0000897 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
898 return NULL;
899 }
900
Sergey Fedoseev08308582018-07-08 12:09:20 +0500901 if (deterministic) {
902#if SQLITE_VERSION_NUMBER < 3008003
903 PyErr_SetString(pysqlite_NotSupportedError,
904 "deterministic=True requires SQLite 3.8.3 or higher");
905 return NULL;
906#else
907 if (sqlite3_libversion_number() < 3008003) {
908 PyErr_SetString(pysqlite_NotSupportedError,
909 "deterministic=True requires SQLite 3.8.3 or higher");
910 return NULL;
911 }
912 flags |= SQLITE_DETERMINISTIC;
913#endif
914 }
gescheitb9a03762019-07-13 06:15:49 +0300915 rc = sqlite3_create_function_v2(self->db,
916 name,
917 narg,
918 flags,
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +0100919 (void*)Py_NewRef(func),
gescheitb9a03762019-07-13 06:15:49 +0300920 _pysqlite_func_callback,
921 NULL,
922 NULL,
923 &_destructor); // will decref func
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000924
Thomas Wouters477c8d52006-05-27 19:21:47 +0000925 if (rc != SQLITE_OK) {
926 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000927 PyErr_SetString(pysqlite_OperationalError, "Error creating function");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000928 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000929 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +0500930 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000931}
932
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100933/*[clinic input]
934_sqlite3.Connection.create_aggregate as pysqlite_connection_create_aggregate
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000935
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100936 name: str
937 n_arg: int
938 aggregate_class: object
939
940Creates a new aggregate. Non-standard.
941[clinic start generated code]*/
942
943static PyObject *
944pysqlite_connection_create_aggregate_impl(pysqlite_Connection *self,
945 const char *name, int n_arg,
946 PyObject *aggregate_class)
947/*[clinic end generated code: output=fbb2f858cfa4d8db input=c2e13bbf234500a5]*/
948{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000949 int rc;
950
Gerhard Häringf9cee222010-03-05 15:20:03 +0000951 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
952 return NULL;
953 }
954
gescheitb9a03762019-07-13 06:15:49 +0300955 rc = sqlite3_create_function_v2(self->db,
956 name,
957 n_arg,
958 SQLITE_UTF8,
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +0100959 (void*)Py_NewRef(aggregate_class),
gescheitb9a03762019-07-13 06:15:49 +0300960 0,
961 &_pysqlite_step_callback,
962 &_pysqlite_final_callback,
963 &_destructor); // will decref func
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000964 if (rc != SQLITE_OK) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000965 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000966 PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000967 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000968 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +0500969 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000970}
971
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000972static 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 +0000973{
974 PyObject *ret;
975 int rc;
976 PyGILState_STATE gilstate;
977
978 gilstate = PyGILState_Ensure();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000979
Victor Stinnerd4095d92013-07-26 22:23:33 +0200980 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000981
Victor Stinnerd4095d92013-07-26 22:23:33 +0200982 if (ret == NULL) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700983 if (_pysqlite_enable_callback_tracebacks)
Victor Stinnerd4095d92013-07-26 22:23:33 +0200984 PyErr_Print();
985 else
986 PyErr_Clear();
Victor Stinner41801f52013-07-21 13:05:38 +0200987
Victor Stinnerd4095d92013-07-26 22:23:33 +0200988 rc = SQLITE_DENY;
Victor Stinner41801f52013-07-21 13:05:38 +0200989 }
990 else {
Victor Stinnerd4095d92013-07-26 22:23:33 +0200991 if (PyLong_Check(ret)) {
992 rc = _PyLong_AsInt(ret);
993 if (rc == -1 && PyErr_Occurred()) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700994 if (_pysqlite_enable_callback_tracebacks)
Victor Stinnerd4095d92013-07-26 22:23:33 +0200995 PyErr_Print();
996 else
997 PyErr_Clear();
998 rc = SQLITE_DENY;
999 }
1000 }
1001 else {
1002 rc = SQLITE_DENY;
1003 }
1004 Py_DECREF(ret);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001005 }
1006
1007 PyGILState_Release(gilstate);
1008 return rc;
1009}
1010
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001011static int _progress_handler(void* user_arg)
1012{
1013 int rc;
1014 PyObject *ret;
1015 PyGILState_STATE gilstate;
1016
1017 gilstate = PyGILState_Ensure();
Victor Stinner070c4d72016-12-09 12:29:18 +01001018 ret = _PyObject_CallNoArg((PyObject*)user_arg);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001019
1020 if (!ret) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -07001021 if (_pysqlite_enable_callback_tracebacks) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001022 PyErr_Print();
1023 } else {
1024 PyErr_Clear();
1025 }
1026
Mark Dickinson934896d2009-02-21 20:59:32 +00001027 /* abort query if error occurred */
Victor Stinner86999502010-05-19 01:27:23 +00001028 rc = 1;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001029 } else {
1030 rc = (int)PyObject_IsTrue(ret);
1031 Py_DECREF(ret);
1032 }
1033
1034 PyGILState_Release(gilstate);
1035 return rc;
1036}
1037
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001038#ifdef HAVE_TRACE_V2
1039/*
1040 * From https://sqlite.org/c3ref/trace_v2.html:
1041 * The integer return value from the callback is currently ignored, though this
1042 * may change in future releases. Callback implementations should return zero
1043 * to ensure future compatibility.
1044 */
1045static int _trace_callback(unsigned int type, void* user_arg, void* prepared_statement, void* statement_string)
1046#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001047static void _trace_callback(void* user_arg, const char* statement_string)
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001048#endif
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001049{
1050 PyObject *py_statement = NULL;
1051 PyObject *ret = NULL;
1052
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001053 PyGILState_STATE gilstate;
1054
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001055#ifdef HAVE_TRACE_V2
1056 if (type != SQLITE_TRACE_STMT) {
1057 return 0;
1058 }
1059#endif
1060
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001061 gilstate = PyGILState_Ensure();
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001062 py_statement = PyUnicode_DecodeUTF8(statement_string,
1063 strlen(statement_string), "replace");
1064 if (py_statement) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001065 ret = PyObject_CallOneArg((PyObject*)user_arg, py_statement);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001066 Py_DECREF(py_statement);
1067 }
1068
1069 if (ret) {
1070 Py_DECREF(ret);
1071 } else {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -07001072 if (_pysqlite_enable_callback_tracebacks) {
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001073 PyErr_Print();
1074 } else {
1075 PyErr_Clear();
1076 }
1077 }
1078
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001079 PyGILState_Release(gilstate);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001080#ifdef HAVE_TRACE_V2
1081 return 0;
1082#endif
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001083}
1084
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001085/*[clinic input]
1086_sqlite3.Connection.set_authorizer as pysqlite_connection_set_authorizer
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001087
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001088 authorizer_callback as authorizer_cb: object
1089
1090Sets authorizer callback. Non-standard.
1091[clinic start generated code]*/
1092
1093static PyObject *
1094pysqlite_connection_set_authorizer_impl(pysqlite_Connection *self,
1095 PyObject *authorizer_cb)
1096/*[clinic end generated code: output=f18ba575d788b35c input=df079724c020d2f2]*/
1097{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001098 int rc;
1099
Gerhard Häringf9cee222010-03-05 15:20:03 +00001100 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1101 return NULL;
1102 }
1103
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001104 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001105 if (rc != SQLITE_OK) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001106 PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
gescheitb9a03762019-07-13 06:15:49 +03001107 Py_XSETREF(self->function_pinboard_authorizer_cb, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001108 return NULL;
gescheitb9a03762019-07-13 06:15:49 +03001109 } else {
1110 Py_INCREF(authorizer_cb);
1111 Py_XSETREF(self->function_pinboard_authorizer_cb, authorizer_cb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001112 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +05001113 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001114}
1115
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001116/*[clinic input]
1117_sqlite3.Connection.set_progress_handler as pysqlite_connection_set_progress_handler
1118
1119 progress_handler: object
1120 n: int
1121
1122Sets progress handler callback. Non-standard.
1123[clinic start generated code]*/
1124
1125static PyObject *
1126pysqlite_connection_set_progress_handler_impl(pysqlite_Connection *self,
1127 PyObject *progress_handler,
1128 int n)
1129/*[clinic end generated code: output=35a7c10364cb1b04 input=857696c25f964c64]*/
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001130{
Gerhard Häringf9cee222010-03-05 15:20:03 +00001131 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1132 return NULL;
1133 }
1134
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001135 if (progress_handler == Py_None) {
1136 /* None clears the progress handler previously set */
1137 sqlite3_progress_handler(self->db, 0, 0, (void*)0);
gescheitb9a03762019-07-13 06:15:49 +03001138 Py_XSETREF(self->function_pinboard_progress_handler, NULL);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001139 } else {
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +05001140 sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
gescheitb9a03762019-07-13 06:15:49 +03001141 Py_INCREF(progress_handler);
1142 Py_XSETREF(self->function_pinboard_progress_handler, progress_handler);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001143 }
Berker Peksagfe21de92016-04-09 07:34:39 +03001144 Py_RETURN_NONE;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001145}
1146
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001147/*[clinic input]
1148_sqlite3.Connection.set_trace_callback as pysqlite_connection_set_trace_callback
1149
1150 trace_callback: object
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001151
1152Sets a trace callback called for each SQL statement (passed as unicode).
1153
1154Non-standard.
1155[clinic start generated code]*/
1156
1157static PyObject *
Dong-hee Na21793492020-12-19 00:41:33 +09001158pysqlite_connection_set_trace_callback_impl(pysqlite_Connection *self,
1159 PyObject *trace_callback)
1160/*[clinic end generated code: output=fb0e307b9924d454 input=56d60fd38d763679]*/
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001161{
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001162 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1163 return NULL;
1164 }
1165
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001166 if (trace_callback == Py_None) {
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001167 /*
1168 * None clears the trace callback previously set
1169 *
1170 * Ref.
1171 * - https://sqlite.org/c3ref/c_trace.html
1172 * - https://sqlite.org/c3ref/trace_v2.html
1173 */
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001174#ifdef HAVE_TRACE_V2
1175 sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, 0, 0);
1176#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001177 sqlite3_trace(self->db, 0, (void*)0);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001178#endif
gescheitb9a03762019-07-13 06:15:49 +03001179 Py_XSETREF(self->function_pinboard_trace_callback, NULL);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001180 } else {
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001181#ifdef HAVE_TRACE_V2
1182 sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, _trace_callback, trace_callback);
1183#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001184 sqlite3_trace(self->db, _trace_callback, trace_callback);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001185#endif
gescheitb9a03762019-07-13 06:15:49 +03001186 Py_INCREF(trace_callback);
1187 Py_XSETREF(self->function_pinboard_trace_callback, trace_callback);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001188 }
1189
Berker Peksagfe21de92016-04-09 07:34:39 +03001190 Py_RETURN_NONE;
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001191}
1192
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +02001193#ifndef SQLITE_OMIT_LOAD_EXTENSION
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001194/*[clinic input]
1195_sqlite3.Connection.enable_load_extension as pysqlite_connection_enable_load_extension
1196
Dong-hee Na21793492020-12-19 00:41:33 +09001197 enable as onoff: bool(accept={int})
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001198 /
1199
1200Enable dynamic loading of SQLite extension modules. Non-standard.
1201[clinic start generated code]*/
1202
1203static PyObject *
1204pysqlite_connection_enable_load_extension_impl(pysqlite_Connection *self,
1205 int onoff)
Dong-hee Na21793492020-12-19 00:41:33 +09001206/*[clinic end generated code: output=9cac37190d388baf input=5c0da5b121121cbc]*/
Gerhard Häringf9cee222010-03-05 15:20:03 +00001207{
1208 int rc;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001209
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +02001210 if (PySys_Audit("sqlite3.enable_load_extension",
1211 "OO", self, onoff ? Py_True : Py_False) < 0) {
1212 return NULL;
1213 }
1214
Gerhard Häringf9cee222010-03-05 15:20:03 +00001215 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1216 return NULL;
1217 }
1218
Gerhard Häringf9cee222010-03-05 15:20:03 +00001219 rc = sqlite3_enable_load_extension(self->db, onoff);
1220
1221 if (rc != SQLITE_OK) {
1222 PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
1223 return NULL;
1224 } else {
Berker Peksagfe21de92016-04-09 07:34:39 +03001225 Py_RETURN_NONE;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001226 }
1227}
1228
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001229/*[clinic input]
1230_sqlite3.Connection.load_extension as pysqlite_connection_load_extension
1231
1232 name as extension_name: str
1233 /
1234
1235Load SQLite extension module. Non-standard.
1236[clinic start generated code]*/
1237
1238static PyObject *
1239pysqlite_connection_load_extension_impl(pysqlite_Connection *self,
1240 const char *extension_name)
1241/*[clinic end generated code: output=47eb1d7312bc97a7 input=0b711574560db9fc]*/
Gerhard Häringf9cee222010-03-05 15:20:03 +00001242{
1243 int rc;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001244 char* errmsg;
1245
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +02001246 if (PySys_Audit("sqlite3.load_extension", "Os", self, extension_name) < 0) {
1247 return NULL;
1248 }
1249
Gerhard Häringf9cee222010-03-05 15:20:03 +00001250 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1251 return NULL;
1252 }
1253
Gerhard Häringf9cee222010-03-05 15:20:03 +00001254 rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1255 if (rc != 0) {
1256 PyErr_SetString(pysqlite_OperationalError, errmsg);
1257 return NULL;
1258 } else {
Berker Peksagfe21de92016-04-09 07:34:39 +03001259 Py_RETURN_NONE;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001260 }
1261}
1262#endif
1263
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001264int pysqlite_check_thread(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001265{
1266 if (self->check_same_thread) {
1267 if (PyThread_get_thread_ident() != self->thread_ident) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001268 PyErr_Format(pysqlite_ProgrammingError,
Takuya Akiba030345c2018-03-27 00:14:00 +09001269 "SQLite objects created in a thread can only be used in that same thread. "
1270 "The object was created in thread id %lu and this is thread id %lu.",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001271 self->thread_ident, PyThread_get_thread_ident());
1272 return 0;
1273 }
1274
1275 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001276 return 1;
1277}
1278
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001279static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001280{
Erlend Egeberg Aasland0cb470e2021-07-30 14:01:22 +02001281 if (!pysqlite_check_connection(self)) {
1282 return NULL;
1283 }
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +01001284 return Py_NewRef(self->isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001285}
1286
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001287static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001288{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001289 if (!pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001290 return NULL;
1291 } else {
1292 return Py_BuildValue("i", sqlite3_total_changes(self->db));
1293 }
1294}
1295
Berker Peksag59da4b32016-09-12 07:16:43 +03001296static PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
1297{
1298 if (!pysqlite_check_connection(self)) {
1299 return NULL;
1300 }
1301 if (!sqlite3_get_autocommit(self->db)) {
1302 Py_RETURN_TRUE;
1303 }
1304 Py_RETURN_FALSE;
1305}
1306
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +02001307static int
1308pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001309{
Zackery Spytz842acaa2018-12-17 07:52:45 -07001310 if (isolation_level == NULL) {
1311 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
1312 return -1;
1313 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001314 if (isolation_level == Py_None) {
Erlend Egeberg Aasland0cb470e2021-07-30 14:01:22 +02001315 /* We might get called during connection init, so we cannot use
1316 * pysqlite_connection_commit() here. */
1317 if (self->db && !sqlite3_get_autocommit(self->db)) {
1318 int rc;
1319 Py_BEGIN_ALLOW_THREADS
1320 rc = sqlite3_exec(self->db, "COMMIT", NULL, NULL, NULL);
1321 Py_END_ALLOW_THREADS
1322 if (rc != SQLITE_OK) {
1323 return _pysqlite_seterror(self->db, NULL);
1324 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001325 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001326
Serhiy Storchaka28914922016-09-01 22:18:03 +03001327 self->begin_statement = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001328 } else {
Serhiy Storchaka28914922016-09-01 22:18:03 +03001329 const char * const *candidate;
1330 PyObject *uppercase_level;
1331 _Py_IDENTIFIER(upper);
Neal Norwitzefee9f52007-10-27 02:50:52 +00001332
Serhiy Storchaka28914922016-09-01 22:18:03 +03001333 if (!PyUnicode_Check(isolation_level)) {
1334 PyErr_Format(PyExc_TypeError,
1335 "isolation_level must be a string or None, not %.100s",
1336 Py_TYPE(isolation_level)->tp_name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001337 return -1;
1338 }
1339
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001340 uppercase_level = _PyObject_CallMethodIdOneArg(
Serhiy Storchaka28914922016-09-01 22:18:03 +03001341 (PyObject *)&PyUnicode_Type, &PyId_upper,
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001342 isolation_level);
Serhiy Storchaka28914922016-09-01 22:18:03 +03001343 if (!uppercase_level) {
Georg Brandl3dbca812008-07-23 16:10:53 +00001344 return -1;
1345 }
Serhiy Storchaka28914922016-09-01 22:18:03 +03001346 for (candidate = begin_statements; *candidate; candidate++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001347 if (_PyUnicode_EqualToASCIIString(uppercase_level, *candidate + 6))
Serhiy Storchaka28914922016-09-01 22:18:03 +03001348 break;
1349 }
1350 Py_DECREF(uppercase_level);
1351 if (!*candidate) {
1352 PyErr_SetString(PyExc_ValueError,
1353 "invalid value for isolation_level");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001354 return -1;
1355 }
Serhiy Storchaka28914922016-09-01 22:18:03 +03001356 self->begin_statement = *candidate;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001357 }
1358
Serhiy Storchaka28914922016-09-01 22:18:03 +03001359 Py_INCREF(isolation_level);
1360 Py_XSETREF(self->isolation_level, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001361 return 0;
1362}
1363
Erlend Egeberg Aaslandbf838a62021-02-21 01:29:19 +01001364static PyObject *
1365pysqlite_connection_call(pysqlite_Connection *self, PyObject *args,
1366 PyObject *kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001367{
1368 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001369 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001370 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001371
Gerhard Häringf9cee222010-03-05 15:20:03 +00001372 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1373 return NULL;
1374 }
1375
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001376 if (!_PyArg_NoKeywords(MODULE_NAME ".Connection", kwargs))
Larry Hastings3b12e952015-05-08 07:45:10 -07001377 return NULL;
1378
Victor Stinnerc6a23202019-06-26 03:16:24 +02001379 if (!PyArg_ParseTuple(args, "U", &sql))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001380 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001381
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001382 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001383
Erlend Egeberg Aasland84d80f52021-06-03 18:38:09 +02001384 statement = pysqlite_statement_create(self, sql);
1385 if (statement == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001386 return NULL;
1387 }
1388
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001389 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
1390 if (weakref == NULL)
1391 goto error;
1392 if (PyList_Append(self->statements, weakref) != 0) {
1393 Py_DECREF(weakref);
1394 goto error;
1395 }
1396 Py_DECREF(weakref);
1397
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001398 return (PyObject*)statement;
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001399
1400error:
1401 Py_DECREF(statement);
1402 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001403}
1404
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001405/*[clinic input]
1406_sqlite3.Connection.execute as pysqlite_connection_execute
1407
1408 sql: unicode
1409 parameters: object = NULL
1410 /
1411
1412Executes a SQL statement. Non-standard.
1413[clinic start generated code]*/
1414
1415static PyObject *
1416pysqlite_connection_execute_impl(pysqlite_Connection *self, PyObject *sql,
1417 PyObject *parameters)
1418/*[clinic end generated code: output=5be05ae01ee17ee4 input=fbd17c75c7140271]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001419{
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001420 _Py_IDENTIFIER(execute);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001421 PyObject* cursor = 0;
1422 PyObject* result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001423
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001424 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001425 if (!cursor) {
1426 goto error;
1427 }
1428
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001429 result = _PyObject_CallMethodIdObjArgs(cursor, &PyId_execute, sql, parameters, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001430 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001431 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001432 }
1433
1434error:
1435 Py_XDECREF(result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001436
1437 return cursor;
1438}
1439
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001440/*[clinic input]
1441_sqlite3.Connection.executemany as pysqlite_connection_executemany
1442
1443 sql: unicode
1444 parameters: object
1445 /
1446
1447Repeatedly executes a SQL statement. Non-standard.
1448[clinic start generated code]*/
1449
1450static PyObject *
1451pysqlite_connection_executemany_impl(pysqlite_Connection *self,
1452 PyObject *sql, PyObject *parameters)
1453/*[clinic end generated code: output=776cd2fd20bfe71f input=4feab80659ffc82b]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001454{
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001455 _Py_IDENTIFIER(executemany);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001456 PyObject* cursor = 0;
1457 PyObject* result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001458
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001459 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001460 if (!cursor) {
1461 goto error;
1462 }
1463
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001464 result = _PyObject_CallMethodIdObjArgs(cursor, &PyId_executemany, sql,
1465 parameters, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001466 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001467 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001468 }
1469
1470error:
1471 Py_XDECREF(result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001472
1473 return cursor;
1474}
1475
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001476/*[clinic input]
1477_sqlite3.Connection.executescript as pysqlite_connection_executescript
1478
1479 sql_script as script_obj: object
1480 /
1481
Erlend Egeberg Aasland02e4c0c2021-07-15 01:02:01 +02001482Executes multiple SQL statements at once. Non-standard.
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001483[clinic start generated code]*/
1484
1485static PyObject *
1486pysqlite_connection_executescript(pysqlite_Connection *self,
1487 PyObject *script_obj)
Erlend Egeberg Aasland02e4c0c2021-07-15 01:02:01 +02001488/*[clinic end generated code: output=4c4f9d77aa0ae37d input=b27ae5c24ffb8b43]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001489{
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001490 _Py_IDENTIFIER(executescript);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001491 PyObject* cursor = 0;
1492 PyObject* result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001493
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001494 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001495 if (!cursor) {
1496 goto error;
1497 }
1498
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001499 result = _PyObject_CallMethodIdObjArgs(cursor, &PyId_executescript,
1500 script_obj, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001501 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001502 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001503 }
1504
1505error:
1506 Py_XDECREF(result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001507
1508 return cursor;
1509}
1510
1511/* ------------------------- COLLATION CODE ------------------------ */
1512
1513static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001514pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001515 void* context,
1516 int text1_length, const void* text1_data,
1517 int text2_length, const void* text2_data)
1518{
1519 PyObject* callback = (PyObject*)context;
1520 PyObject* string1 = 0;
1521 PyObject* string2 = 0;
1522 PyGILState_STATE gilstate;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001523 PyObject* retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001524 long longval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001525 int result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001526 gilstate = PyGILState_Ensure();
1527
1528 if (PyErr_Occurred()) {
1529 goto finally;
1530 }
1531
Guido van Rossum98297ee2007-11-06 21:34:58 +00001532 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1533 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001534
1535 if (!string1 || !string2) {
1536 goto finally; /* failed to allocate strings */
1537 }
1538
1539 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1540
1541 if (!retval) {
1542 /* execution failed */
1543 goto finally;
1544 }
1545
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001546 longval = PyLong_AsLongAndOverflow(retval, &result);
1547 if (longval == -1 && PyErr_Occurred()) {
1548 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001549 result = 0;
1550 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001551 else if (!result) {
1552 if (longval > 0)
1553 result = 1;
1554 else if (longval < 0)
1555 result = -1;
1556 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001557
1558finally:
1559 Py_XDECREF(string1);
1560 Py_XDECREF(string2);
1561 Py_XDECREF(retval);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001562 PyGILState_Release(gilstate);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001563 return result;
1564}
1565
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001566/*[clinic input]
1567_sqlite3.Connection.interrupt as pysqlite_connection_interrupt
1568
1569Abort any pending database operation. Non-standard.
1570[clinic start generated code]*/
1571
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001572static PyObject *
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001573pysqlite_connection_interrupt_impl(pysqlite_Connection *self)
1574/*[clinic end generated code: output=f193204bc9e70b47 input=4bd0ad083cf93aa7]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001575{
1576 PyObject* retval = NULL;
1577
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001578 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001579 goto finally;
1580 }
1581
1582 sqlite3_interrupt(self->db);
1583
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +01001584 retval = Py_NewRef(Py_None);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001585
1586finally:
1587 return retval;
1588}
1589
Christian Heimesbbe741d2008-03-28 10:53:29 +00001590/* Function author: Paul Kippes <kippesp@gmail.com>
1591 * Class method of Connection to call the Python function _iterdump
1592 * of the sqlite3 module.
1593 */
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001594/*[clinic input]
1595_sqlite3.Connection.iterdump as pysqlite_connection_iterdump
1596
1597Returns iterator to the dump of the database in an SQL text format.
1598
1599Non-standard.
1600[clinic start generated code]*/
1601
Christian Heimesbbe741d2008-03-28 10:53:29 +00001602static PyObject *
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001603pysqlite_connection_iterdump_impl(pysqlite_Connection *self)
1604/*[clinic end generated code: output=586997aaf9808768 input=53bc907cb5eedb85]*/
Christian Heimesbbe741d2008-03-28 10:53:29 +00001605{
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001606 _Py_IDENTIFIER(_iterdump);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001607 PyObject* retval = NULL;
1608 PyObject* module = NULL;
1609 PyObject* module_dict;
1610 PyObject* pyfn_iterdump;
1611
1612 if (!pysqlite_check_connection(self)) {
1613 goto finally;
1614 }
1615
1616 module = PyImport_ImportModule(MODULE_NAME ".dump");
1617 if (!module) {
1618 goto finally;
1619 }
1620
1621 module_dict = PyModule_GetDict(module);
1622 if (!module_dict) {
1623 goto finally;
1624 }
1625
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001626 pyfn_iterdump = _PyDict_GetItemIdWithError(module_dict, &PyId__iterdump);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001627 if (!pyfn_iterdump) {
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001628 if (!PyErr_Occurred()) {
1629 PyErr_SetString(pysqlite_OperationalError,
1630 "Failed to obtain _iterdump() reference");
1631 }
Christian Heimesbbe741d2008-03-28 10:53:29 +00001632 goto finally;
1633 }
1634
Petr Viktorinffd97532020-02-11 17:46:57 +01001635 retval = PyObject_CallOneArg(pyfn_iterdump, (PyObject *)self);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001636
1637finally:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001638 Py_XDECREF(module);
1639 return retval;
1640}
1641
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001642/*[clinic input]
1643_sqlite3.Connection.backup as pysqlite_connection_backup
1644
Erlend Egeberg Aaslandea465792021-02-11 00:04:02 +01001645 target: object(type='pysqlite_Connection *', subclass_of='pysqlite_ConnectionType')
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001646 *
1647 pages: int = -1
1648 progress: object = None
1649 name: str = "main"
1650 sleep: double = 0.250
1651
1652Makes a backup of the database. Non-standard.
1653[clinic start generated code]*/
1654
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001655static PyObject *
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001656pysqlite_connection_backup_impl(pysqlite_Connection *self,
1657 pysqlite_Connection *target, int pages,
1658 PyObject *progress, const char *name,
1659 double sleep)
Erlend Egeberg Aaslandea465792021-02-11 00:04:02 +01001660/*[clinic end generated code: output=306a3e6a38c36334 input=30ae45fc420bfd3b]*/
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001661{
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001662 int rc;
Pablo Galindoa6d63a22020-12-29 00:28:09 +00001663 int sleep_ms = (int)(sleep * 1000.0);
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001664 sqlite3 *bck_conn;
1665 sqlite3_backup *bck_handle;
Victor Stinnerca405012018-04-30 12:22:17 +02001666
Peter McCormickbfee9fa2020-09-19 23:40:46 -04001667 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1668 return NULL;
1669 }
1670
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001671 if (!pysqlite_check_connection(target)) {
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001672 return NULL;
1673 }
1674
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001675 if (target == self) {
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001676 PyErr_SetString(PyExc_ValueError, "target cannot be the same connection instance");
1677 return NULL;
1678 }
1679
Aviv Palivodabbf7bb72018-03-18 02:48:55 +02001680#if SQLITE_VERSION_NUMBER < 3008008
1681 /* Since 3.8.8 this is already done, per commit
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001682 https://www.sqlite.org/src/info/169b5505498c0a7e */
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001683 if (!sqlite3_get_autocommit(target->db)) {
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001684 PyErr_SetString(pysqlite_OperationalError, "target is in transaction");
1685 return NULL;
1686 }
1687#endif
1688
1689 if (progress != Py_None && !PyCallable_Check(progress)) {
1690 PyErr_SetString(PyExc_TypeError, "progress argument must be a callable");
1691 return NULL;
1692 }
1693
1694 if (pages == 0) {
1695 pages = -1;
1696 }
1697
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001698 bck_conn = target->db;
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001699
1700 Py_BEGIN_ALLOW_THREADS
1701 bck_handle = sqlite3_backup_init(bck_conn, "main", self->db, name);
1702 Py_END_ALLOW_THREADS
1703
Erlend Egeberg Aaslandc1ae7412021-04-14 13:45:49 +02001704 if (bck_handle == NULL) {
1705 _pysqlite_seterror(bck_conn, NULL);
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001706 return NULL;
1707 }
Erlend Egeberg Aaslandc1ae7412021-04-14 13:45:49 +02001708
1709 do {
1710 Py_BEGIN_ALLOW_THREADS
1711 rc = sqlite3_backup_step(bck_handle, pages);
1712 Py_END_ALLOW_THREADS
1713
1714 if (progress != Py_None) {
1715 int remaining = sqlite3_backup_remaining(bck_handle);
1716 int pagecount = sqlite3_backup_pagecount(bck_handle);
1717 PyObject *res = PyObject_CallFunction(progress, "iii", rc,
1718 remaining, pagecount);
1719 if (res == NULL) {
1720 /* Callback failed: abort backup and bail. */
1721 Py_BEGIN_ALLOW_THREADS
1722 sqlite3_backup_finish(bck_handle);
1723 Py_END_ALLOW_THREADS
1724 return NULL;
1725 }
1726 Py_DECREF(res);
1727 }
1728
1729 /* Sleep for a while if there are still further pages to copy and
1730 the engine could not make any progress */
1731 if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) {
1732 Py_BEGIN_ALLOW_THREADS
1733 sqlite3_sleep(sleep_ms);
1734 Py_END_ALLOW_THREADS
1735 }
1736 } while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);
1737
1738 Py_BEGIN_ALLOW_THREADS
1739 rc = sqlite3_backup_finish(bck_handle);
1740 Py_END_ALLOW_THREADS
1741
1742 if (rc != SQLITE_OK) {
1743 _pysqlite_seterror(bck_conn, NULL);
1744 return NULL;
1745 }
1746
1747 Py_RETURN_NONE;
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001748}
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001749
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001750/*[clinic input]
1751_sqlite3.Connection.create_collation as pysqlite_connection_create_collation
1752
1753 name: unicode
1754 callback as callable: object
1755 /
1756
1757Creates a collation function. Non-standard.
1758[clinic start generated code]*/
1759
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001760static PyObject *
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001761pysqlite_connection_create_collation_impl(pysqlite_Connection *self,
1762 PyObject *name, PyObject *callable)
1763/*[clinic end generated code: output=0f63b8995565ae22 input=5c3898813a776cf2]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001764{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001765 PyObject* uppercase_name = 0;
Victor Stinner35466c52010-04-22 11:23:23 +00001766 Py_ssize_t i, len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001767 _Py_IDENTIFIER(upper);
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001768 const char *uppercase_name_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001769 int rc;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001770 unsigned int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001771 const void *data;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001772
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001773 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001774 goto finally;
1775 }
1776
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001777 uppercase_name = _PyObject_CallMethodIdOneArg((PyObject *)&PyUnicode_Type,
1778 &PyId_upper, name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001779 if (!uppercase_name) {
1780 goto finally;
1781 }
1782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001783 if (PyUnicode_READY(uppercase_name))
1784 goto finally;
1785 len = PyUnicode_GET_LENGTH(uppercase_name);
1786 kind = PyUnicode_KIND(uppercase_name);
1787 data = PyUnicode_DATA(uppercase_name);
1788 for (i=0; i<len; i++) {
1789 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1790 if ((ch >= '0' && ch <= '9')
1791 || (ch >= 'A' && ch <= 'Z')
1792 || (ch == '_'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001793 {
Victor Stinner35466c52010-04-22 11:23:23 +00001794 continue;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001795 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001796 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001797 goto finally;
1798 }
1799 }
1800
Serhiy Storchaka06515832016-11-20 09:13:07 +02001801 uppercase_name_str = PyUnicode_AsUTF8(uppercase_name);
Victor Stinner35466c52010-04-22 11:23:23 +00001802 if (!uppercase_name_str)
1803 goto finally;
1804
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001805 if (callable != Py_None && !PyCallable_Check(callable)) {
1806 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1807 goto finally;
1808 }
1809
1810 if (callable != Py_None) {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001811 if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
1812 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001813 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001814 if (PyDict_DelItem(self->collations, uppercase_name) == -1)
1815 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001816 }
1817
1818 rc = sqlite3_create_collation(self->db,
Victor Stinner35466c52010-04-22 11:23:23 +00001819 uppercase_name_str,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001820 SQLITE_UTF8,
1821 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001822 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001823 if (rc != SQLITE_OK) {
Serhiy Storchaka90731802021-01-31 17:42:38 +02001824 if (callable != Py_None) {
1825 if (PyDict_DelItem(self->collations, uppercase_name) < 0) {
1826 PyErr_Clear();
1827 }
1828 }
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001829 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001830 goto finally;
1831 }
1832
1833finally:
1834 Py_XDECREF(uppercase_name);
1835
1836 if (PyErr_Occurred()) {
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +01001837 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001838 }
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +01001839 return Py_NewRef(Py_None);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001840}
1841
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001842/*[clinic input]
1843_sqlite3.Connection.__enter__ as pysqlite_connection_enter
1844
1845Called when the connection is used as a context manager.
1846
1847Returns itself as a convenience to the caller.
1848[clinic start generated code]*/
1849
Christian Heimesbbe741d2008-03-28 10:53:29 +00001850static PyObject *
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001851pysqlite_connection_enter_impl(pysqlite_Connection *self)
1852/*[clinic end generated code: output=457b09726d3e9dcd input=127d7a4f17e86d8f]*/
Christian Heimesbbe741d2008-03-28 10:53:29 +00001853{
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +01001854 return Py_NewRef((PyObject *)self);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001855}
1856
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001857/*[clinic input]
1858_sqlite3.Connection.__exit__ as pysqlite_connection_exit
1859
1860 type as exc_type: object
1861 value as exc_value: object
1862 traceback as exc_tb: object
1863 /
1864
1865Called when the connection is used as a context manager.
1866
1867If there was any exception, a rollback takes place; otherwise we commit.
1868[clinic start generated code]*/
1869
Christian Heimesbbe741d2008-03-28 10:53:29 +00001870static PyObject *
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001871pysqlite_connection_exit_impl(pysqlite_Connection *self, PyObject *exc_type,
1872 PyObject *exc_value, PyObject *exc_tb)
1873/*[clinic end generated code: output=0705200e9321202a input=bd66f1532c9c54a7]*/
Christian Heimesbbe741d2008-03-28 10:53:29 +00001874{
Erlend Egeberg Aasland2a808932021-08-28 20:26:00 +02001875 int commit = 0;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001876 PyObject* result;
1877
Christian Heimesbbe741d2008-03-28 10:53:29 +00001878 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
Erlend Egeberg Aasland2a808932021-08-28 20:26:00 +02001879 commit = 1;
1880 result = pysqlite_connection_commit_impl(self);
1881 }
1882 else {
1883 result = pysqlite_connection_rollback_impl(self);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001884 }
1885
Erlend Egeberg Aasland2a808932021-08-28 20:26:00 +02001886 if (result == NULL) {
1887 if (commit) {
1888 /* Commit failed; try to rollback in order to unlock the database.
1889 * If rollback also fails, chain the exceptions. */
1890 PyObject *exc, *val, *tb;
1891 PyErr_Fetch(&exc, &val, &tb);
1892 result = pysqlite_connection_rollback_impl(self);
1893 if (result == NULL) {
1894 _PyErr_ChainExceptions(exc, val, tb);
1895 }
1896 else {
1897 Py_DECREF(result);
1898 PyErr_Restore(exc, val, tb);
1899 }
1900 }
Christian Heimesbbe741d2008-03-28 10:53:29 +00001901 return NULL;
1902 }
1903 Py_DECREF(result);
1904
1905 Py_RETURN_FALSE;
1906}
1907
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001908static const char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001909PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001910
1911static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001912 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1913 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Berker Peksag59da4b32016-09-12 07:16:43 +03001914 {"in_transaction", (getter)pysqlite_connection_get_in_transaction, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001915 {NULL}
1916};
1917
1918static PyMethodDef connection_methods[] = {
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001919 PYSQLITE_CONNECTION_BACKUP_METHODDEF
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001920 PYSQLITE_CONNECTION_CLOSE_METHODDEF
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001921 PYSQLITE_CONNECTION_COMMIT_METHODDEF
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001922 PYSQLITE_CONNECTION_CREATE_AGGREGATE_METHODDEF
1923 PYSQLITE_CONNECTION_CREATE_COLLATION_METHODDEF
1924 PYSQLITE_CONNECTION_CREATE_FUNCTION_METHODDEF
1925 PYSQLITE_CONNECTION_CURSOR_METHODDEF
1926 PYSQLITE_CONNECTION_ENABLE_LOAD_EXTENSION_METHODDEF
1927 PYSQLITE_CONNECTION_ENTER_METHODDEF
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001928 PYSQLITE_CONNECTION_EXECUTEMANY_METHODDEF
1929 PYSQLITE_CONNECTION_EXECUTESCRIPT_METHODDEF
1930 PYSQLITE_CONNECTION_EXECUTE_METHODDEF
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001931 PYSQLITE_CONNECTION_EXIT_METHODDEF
1932 PYSQLITE_CONNECTION_INTERRUPT_METHODDEF
1933 PYSQLITE_CONNECTION_ITERDUMP_METHODDEF
1934 PYSQLITE_CONNECTION_LOAD_EXTENSION_METHODDEF
1935 PYSQLITE_CONNECTION_ROLLBACK_METHODDEF
1936 PYSQLITE_CONNECTION_SET_AUTHORIZER_METHODDEF
1937 PYSQLITE_CONNECTION_SET_PROGRESS_HANDLER_METHODDEF
1938 PYSQLITE_CONNECTION_SET_TRACE_CALLBACK_METHODDEF
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001939 {NULL, NULL}
1940};
1941
1942static struct PyMemberDef connection_members[] =
1943{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001944 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1945 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1946 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1947 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1948 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1949 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1950 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1951 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1952 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1953 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001954 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1955 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001956 {NULL}
1957};
1958
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001959static PyType_Slot connection_slots[] = {
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -07001960 {Py_tp_dealloc, connection_dealloc},
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001961 {Py_tp_doc, (void *)connection_doc},
1962 {Py_tp_methods, connection_methods},
1963 {Py_tp_members, connection_members},
1964 {Py_tp_getset, connection_getset},
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001965 {Py_tp_init, pysqlite_connection_init},
1966 {Py_tp_call, pysqlite_connection_call},
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -07001967 {Py_tp_traverse, connection_traverse},
1968 {Py_tp_clear, connection_clear},
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001969 {0, NULL},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001970};
1971
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001972static PyType_Spec connection_spec = {
1973 .name = MODULE_NAME ".Connection",
1974 .basicsize = sizeof(pysqlite_Connection),
Miss Islington (bot)7297d742021-06-17 03:19:44 -07001975 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1976 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001977 .slots = connection_slots,
1978};
1979
1980PyTypeObject *pysqlite_ConnectionType = NULL;
1981
Erlend Egeberg Aasland38b6c2a2021-02-21 11:07:49 +01001982int
1983pysqlite_connection_setup_types(PyObject *module)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001984{
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001985 pysqlite_ConnectionType = (PyTypeObject *)PyType_FromModuleAndSpec(module, &connection_spec, NULL);
1986 if (pysqlite_ConnectionType == NULL) {
1987 return -1;
1988 }
1989 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001990}