blob: b6691601286913812f151cf8b913ac493ada6591 [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
Łukasz Langa7e2c0a12021-10-29 22:54:07 +0200116 if (self->db == NULL && rc == SQLITE_NOMEM) {
117 PyErr_NoMemory();
118 return -1;
119 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000120 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000121 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000122 return -1;
123 }
124
125 if (!isolation_level) {
Neal Norwitzefee9f52007-10-27 02:50:52 +0000126 isolation_level = PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000127 if (!isolation_level) {
128 return -1;
129 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000130 } else {
131 Py_INCREF(isolation_level);
132 }
Oren Milman93c5a5d2017-10-10 22:27:46 +0300133 Py_CLEAR(self->isolation_level);
Erlend Egeberg Aasland0cb470e2021-07-30 14:01:22 +0200134 if (pysqlite_connection_set_isolation_level(self, isolation_level, NULL) != 0) {
Victor Stinnercb1f74e2013-12-19 16:38:03 +0100135 Py_DECREF(isolation_level);
136 return -1;
137 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000138 Py_DECREF(isolation_level);
139
Erlend Egeberg Aaslanda937ab42020-09-27 14:14:50 +0200140 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)pysqlite_CacheType, "Oi", self, cached_statements);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000141 if (PyErr_Occurred()) {
142 return -1;
143 }
144
Gerhard Häringf9cee222010-03-05 15:20:03 +0000145 self->created_statements = 0;
146 self->created_cursors = 0;
147
148 /* Create lists of weak references to statements/cursors */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000149 self->statements = PyList_New(0);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000150 self->cursors = PyList_New(0);
151 if (!self->statements || !self->cursors) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000152 return -1;
153 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000154
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000155 /* By default, the Cache class INCREFs the factory in its initializer, and
156 * decrefs it in its deallocator method. Since this would create a circular
157 * reference here, we're breaking it by decrementing self, and telling the
158 * cache class to not decref the factory (self) in its deallocator.
159 */
160 self->statement_cache->decref_factory = 0;
161 Py_DECREF(self);
162
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000163 self->detect_types = detect_types;
164 self->timeout = timeout;
165 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000166 self->thread_ident = PyThread_get_thread_ident();
167 self->check_same_thread = check_same_thread;
168
gescheitb9a03762019-07-13 06:15:49 +0300169 self->function_pinboard_trace_callback = NULL;
170 self->function_pinboard_progress_handler = NULL;
171 self->function_pinboard_authorizer_cb = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000172
Oren Milman93c5a5d2017-10-10 22:27:46 +0300173 Py_XSETREF(self->collations, PyDict_New());
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000174 if (!self->collations) {
175 return -1;
176 }
177
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000178 self->Warning = pysqlite_Warning;
179 self->Error = pysqlite_Error;
180 self->InterfaceError = pysqlite_InterfaceError;
181 self->DatabaseError = pysqlite_DatabaseError;
182 self->DataError = pysqlite_DataError;
183 self->OperationalError = pysqlite_OperationalError;
184 self->IntegrityError = pysqlite_IntegrityError;
185 self->InternalError = pysqlite_InternalError;
186 self->ProgrammingError = pysqlite_ProgrammingError;
187 self->NotSupportedError = pysqlite_NotSupportedError;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000188
Erlend Egeberg Aaslandc96cc082021-05-02 23:25:17 +0200189 if (PySys_Audit("sqlite3.connect/handle", "O", self) < 0) {
190 return -1;
191 }
192
Erlend Egeberg Aasland0cb470e2021-07-30 14:01:22 +0200193 self->initialized = 1;
194
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000195 return 0;
196}
197
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000198/* action in (ACTION_RESET, ACTION_FINALIZE) */
Erlend Egeberg Aaslandbf838a62021-02-21 01:29:19 +0100199static void
200pysqlite_do_all_statements(pysqlite_Connection *self, int action,
201 int reset_cursors)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000202{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000203 int i;
204 PyObject* weakref;
205 PyObject* statement;
Gerhard Häringf9cee222010-03-05 15:20:03 +0000206 pysqlite_Cursor* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000207
Thomas Wouters477c8d52006-05-27 19:21:47 +0000208 for (i = 0; i < PyList_Size(self->statements); i++) {
209 weakref = PyList_GetItem(self->statements, i);
210 statement = PyWeakref_GetObject(weakref);
211 if (statement != Py_None) {
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500212 Py_INCREF(statement);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000213 if (action == ACTION_RESET) {
214 (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
215 } else {
216 (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
217 }
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500218 Py_DECREF(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000219 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000220 }
Gerhard Häringf9cee222010-03-05 15:20:03 +0000221
222 if (reset_cursors) {
223 for (i = 0; i < PyList_Size(self->cursors); i++) {
224 weakref = PyList_GetItem(self->cursors, i);
225 cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
226 if ((PyObject*)cursor != Py_None) {
227 cursor->reset = 1;
228 }
229 }
230 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000231}
232
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700233static int
234connection_traverse(pysqlite_Connection *self, visitproc visit, void *arg)
235{
Miss Islington (bot)ff359d72021-05-31 02:12:27 -0700236 Py_VISIT(Py_TYPE(self));
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700237 Py_VISIT(self->isolation_level);
Miss Islington (bot)ff359d72021-05-31 02:12:27 -0700238 Py_VISIT(self->statement_cache);
239 Py_VISIT(self->statements);
240 Py_VISIT(self->cursors);
241 Py_VISIT(self->row_factory);
242 Py_VISIT(self->text_factory);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700243 Py_VISIT(self->function_pinboard_trace_callback);
244 Py_VISIT(self->function_pinboard_progress_handler);
245 Py_VISIT(self->function_pinboard_authorizer_cb);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700246 Py_VISIT(self->collations);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700247 return 0;
248}
249
250static int
251connection_clear(pysqlite_Connection *self)
252{
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700253 Py_CLEAR(self->isolation_level);
Miss Islington (bot)ff359d72021-05-31 02:12:27 -0700254 Py_CLEAR(self->statement_cache);
255 Py_CLEAR(self->statements);
256 Py_CLEAR(self->cursors);
257 Py_CLEAR(self->row_factory);
258 Py_CLEAR(self->text_factory);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700259 Py_CLEAR(self->function_pinboard_trace_callback);
260 Py_CLEAR(self->function_pinboard_progress_handler);
261 Py_CLEAR(self->function_pinboard_authorizer_cb);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700262 Py_CLEAR(self->collations);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700263 return 0;
264}
265
Erlend Egeberg Aaslandbf838a62021-02-21 01:29:19 +0100266static void
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700267connection_dealloc(pysqlite_Connection *self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000268{
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200269 PyTypeObject *tp = Py_TYPE(self);
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -0700270 PyObject_GC_UnTrack(self);
271 tp->tp_clear((PyObject *)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000272
273 /* Clean up if user has not called .close() explicitly. */
274 if (self->db) {
Erlend Egeberg Aaslandcf0b2392021-01-06 01:02:43 +0100275 sqlite3_close_v2(self->db);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000276 }
277
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200278 tp->tp_free(self);
279 Py_DECREF(tp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000280}
281
Gerhard Häringf9cee222010-03-05 15:20:03 +0000282/*
283 * Registers a cursor with the connection.
284 *
285 * 0 => error; 1 => ok
286 */
287int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
288{
289 PyObject* weakref;
290
291 weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
292 if (!weakref) {
293 goto error;
294 }
295
296 if (PyList_Append(connection->cursors, weakref) != 0) {
297 Py_CLEAR(weakref);
298 goto error;
299 }
300
301 Py_DECREF(weakref);
302
303 return 1;
304error:
305 return 0;
306}
307
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100308/*[clinic input]
309_sqlite3.Connection.cursor as pysqlite_connection_cursor
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000310
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100311 factory: object = NULL
312
313Return a cursor for the connection.
314[clinic start generated code]*/
315
316static PyObject *
317pysqlite_connection_cursor_impl(pysqlite_Connection *self, PyObject *factory)
318/*[clinic end generated code: output=562432a9e6af2aa1 input=4127345aa091b650]*/
319{
320 PyObject* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000321
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000322 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000323 return NULL;
324 }
325
326 if (factory == NULL) {
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200327 factory = (PyObject*)pysqlite_CursorType;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000328 }
329
Petr Viktorinffd97532020-02-11 17:46:57 +0100330 cursor = PyObject_CallOneArg(factory, (PyObject *)self);
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300331 if (cursor == NULL)
332 return NULL;
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +0200333 if (!PyObject_TypeCheck(cursor, pysqlite_CursorType)) {
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300334 PyErr_Format(PyExc_TypeError,
335 "factory must return a cursor, not %.100s",
336 Py_TYPE(cursor)->tp_name);
337 Py_DECREF(cursor);
338 return NULL;
339 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000340
Gerhard Häringf9cee222010-03-05 15:20:03 +0000341 _pysqlite_drop_unused_cursor_references(self);
342
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000343 if (cursor && self->row_factory != Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000344 Py_INCREF(self->row_factory);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300345 Py_XSETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000346 }
347
348 return cursor;
349}
350
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100351/*[clinic input]
352_sqlite3.Connection.close as pysqlite_connection_close
353
354Closes the connection.
355[clinic start generated code]*/
356
357static PyObject *
358pysqlite_connection_close_impl(pysqlite_Connection *self)
359/*[clinic end generated code: output=a546a0da212c9b97 input=3d58064bbffaa3d3]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000360{
361 int rc;
362
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000363 if (!pysqlite_check_thread(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000364 return NULL;
365 }
366
Erlend Egeberg Aasland0cb470e2021-07-30 14:01:22 +0200367 if (!self->initialized) {
368 PyErr_SetString(pysqlite_ProgrammingError,
369 "Base Connection.__init__ not called.");
370 return NULL;
371 }
372
Gerhard Häringf9cee222010-03-05 15:20:03 +0000373 pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000374
375 if (self->db) {
Erlend Egeberg Aaslandcf0b2392021-01-06 01:02:43 +0100376 rc = sqlite3_close_v2(self->db);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000377
378 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000379 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000380 return NULL;
381 } else {
382 self->db = NULL;
383 }
384 }
385
Berker Peksagfe21de92016-04-09 07:34:39 +0300386 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000387}
388
389/*
390 * Checks if a connection object is usable (i. e. not closed).
391 *
392 * 0 => error; 1 => ok
393 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000394int pysqlite_check_connection(pysqlite_Connection* con)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000395{
Gerhard Häringf9cee222010-03-05 15:20:03 +0000396 if (!con->initialized) {
397 PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
398 return 0;
399 }
400
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000401 if (!con->db) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000402 PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000403 return 0;
404 } else {
405 return 1;
406 }
407}
408
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000409PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000410{
411 int rc;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000412 sqlite3_stmt* statement;
413
414 Py_BEGIN_ALLOW_THREADS
Erlend Egeberg Aasland5e48e832021-02-26 15:30:22 +0100415 rc = sqlite3_prepare_v2(self->db, self->begin_statement, -1, &statement,
416 NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417 Py_END_ALLOW_THREADS
418
419 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000420 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000421 goto error;
422 }
423
Benjamin Petersond7b03282008-09-13 15:58:53 +0000424 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300425 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000426 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000427 }
428
429 Py_BEGIN_ALLOW_THREADS
430 rc = sqlite3_finalize(statement);
431 Py_END_ALLOW_THREADS
432
433 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000434 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000435 }
436
437error:
438 if (PyErr_Occurred()) {
439 return NULL;
440 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200441 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000442 }
443}
444
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +0100445/*[clinic input]
446_sqlite3.Connection.commit as pysqlite_connection_commit
447
448Commit the current transaction.
449[clinic start generated code]*/
450
451static PyObject *
452pysqlite_connection_commit_impl(pysqlite_Connection *self)
453/*[clinic end generated code: output=3da45579e89407f2 input=39c12c04dda276a8]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000454{
455 int rc;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000456 sqlite3_stmt* statement;
457
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000458 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000459 return NULL;
460 }
461
Berker Peksag59da4b32016-09-12 07:16:43 +0300462 if (!sqlite3_get_autocommit(self->db)) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000463
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000464 Py_BEGIN_ALLOW_THREADS
Erlend Egeberg Aasland5e48e832021-02-26 15:30:22 +0100465 rc = sqlite3_prepare_v2(self->db, "COMMIT", -1, &statement, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000466 Py_END_ALLOW_THREADS
467 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000468 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000469 goto error;
470 }
471
Benjamin Petersond7b03282008-09-13 15:58:53 +0000472 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300473 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000474 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000475 }
476
477 Py_BEGIN_ALLOW_THREADS
478 rc = sqlite3_finalize(statement);
479 Py_END_ALLOW_THREADS
480 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000481 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000482 }
483
484 }
485
486error:
487 if (PyErr_Occurred()) {
488 return NULL;
489 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200490 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000491 }
492}
493
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100494/*[clinic input]
495_sqlite3.Connection.rollback as pysqlite_connection_rollback
496
497Roll back the current transaction.
498[clinic start generated code]*/
499
500static PyObject *
501pysqlite_connection_rollback_impl(pysqlite_Connection *self)
502/*[clinic end generated code: output=b66fa0d43e7ef305 input=12d4e8d068942830]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000503{
504 int rc;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000505 sqlite3_stmt* statement;
506
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000507 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000508 return NULL;
509 }
510
Berker Peksag59da4b32016-09-12 07:16:43 +0300511 if (!sqlite3_get_autocommit(self->db)) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000512 pysqlite_do_all_statements(self, ACTION_RESET, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000513
514 Py_BEGIN_ALLOW_THREADS
Erlend Egeberg Aasland5e48e832021-02-26 15:30:22 +0100515 rc = sqlite3_prepare_v2(self->db, "ROLLBACK", -1, &statement, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000516 Py_END_ALLOW_THREADS
517 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000518 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000519 goto error;
520 }
521
Benjamin Petersond7b03282008-09-13 15:58:53 +0000522 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300523 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000524 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000525 }
526
527 Py_BEGIN_ALLOW_THREADS
528 rc = sqlite3_finalize(statement);
529 Py_END_ALLOW_THREADS
530 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000531 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000532 }
533
534 }
535
536error:
537 if (PyErr_Occurred()) {
538 return NULL;
539 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200540 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000541 }
542}
543
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200544static int
545_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000546{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200547 if (py_val == Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000548 sqlite3_result_null(context);
Christian Heimes217cfd12007-12-02 14:31:20 +0000549 } else if (PyLong_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200550 sqlite_int64 value = _pysqlite_long_as_int64(py_val);
551 if (value == -1 && PyErr_Occurred())
552 return -1;
553 sqlite3_result_int64(context, value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000554 } else if (PyFloat_Check(py_val)) {
Erlend Egeberg Aaslandba457fe2022-02-21 01:13:04 +0100555 double value = PyFloat_AsDouble(py_val);
556 if (value == -1 && PyErr_Occurred()) {
557 return -1;
558 }
559 sqlite3_result_double(context, value);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000560 } else if (PyUnicode_Check(py_val)) {
Miss Islington (bot)2b1e7132021-08-06 10:59:51 -0700561 Py_ssize_t sz;
562 const char *str = PyUnicode_AsUTF8AndSize(py_val, &sz);
563 if (str == NULL) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200564 return -1;
Miss Islington (bot)2b1e7132021-08-06 10:59:51 -0700565 }
566 if (sz > INT_MAX) {
567 PyErr_SetString(PyExc_OverflowError,
568 "string is longer than INT_MAX bytes");
569 return -1;
570 }
571 sqlite3_result_text(context, str, (int)sz, SQLITE_TRANSIENT);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000572 } else if (PyObject_CheckBuffer(py_val)) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200573 Py_buffer view;
574 if (PyObject_GetBuffer(py_val, &view, PyBUF_SIMPLE) != 0) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100575 PyErr_SetString(PyExc_ValueError,
576 "could not convert BLOB to buffer");
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200577 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000578 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200579 if (view.len > INT_MAX) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100580 PyErr_SetString(PyExc_OverflowError,
581 "BLOB longer than INT_MAX bytes");
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200582 PyBuffer_Release(&view);
Victor Stinner83ed42b2013-11-18 01:24:31 +0100583 return -1;
584 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200585 sqlite3_result_blob(context, view.buf, (int)view.len, SQLITE_TRANSIENT);
586 PyBuffer_Release(&view);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000587 } else {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200588 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000589 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200590 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000591}
592
Erlend Egeberg Aaslandbf838a62021-02-21 01:29:19 +0100593static PyObject *
594_pysqlite_build_py_params(sqlite3_context *context, int argc,
595 sqlite3_value **argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000596{
597 PyObject* args;
598 int i;
599 sqlite3_value* cur_value;
600 PyObject* cur_py_value;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601
602 args = PyTuple_New(argc);
603 if (!args) {
604 return NULL;
605 }
606
607 for (i = 0; i < argc; i++) {
608 cur_value = argv[i];
609 switch (sqlite3_value_type(argv[i])) {
610 case SQLITE_INTEGER:
Sergey Fedoseevb6f5b9d2019-10-23 13:09:01 +0500611 cur_py_value = PyLong_FromLongLong(sqlite3_value_int64(cur_value));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000612 break;
613 case SQLITE_FLOAT:
614 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
615 break;
Miss Islington (bot)067d6d42021-06-04 11:54:39 -0700616 case SQLITE_TEXT: {
617 sqlite3 *db = sqlite3_context_db_handle(context);
618 const char *text = (const char *)sqlite3_value_text(cur_value);
619
620 if (text == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
621 PyErr_NoMemory();
622 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000623 }
Miss Islington (bot)067d6d42021-06-04 11:54:39 -0700624
625 Py_ssize_t size = sqlite3_value_bytes(cur_value);
626 cur_py_value = PyUnicode_FromStringAndSize(text, size);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627 break;
Miss Islington (bot)067d6d42021-06-04 11:54:39 -0700628 }
Erlend Egeberg Aasland5cb601f2021-04-14 23:09:11 +0200629 case SQLITE_BLOB: {
630 sqlite3 *db = sqlite3_context_db_handle(context);
631 const void *blob = sqlite3_value_blob(cur_value);
632
633 if (blob == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
634 PyErr_NoMemory();
635 goto error;
636 }
637
638 Py_ssize_t size = sqlite3_value_bytes(cur_value);
639 cur_py_value = PyBytes_FromStringAndSize(blob, size);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000640 break;
Erlend Egeberg Aasland5cb601f2021-04-14 23:09:11 +0200641 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000642 case SQLITE_NULL:
643 default:
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +0100644 cur_py_value = Py_NewRef(Py_None);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000645 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000646
647 if (!cur_py_value) {
Erlend Egeberg Aasland5cb601f2021-04-14 23:09:11 +0200648 goto error;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000649 }
650
Erlend Egeberg Aaslande9194ea2021-04-23 13:21:08 +0200651 PyTuple_SET_ITEM(args, i, cur_py_value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000652 }
653
654 return args;
Erlend Egeberg Aasland5cb601f2021-04-14 23:09:11 +0200655
656error:
657 Py_DECREF(args);
658 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000659}
660
Erlend Egeberg Aasland2bb0bf42021-02-19 12:59:24 +0100661static void
662_pysqlite_func_callback(sqlite3_context *context, int argc, sqlite3_value **argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000663{
664 PyObject* args;
665 PyObject* py_func;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000666 PyObject* py_retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200667 int ok;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000668
669 PyGILState_STATE threadstate;
670
671 threadstate = PyGILState_Ensure();
672
673 py_func = (PyObject*)sqlite3_user_data(context);
674
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000675 args = _pysqlite_build_py_params(context, argc, argv);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000676 if (args) {
677 py_retval = PyObject_CallObject(py_func, args);
678 Py_DECREF(args);
679 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000680
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200681 ok = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000682 if (py_retval) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200683 ok = _pysqlite_set_result(context, py_retval) == 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000684 Py_DECREF(py_retval);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200685 }
686 if (!ok) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700687 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000688 PyErr_Print();
689 } else {
690 PyErr_Clear();
691 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200692 sqlite3_result_error(context, "user-defined function raised exception", -1);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000693 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694
695 PyGILState_Release(threadstate);
696}
697
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000698static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000699{
700 PyObject* args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000701 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000702 PyObject* aggregate_class;
703 PyObject** aggregate_instance;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000704 PyObject* stepmethod = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000705
706 PyGILState_STATE threadstate;
707
708 threadstate = PyGILState_Ensure();
709
710 aggregate_class = (PyObject*)sqlite3_user_data(context);
711
712 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
713
Serhiy Storchaka0b3ec192017-03-23 17:53:47 +0200714 if (*aggregate_instance == NULL) {
Victor Stinner070c4d72016-12-09 12:29:18 +0100715 *aggregate_instance = _PyObject_CallNoArg(aggregate_class);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000716
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717 if (PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000718 *aggregate_instance = 0;
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700719 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000720 PyErr_Print();
721 } else {
722 PyErr_Clear();
723 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200724 sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000725 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000726 }
727 }
728
729 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730 if (!stepmethod) {
731 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000732 }
733
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000734 args = _pysqlite_build_py_params(context, argc, params);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735 if (!args) {
736 goto error;
737 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000738
739 function_result = PyObject_CallObject(stepmethod, args);
740 Py_DECREF(args);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000741
Thomas Wouters477c8d52006-05-27 19:21:47 +0000742 if (!function_result) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700743 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000744 PyErr_Print();
745 } else {
746 PyErr_Clear();
747 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200748 sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000749 }
750
Thomas Wouters477c8d52006-05-27 19:21:47 +0000751error:
752 Py_XDECREF(stepmethod);
753 Py_XDECREF(function_result);
754
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000755 PyGILState_Release(threadstate);
756}
757
Erlend Egeberg Aasland2bb0bf42021-02-19 12:59:24 +0100758static void
759_pysqlite_final_callback(sqlite3_context *context)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000760{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200761 PyObject* function_result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000762 PyObject** aggregate_instance;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200763 _Py_IDENTIFIER(finalize);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200764 int ok;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200765 PyObject *exception, *value, *tb;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000766
767 PyGILState_STATE threadstate;
768
769 threadstate = PyGILState_Ensure();
770
Erlend Egeberg Aasland979b23c2021-02-19 12:20:32 +0100771 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, 0);
772 if (aggregate_instance == NULL) {
773 /* No rows matched the query; the step handler was never called. */
774 goto error;
775 }
776 else if (!*aggregate_instance) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000777 /* this branch is executed if there was an exception in the aggregate's
778 * __init__ */
779
Thomas Wouters477c8d52006-05-27 19:21:47 +0000780 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000781 }
782
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200783 /* Keep the exception (if any) of the last call to step() */
784 PyErr_Fetch(&exception, &value, &tb);
785
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200786 function_result = _PyObject_CallMethodIdNoArgs(*aggregate_instance, &PyId_finalize);
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200787
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200788 Py_DECREF(*aggregate_instance);
789
790 ok = 0;
791 if (function_result) {
792 ok = _pysqlite_set_result(context, function_result) == 0;
793 Py_DECREF(function_result);
794 }
795 if (!ok) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700796 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000797 PyErr_Print();
798 } else {
799 PyErr_Clear();
800 }
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200801 sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000802 }
803
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +0200804 /* Restore the exception (if any) of the last call to step(),
805 but clear also the current exception if finalize() failed */
806 PyErr_Restore(exception, value, tb);
Victor Stinner3a857322013-07-22 08:34:32 +0200807
Thomas Wouters477c8d52006-05-27 19:21:47 +0000808error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809 PyGILState_Release(threadstate);
810}
811
Gerhard Häringf9cee222010-03-05 15:20:03 +0000812static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000813{
814 PyObject* new_list;
815 PyObject* weakref;
816 int i;
817
818 /* we only need to do this once in a while */
819 if (self->created_statements++ < 200) {
820 return;
821 }
822
823 self->created_statements = 0;
824
825 new_list = PyList_New(0);
826 if (!new_list) {
827 return;
828 }
829
830 for (i = 0; i < PyList_Size(self->statements); i++) {
831 weakref = PyList_GetItem(self->statements, i);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000832 if (PyWeakref_GetObject(weakref) != Py_None) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000833 if (PyList_Append(new_list, weakref) != 0) {
834 Py_DECREF(new_list);
835 return;
836 }
837 }
838 }
839
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300840 Py_SETREF(self->statements, new_list);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000841}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000842
Gerhard Häringf9cee222010-03-05 15:20:03 +0000843static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
844{
845 PyObject* new_list;
846 PyObject* weakref;
847 int i;
848
849 /* we only need to do this once in a while */
850 if (self->created_cursors++ < 200) {
851 return;
852 }
853
854 self->created_cursors = 0;
855
856 new_list = PyList_New(0);
857 if (!new_list) {
858 return;
859 }
860
861 for (i = 0; i < PyList_Size(self->cursors); i++) {
862 weakref = PyList_GetItem(self->cursors, i);
863 if (PyWeakref_GetObject(weakref) != Py_None) {
864 if (PyList_Append(new_list, weakref) != 0) {
865 Py_DECREF(new_list);
866 return;
867 }
868 }
869 }
870
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300871 Py_SETREF(self->cursors, new_list);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000872}
873
gescheitb9a03762019-07-13 06:15:49 +0300874static void _destructor(void* args)
875{
Miss Islington (bot)317e9ed2021-06-05 16:13:27 -0700876 // This function may be called without the GIL held, so we need to ensure
877 // that we destroy 'args' with the GIL
878 PyGILState_STATE gstate;
879 gstate = PyGILState_Ensure();
gescheitb9a03762019-07-13 06:15:49 +0300880 Py_DECREF((PyObject*)args);
Miss Islington (bot)317e9ed2021-06-05 16:13:27 -0700881 PyGILState_Release(gstate);
gescheitb9a03762019-07-13 06:15:49 +0300882}
883
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100884/*[clinic input]
885_sqlite3.Connection.create_function as pysqlite_connection_create_function
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000886
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100887 name: str
888 narg: int
889 func: object
890 *
891 deterministic: bool = False
892
893Creates a new function. Non-standard.
894[clinic start generated code]*/
895
896static PyObject *
897pysqlite_connection_create_function_impl(pysqlite_Connection *self,
898 const char *name, int narg,
899 PyObject *func, int deterministic)
900/*[clinic end generated code: output=07d1877dd98c0308 input=f2edcf073e815beb]*/
901{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000902 int rc;
Sergey Fedoseev08308582018-07-08 12:09:20 +0500903 int flags = SQLITE_UTF8;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000904
Gerhard Häringf9cee222010-03-05 15:20:03 +0000905 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
906 return NULL;
907 }
908
Sergey Fedoseev08308582018-07-08 12:09:20 +0500909 if (deterministic) {
910#if SQLITE_VERSION_NUMBER < 3008003
911 PyErr_SetString(pysqlite_NotSupportedError,
912 "deterministic=True requires SQLite 3.8.3 or higher");
913 return NULL;
914#else
915 if (sqlite3_libversion_number() < 3008003) {
916 PyErr_SetString(pysqlite_NotSupportedError,
917 "deterministic=True requires SQLite 3.8.3 or higher");
918 return NULL;
919 }
920 flags |= SQLITE_DETERMINISTIC;
921#endif
922 }
gescheitb9a03762019-07-13 06:15:49 +0300923 rc = sqlite3_create_function_v2(self->db,
924 name,
925 narg,
926 flags,
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +0100927 (void*)Py_NewRef(func),
gescheitb9a03762019-07-13 06:15:49 +0300928 _pysqlite_func_callback,
929 NULL,
930 NULL,
931 &_destructor); // will decref func
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000932
Thomas Wouters477c8d52006-05-27 19:21:47 +0000933 if (rc != SQLITE_OK) {
934 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000935 PyErr_SetString(pysqlite_OperationalError, "Error creating function");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000936 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000937 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +0500938 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000939}
940
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100941/*[clinic input]
942_sqlite3.Connection.create_aggregate as pysqlite_connection_create_aggregate
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000943
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +0100944 name: str
945 n_arg: int
946 aggregate_class: object
947
948Creates a new aggregate. Non-standard.
949[clinic start generated code]*/
950
951static PyObject *
952pysqlite_connection_create_aggregate_impl(pysqlite_Connection *self,
953 const char *name, int n_arg,
954 PyObject *aggregate_class)
955/*[clinic end generated code: output=fbb2f858cfa4d8db input=c2e13bbf234500a5]*/
956{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000957 int rc;
958
Gerhard Häringf9cee222010-03-05 15:20:03 +0000959 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
960 return NULL;
961 }
962
gescheitb9a03762019-07-13 06:15:49 +0300963 rc = sqlite3_create_function_v2(self->db,
964 name,
965 n_arg,
966 SQLITE_UTF8,
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +0100967 (void*)Py_NewRef(aggregate_class),
gescheitb9a03762019-07-13 06:15:49 +0300968 0,
969 &_pysqlite_step_callback,
970 &_pysqlite_final_callback,
971 &_destructor); // will decref func
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000972 if (rc != SQLITE_OK) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000973 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000974 PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000975 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000976 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +0500977 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000978}
979
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000980static 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 +0000981{
982 PyObject *ret;
983 int rc;
984 PyGILState_STATE gilstate;
985
986 gilstate = PyGILState_Ensure();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000987
Victor Stinnerd4095d92013-07-26 22:23:33 +0200988 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000989
Victor Stinnerd4095d92013-07-26 22:23:33 +0200990 if (ret == NULL) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700991 if (_pysqlite_enable_callback_tracebacks)
Victor Stinnerd4095d92013-07-26 22:23:33 +0200992 PyErr_Print();
993 else
994 PyErr_Clear();
Victor Stinner41801f52013-07-21 13:05:38 +0200995
Victor Stinnerd4095d92013-07-26 22:23:33 +0200996 rc = SQLITE_DENY;
Victor Stinner41801f52013-07-21 13:05:38 +0200997 }
998 else {
Victor Stinnerd4095d92013-07-26 22:23:33 +0200999 if (PyLong_Check(ret)) {
1000 rc = _PyLong_AsInt(ret);
1001 if (rc == -1 && PyErr_Occurred()) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -07001002 if (_pysqlite_enable_callback_tracebacks)
Victor Stinnerd4095d92013-07-26 22:23:33 +02001003 PyErr_Print();
1004 else
1005 PyErr_Clear();
1006 rc = SQLITE_DENY;
1007 }
1008 }
1009 else {
1010 rc = SQLITE_DENY;
1011 }
1012 Py_DECREF(ret);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001013 }
1014
1015 PyGILState_Release(gilstate);
1016 return rc;
1017}
1018
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001019static int _progress_handler(void* user_arg)
1020{
1021 int rc;
1022 PyObject *ret;
1023 PyGILState_STATE gilstate;
1024
1025 gilstate = PyGILState_Ensure();
Victor Stinner070c4d72016-12-09 12:29:18 +01001026 ret = _PyObject_CallNoArg((PyObject*)user_arg);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001027
1028 if (!ret) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -07001029 if (_pysqlite_enable_callback_tracebacks) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001030 PyErr_Print();
1031 } else {
1032 PyErr_Clear();
1033 }
1034
Mark Dickinson934896d2009-02-21 20:59:32 +00001035 /* abort query if error occurred */
Victor Stinner86999502010-05-19 01:27:23 +00001036 rc = 1;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001037 } else {
1038 rc = (int)PyObject_IsTrue(ret);
1039 Py_DECREF(ret);
1040 }
1041
1042 PyGILState_Release(gilstate);
1043 return rc;
1044}
1045
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001046#ifdef HAVE_TRACE_V2
1047/*
1048 * From https://sqlite.org/c3ref/trace_v2.html:
1049 * The integer return value from the callback is currently ignored, though this
1050 * may change in future releases. Callback implementations should return zero
1051 * to ensure future compatibility.
1052 */
1053static int _trace_callback(unsigned int type, void* user_arg, void* prepared_statement, void* statement_string)
1054#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001055static void _trace_callback(void* user_arg, const char* statement_string)
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001056#endif
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001057{
1058 PyObject *py_statement = NULL;
1059 PyObject *ret = NULL;
1060
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001061 PyGILState_STATE gilstate;
1062
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001063#ifdef HAVE_TRACE_V2
1064 if (type != SQLITE_TRACE_STMT) {
1065 return 0;
1066 }
1067#endif
1068
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001069 gilstate = PyGILState_Ensure();
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001070 py_statement = PyUnicode_DecodeUTF8(statement_string,
1071 strlen(statement_string), "replace");
1072 if (py_statement) {
Petr Viktorinffd97532020-02-11 17:46:57 +01001073 ret = PyObject_CallOneArg((PyObject*)user_arg, py_statement);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001074 Py_DECREF(py_statement);
1075 }
1076
1077 if (ret) {
1078 Py_DECREF(ret);
1079 } else {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -07001080 if (_pysqlite_enable_callback_tracebacks) {
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001081 PyErr_Print();
1082 } else {
1083 PyErr_Clear();
1084 }
1085 }
1086
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001087 PyGILState_Release(gilstate);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001088#ifdef HAVE_TRACE_V2
1089 return 0;
1090#endif
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001091}
1092
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001093/*[clinic input]
1094_sqlite3.Connection.set_authorizer as pysqlite_connection_set_authorizer
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001095
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001096 authorizer_callback as authorizer_cb: object
1097
1098Sets authorizer callback. Non-standard.
1099[clinic start generated code]*/
1100
1101static PyObject *
1102pysqlite_connection_set_authorizer_impl(pysqlite_Connection *self,
1103 PyObject *authorizer_cb)
1104/*[clinic end generated code: output=f18ba575d788b35c input=df079724c020d2f2]*/
1105{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001106 int rc;
1107
Gerhard Häringf9cee222010-03-05 15:20:03 +00001108 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1109 return NULL;
1110 }
1111
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001112 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001113 if (rc != SQLITE_OK) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001114 PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
gescheitb9a03762019-07-13 06:15:49 +03001115 Py_XSETREF(self->function_pinboard_authorizer_cb, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001116 return NULL;
gescheitb9a03762019-07-13 06:15:49 +03001117 } else {
1118 Py_INCREF(authorizer_cb);
1119 Py_XSETREF(self->function_pinboard_authorizer_cb, authorizer_cb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001120 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +05001121 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001122}
1123
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001124/*[clinic input]
1125_sqlite3.Connection.set_progress_handler as pysqlite_connection_set_progress_handler
1126
1127 progress_handler: object
1128 n: int
1129
1130Sets progress handler callback. Non-standard.
1131[clinic start generated code]*/
1132
1133static PyObject *
1134pysqlite_connection_set_progress_handler_impl(pysqlite_Connection *self,
1135 PyObject *progress_handler,
1136 int n)
1137/*[clinic end generated code: output=35a7c10364cb1b04 input=857696c25f964c64]*/
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001138{
Gerhard Häringf9cee222010-03-05 15:20:03 +00001139 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1140 return NULL;
1141 }
1142
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001143 if (progress_handler == Py_None) {
1144 /* None clears the progress handler previously set */
1145 sqlite3_progress_handler(self->db, 0, 0, (void*)0);
gescheitb9a03762019-07-13 06:15:49 +03001146 Py_XSETREF(self->function_pinboard_progress_handler, NULL);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001147 } else {
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +05001148 sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
gescheitb9a03762019-07-13 06:15:49 +03001149 Py_INCREF(progress_handler);
1150 Py_XSETREF(self->function_pinboard_progress_handler, progress_handler);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001151 }
Berker Peksagfe21de92016-04-09 07:34:39 +03001152 Py_RETURN_NONE;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001153}
1154
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001155/*[clinic input]
1156_sqlite3.Connection.set_trace_callback as pysqlite_connection_set_trace_callback
1157
1158 trace_callback: object
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001159
1160Sets a trace callback called for each SQL statement (passed as unicode).
1161
1162Non-standard.
1163[clinic start generated code]*/
1164
1165static PyObject *
Dong-hee Na21793492020-12-19 00:41:33 +09001166pysqlite_connection_set_trace_callback_impl(pysqlite_Connection *self,
1167 PyObject *trace_callback)
1168/*[clinic end generated code: output=fb0e307b9924d454 input=56d60fd38d763679]*/
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001169{
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001170 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1171 return NULL;
1172 }
1173
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001174 if (trace_callback == Py_None) {
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001175 /*
1176 * None clears the trace callback previously set
1177 *
1178 * Ref.
1179 * - https://sqlite.org/c3ref/c_trace.html
1180 * - https://sqlite.org/c3ref/trace_v2.html
1181 */
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001182#ifdef HAVE_TRACE_V2
1183 sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, 0, 0);
1184#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001185 sqlite3_trace(self->db, 0, (void*)0);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001186#endif
gescheitb9a03762019-07-13 06:15:49 +03001187 Py_XSETREF(self->function_pinboard_trace_callback, NULL);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001188 } else {
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001189#ifdef HAVE_TRACE_V2
1190 sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, _trace_callback, trace_callback);
1191#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001192 sqlite3_trace(self->db, _trace_callback, trace_callback);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001193#endif
gescheitb9a03762019-07-13 06:15:49 +03001194 Py_INCREF(trace_callback);
1195 Py_XSETREF(self->function_pinboard_trace_callback, trace_callback);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001196 }
1197
Berker Peksagfe21de92016-04-09 07:34:39 +03001198 Py_RETURN_NONE;
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001199}
1200
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +02001201#ifndef SQLITE_OMIT_LOAD_EXTENSION
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001202/*[clinic input]
1203_sqlite3.Connection.enable_load_extension as pysqlite_connection_enable_load_extension
1204
Dong-hee Na21793492020-12-19 00:41:33 +09001205 enable as onoff: bool(accept={int})
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001206 /
1207
1208Enable dynamic loading of SQLite extension modules. Non-standard.
1209[clinic start generated code]*/
1210
1211static PyObject *
1212pysqlite_connection_enable_load_extension_impl(pysqlite_Connection *self,
1213 int onoff)
Dong-hee Na21793492020-12-19 00:41:33 +09001214/*[clinic end generated code: output=9cac37190d388baf input=5c0da5b121121cbc]*/
Gerhard Häringf9cee222010-03-05 15:20:03 +00001215{
1216 int rc;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001217
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +02001218 if (PySys_Audit("sqlite3.enable_load_extension",
1219 "OO", self, onoff ? Py_True : Py_False) < 0) {
1220 return NULL;
1221 }
1222
Gerhard Häringf9cee222010-03-05 15:20:03 +00001223 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1224 return NULL;
1225 }
1226
Gerhard Häringf9cee222010-03-05 15:20:03 +00001227 rc = sqlite3_enable_load_extension(self->db, onoff);
1228
1229 if (rc != SQLITE_OK) {
1230 PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
1231 return NULL;
1232 } else {
Berker Peksagfe21de92016-04-09 07:34:39 +03001233 Py_RETURN_NONE;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001234 }
1235}
1236
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001237/*[clinic input]
1238_sqlite3.Connection.load_extension as pysqlite_connection_load_extension
1239
1240 name as extension_name: str
1241 /
1242
1243Load SQLite extension module. Non-standard.
1244[clinic start generated code]*/
1245
1246static PyObject *
1247pysqlite_connection_load_extension_impl(pysqlite_Connection *self,
1248 const char *extension_name)
1249/*[clinic end generated code: output=47eb1d7312bc97a7 input=0b711574560db9fc]*/
Gerhard Häringf9cee222010-03-05 15:20:03 +00001250{
1251 int rc;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001252 char* errmsg;
1253
Erlend Egeberg Aasland7244c002021-04-27 01:16:46 +02001254 if (PySys_Audit("sqlite3.load_extension", "Os", self, extension_name) < 0) {
1255 return NULL;
1256 }
1257
Gerhard Häringf9cee222010-03-05 15:20:03 +00001258 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1259 return NULL;
1260 }
1261
Gerhard Häringf9cee222010-03-05 15:20:03 +00001262 rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1263 if (rc != 0) {
1264 PyErr_SetString(pysqlite_OperationalError, errmsg);
1265 return NULL;
1266 } else {
Berker Peksagfe21de92016-04-09 07:34:39 +03001267 Py_RETURN_NONE;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001268 }
1269}
1270#endif
1271
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001272int pysqlite_check_thread(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001273{
1274 if (self->check_same_thread) {
1275 if (PyThread_get_thread_ident() != self->thread_ident) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001276 PyErr_Format(pysqlite_ProgrammingError,
Takuya Akiba030345c2018-03-27 00:14:00 +09001277 "SQLite objects created in a thread can only be used in that same thread. "
1278 "The object was created in thread id %lu and this is thread id %lu.",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001279 self->thread_ident, PyThread_get_thread_ident());
1280 return 0;
1281 }
1282
1283 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001284 return 1;
1285}
1286
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001287static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001288{
Erlend Egeberg Aasland0cb470e2021-07-30 14:01:22 +02001289 if (!pysqlite_check_connection(self)) {
1290 return NULL;
1291 }
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +01001292 return Py_NewRef(self->isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001293}
1294
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001295static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001296{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001297 if (!pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001298 return NULL;
1299 } else {
1300 return Py_BuildValue("i", sqlite3_total_changes(self->db));
1301 }
1302}
1303
Berker Peksag59da4b32016-09-12 07:16:43 +03001304static PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
1305{
1306 if (!pysqlite_check_connection(self)) {
1307 return NULL;
1308 }
1309 if (!sqlite3_get_autocommit(self->db)) {
1310 Py_RETURN_TRUE;
1311 }
1312 Py_RETURN_FALSE;
1313}
1314
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +02001315static int
1316pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001317{
Zackery Spytz842acaa2018-12-17 07:52:45 -07001318 if (isolation_level == NULL) {
1319 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
1320 return -1;
1321 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001322 if (isolation_level == Py_None) {
Erlend Egeberg Aasland0cb470e2021-07-30 14:01:22 +02001323 /* We might get called during connection init, so we cannot use
1324 * pysqlite_connection_commit() here. */
1325 if (self->db && !sqlite3_get_autocommit(self->db)) {
1326 int rc;
1327 Py_BEGIN_ALLOW_THREADS
1328 rc = sqlite3_exec(self->db, "COMMIT", NULL, NULL, NULL);
1329 Py_END_ALLOW_THREADS
1330 if (rc != SQLITE_OK) {
1331 return _pysqlite_seterror(self->db, NULL);
1332 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001333 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001334
Serhiy Storchaka28914922016-09-01 22:18:03 +03001335 self->begin_statement = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001336 } else {
Serhiy Storchaka28914922016-09-01 22:18:03 +03001337 const char * const *candidate;
1338 PyObject *uppercase_level;
1339 _Py_IDENTIFIER(upper);
Neal Norwitzefee9f52007-10-27 02:50:52 +00001340
Serhiy Storchaka28914922016-09-01 22:18:03 +03001341 if (!PyUnicode_Check(isolation_level)) {
1342 PyErr_Format(PyExc_TypeError,
1343 "isolation_level must be a string or None, not %.100s",
1344 Py_TYPE(isolation_level)->tp_name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001345 return -1;
1346 }
1347
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001348 uppercase_level = _PyObject_CallMethodIdOneArg(
Serhiy Storchaka28914922016-09-01 22:18:03 +03001349 (PyObject *)&PyUnicode_Type, &PyId_upper,
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001350 isolation_level);
Serhiy Storchaka28914922016-09-01 22:18:03 +03001351 if (!uppercase_level) {
Georg Brandl3dbca812008-07-23 16:10:53 +00001352 return -1;
1353 }
Serhiy Storchaka28914922016-09-01 22:18:03 +03001354 for (candidate = begin_statements; *candidate; candidate++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001355 if (_PyUnicode_EqualToASCIIString(uppercase_level, *candidate + 6))
Serhiy Storchaka28914922016-09-01 22:18:03 +03001356 break;
1357 }
1358 Py_DECREF(uppercase_level);
1359 if (!*candidate) {
1360 PyErr_SetString(PyExc_ValueError,
1361 "invalid value for isolation_level");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001362 return -1;
1363 }
Serhiy Storchaka28914922016-09-01 22:18:03 +03001364 self->begin_statement = *candidate;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001365 }
1366
Serhiy Storchaka28914922016-09-01 22:18:03 +03001367 Py_INCREF(isolation_level);
1368 Py_XSETREF(self->isolation_level, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001369 return 0;
1370}
1371
Erlend Egeberg Aaslandbf838a62021-02-21 01:29:19 +01001372static PyObject *
1373pysqlite_connection_call(pysqlite_Connection *self, PyObject *args,
1374 PyObject *kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001375{
1376 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001377 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001378 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001379
Gerhard Häringf9cee222010-03-05 15:20:03 +00001380 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1381 return NULL;
1382 }
1383
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001384 if (!_PyArg_NoKeywords(MODULE_NAME ".Connection", kwargs))
Larry Hastings3b12e952015-05-08 07:45:10 -07001385 return NULL;
1386
Victor Stinnerc6a23202019-06-26 03:16:24 +02001387 if (!PyArg_ParseTuple(args, "U", &sql))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001388 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001389
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001390 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001391
Erlend Egeberg Aasland84d80f52021-06-03 18:38:09 +02001392 statement = pysqlite_statement_create(self, sql);
1393 if (statement == NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001394 return NULL;
1395 }
1396
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001397 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
1398 if (weakref == NULL)
1399 goto error;
1400 if (PyList_Append(self->statements, weakref) != 0) {
1401 Py_DECREF(weakref);
1402 goto error;
1403 }
1404 Py_DECREF(weakref);
1405
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001406 return (PyObject*)statement;
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001407
1408error:
1409 Py_DECREF(statement);
1410 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001411}
1412
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001413/*[clinic input]
1414_sqlite3.Connection.execute as pysqlite_connection_execute
1415
1416 sql: unicode
1417 parameters: object = NULL
1418 /
1419
1420Executes a SQL statement. Non-standard.
1421[clinic start generated code]*/
1422
1423static PyObject *
1424pysqlite_connection_execute_impl(pysqlite_Connection *self, PyObject *sql,
1425 PyObject *parameters)
1426/*[clinic end generated code: output=5be05ae01ee17ee4 input=fbd17c75c7140271]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001427{
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001428 _Py_IDENTIFIER(execute);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001429 PyObject* cursor = 0;
1430 PyObject* result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001431
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001432 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001433 if (!cursor) {
1434 goto error;
1435 }
1436
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001437 result = _PyObject_CallMethodIdObjArgs(cursor, &PyId_execute, sql, parameters, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001438 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001439 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001440 }
1441
1442error:
1443 Py_XDECREF(result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001444
1445 return cursor;
1446}
1447
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001448/*[clinic input]
1449_sqlite3.Connection.executemany as pysqlite_connection_executemany
1450
1451 sql: unicode
1452 parameters: object
1453 /
1454
1455Repeatedly executes a SQL statement. Non-standard.
1456[clinic start generated code]*/
1457
1458static PyObject *
1459pysqlite_connection_executemany_impl(pysqlite_Connection *self,
1460 PyObject *sql, PyObject *parameters)
1461/*[clinic end generated code: output=776cd2fd20bfe71f input=4feab80659ffc82b]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001462{
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001463 _Py_IDENTIFIER(executemany);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001464 PyObject* cursor = 0;
1465 PyObject* result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001466
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001467 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001468 if (!cursor) {
1469 goto error;
1470 }
1471
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001472 result = _PyObject_CallMethodIdObjArgs(cursor, &PyId_executemany, sql,
1473 parameters, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001474 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001475 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001476 }
1477
1478error:
1479 Py_XDECREF(result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001480
1481 return cursor;
1482}
1483
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001484/*[clinic input]
1485_sqlite3.Connection.executescript as pysqlite_connection_executescript
1486
1487 sql_script as script_obj: object
1488 /
1489
Erlend Egeberg Aasland02e4c0c2021-07-15 01:02:01 +02001490Executes multiple SQL statements at once. Non-standard.
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001491[clinic start generated code]*/
1492
1493static PyObject *
1494pysqlite_connection_executescript(pysqlite_Connection *self,
1495 PyObject *script_obj)
Erlend Egeberg Aasland02e4c0c2021-07-15 01:02:01 +02001496/*[clinic end generated code: output=4c4f9d77aa0ae37d input=b27ae5c24ffb8b43]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001497{
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001498 _Py_IDENTIFIER(executescript);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001499 PyObject* cursor = 0;
1500 PyObject* result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001501
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001502 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001503 if (!cursor) {
1504 goto error;
1505 }
1506
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001507 result = _PyObject_CallMethodIdObjArgs(cursor, &PyId_executescript,
1508 script_obj, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001509 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001510 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001511 }
1512
1513error:
1514 Py_XDECREF(result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001515
1516 return cursor;
1517}
1518
1519/* ------------------------- COLLATION CODE ------------------------ */
1520
1521static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001522pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001523 void* context,
1524 int text1_length, const void* text1_data,
1525 int text2_length, const void* text2_data)
1526{
1527 PyObject* callback = (PyObject*)context;
1528 PyObject* string1 = 0;
1529 PyObject* string2 = 0;
1530 PyGILState_STATE gilstate;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001531 PyObject* retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001532 long longval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001533 int result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001534 gilstate = PyGILState_Ensure();
1535
1536 if (PyErr_Occurred()) {
1537 goto finally;
1538 }
1539
Guido van Rossum98297ee2007-11-06 21:34:58 +00001540 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1541 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001542
1543 if (!string1 || !string2) {
1544 goto finally; /* failed to allocate strings */
1545 }
1546
1547 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1548
1549 if (!retval) {
1550 /* execution failed */
1551 goto finally;
1552 }
1553
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001554 longval = PyLong_AsLongAndOverflow(retval, &result);
1555 if (longval == -1 && PyErr_Occurred()) {
1556 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001557 result = 0;
1558 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001559 else if (!result) {
1560 if (longval > 0)
1561 result = 1;
1562 else if (longval < 0)
1563 result = -1;
1564 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001565
1566finally:
1567 Py_XDECREF(string1);
1568 Py_XDECREF(string2);
1569 Py_XDECREF(retval);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001570 PyGILState_Release(gilstate);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001571 return result;
1572}
1573
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001574/*[clinic input]
1575_sqlite3.Connection.interrupt as pysqlite_connection_interrupt
1576
1577Abort any pending database operation. Non-standard.
1578[clinic start generated code]*/
1579
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001580static PyObject *
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001581pysqlite_connection_interrupt_impl(pysqlite_Connection *self)
1582/*[clinic end generated code: output=f193204bc9e70b47 input=4bd0ad083cf93aa7]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001583{
1584 PyObject* retval = NULL;
1585
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001586 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001587 goto finally;
1588 }
1589
1590 sqlite3_interrupt(self->db);
1591
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +01001592 retval = Py_NewRef(Py_None);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001593
1594finally:
1595 return retval;
1596}
1597
Christian Heimesbbe741d2008-03-28 10:53:29 +00001598/* Function author: Paul Kippes <kippesp@gmail.com>
1599 * Class method of Connection to call the Python function _iterdump
1600 * of the sqlite3 module.
1601 */
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001602/*[clinic input]
1603_sqlite3.Connection.iterdump as pysqlite_connection_iterdump
1604
1605Returns iterator to the dump of the database in an SQL text format.
1606
1607Non-standard.
1608[clinic start generated code]*/
1609
Christian Heimesbbe741d2008-03-28 10:53:29 +00001610static PyObject *
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001611pysqlite_connection_iterdump_impl(pysqlite_Connection *self)
1612/*[clinic end generated code: output=586997aaf9808768 input=53bc907cb5eedb85]*/
Christian Heimesbbe741d2008-03-28 10:53:29 +00001613{
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001614 _Py_IDENTIFIER(_iterdump);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001615 PyObject* retval = NULL;
1616 PyObject* module = NULL;
1617 PyObject* module_dict;
1618 PyObject* pyfn_iterdump;
1619
1620 if (!pysqlite_check_connection(self)) {
1621 goto finally;
1622 }
1623
1624 module = PyImport_ImportModule(MODULE_NAME ".dump");
1625 if (!module) {
1626 goto finally;
1627 }
1628
1629 module_dict = PyModule_GetDict(module);
1630 if (!module_dict) {
1631 goto finally;
1632 }
1633
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001634 pyfn_iterdump = _PyDict_GetItemIdWithError(module_dict, &PyId__iterdump);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001635 if (!pyfn_iterdump) {
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001636 if (!PyErr_Occurred()) {
1637 PyErr_SetString(pysqlite_OperationalError,
1638 "Failed to obtain _iterdump() reference");
1639 }
Christian Heimesbbe741d2008-03-28 10:53:29 +00001640 goto finally;
1641 }
1642
Petr Viktorinffd97532020-02-11 17:46:57 +01001643 retval = PyObject_CallOneArg(pyfn_iterdump, (PyObject *)self);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001644
1645finally:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001646 Py_XDECREF(module);
1647 return retval;
1648}
1649
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001650/*[clinic input]
1651_sqlite3.Connection.backup as pysqlite_connection_backup
1652
Erlend Egeberg Aaslandea465792021-02-11 00:04:02 +01001653 target: object(type='pysqlite_Connection *', subclass_of='pysqlite_ConnectionType')
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001654 *
1655 pages: int = -1
1656 progress: object = None
1657 name: str = "main"
1658 sleep: double = 0.250
1659
1660Makes a backup of the database. Non-standard.
1661[clinic start generated code]*/
1662
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001663static PyObject *
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001664pysqlite_connection_backup_impl(pysqlite_Connection *self,
1665 pysqlite_Connection *target, int pages,
1666 PyObject *progress, const char *name,
1667 double sleep)
Erlend Egeberg Aaslandea465792021-02-11 00:04:02 +01001668/*[clinic end generated code: output=306a3e6a38c36334 input=30ae45fc420bfd3b]*/
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001669{
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001670 int rc;
Pablo Galindoa6d63a22020-12-29 00:28:09 +00001671 int sleep_ms = (int)(sleep * 1000.0);
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001672 sqlite3 *bck_conn;
1673 sqlite3_backup *bck_handle;
Victor Stinnerca405012018-04-30 12:22:17 +02001674
Peter McCormickbfee9fa2020-09-19 23:40:46 -04001675 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1676 return NULL;
1677 }
1678
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001679 if (!pysqlite_check_connection(target)) {
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001680 return NULL;
1681 }
1682
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001683 if (target == self) {
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001684 PyErr_SetString(PyExc_ValueError, "target cannot be the same connection instance");
1685 return NULL;
1686 }
1687
Aviv Palivodabbf7bb72018-03-18 02:48:55 +02001688#if SQLITE_VERSION_NUMBER < 3008008
1689 /* Since 3.8.8 this is already done, per commit
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001690 https://www.sqlite.org/src/info/169b5505498c0a7e */
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001691 if (!sqlite3_get_autocommit(target->db)) {
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001692 PyErr_SetString(pysqlite_OperationalError, "target is in transaction");
1693 return NULL;
1694 }
1695#endif
1696
1697 if (progress != Py_None && !PyCallable_Check(progress)) {
1698 PyErr_SetString(PyExc_TypeError, "progress argument must be a callable");
1699 return NULL;
1700 }
1701
1702 if (pages == 0) {
1703 pages = -1;
1704 }
1705
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001706 bck_conn = target->db;
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001707
1708 Py_BEGIN_ALLOW_THREADS
1709 bck_handle = sqlite3_backup_init(bck_conn, "main", self->db, name);
1710 Py_END_ALLOW_THREADS
1711
Erlend Egeberg Aaslandc1ae7412021-04-14 13:45:49 +02001712 if (bck_handle == NULL) {
1713 _pysqlite_seterror(bck_conn, NULL);
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001714 return NULL;
1715 }
Erlend Egeberg Aaslandc1ae7412021-04-14 13:45:49 +02001716
1717 do {
1718 Py_BEGIN_ALLOW_THREADS
1719 rc = sqlite3_backup_step(bck_handle, pages);
1720 Py_END_ALLOW_THREADS
1721
1722 if (progress != Py_None) {
1723 int remaining = sqlite3_backup_remaining(bck_handle);
1724 int pagecount = sqlite3_backup_pagecount(bck_handle);
1725 PyObject *res = PyObject_CallFunction(progress, "iii", rc,
1726 remaining, pagecount);
1727 if (res == NULL) {
1728 /* Callback failed: abort backup and bail. */
1729 Py_BEGIN_ALLOW_THREADS
1730 sqlite3_backup_finish(bck_handle);
1731 Py_END_ALLOW_THREADS
1732 return NULL;
1733 }
1734 Py_DECREF(res);
1735 }
1736
1737 /* Sleep for a while if there are still further pages to copy and
1738 the engine could not make any progress */
1739 if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) {
1740 Py_BEGIN_ALLOW_THREADS
1741 sqlite3_sleep(sleep_ms);
1742 Py_END_ALLOW_THREADS
1743 }
1744 } while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);
1745
1746 Py_BEGIN_ALLOW_THREADS
1747 rc = sqlite3_backup_finish(bck_handle);
1748 Py_END_ALLOW_THREADS
1749
1750 if (rc != SQLITE_OK) {
1751 _pysqlite_seterror(bck_conn, NULL);
1752 return NULL;
1753 }
1754
1755 Py_RETURN_NONE;
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001756}
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001757
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001758/*[clinic input]
1759_sqlite3.Connection.create_collation as pysqlite_connection_create_collation
1760
1761 name: unicode
1762 callback as callable: object
1763 /
1764
1765Creates a collation function. Non-standard.
1766[clinic start generated code]*/
1767
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001768static PyObject *
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001769pysqlite_connection_create_collation_impl(pysqlite_Connection *self,
1770 PyObject *name, PyObject *callable)
1771/*[clinic end generated code: output=0f63b8995565ae22 input=5c3898813a776cf2]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001772{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001773 PyObject* uppercase_name = 0;
Victor Stinner35466c52010-04-22 11:23:23 +00001774 Py_ssize_t i, len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001775 _Py_IDENTIFIER(upper);
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001776 const char *uppercase_name_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001777 int rc;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001778 unsigned int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001779 const void *data;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001780
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001781 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001782 goto finally;
1783 }
1784
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001785 uppercase_name = _PyObject_CallMethodIdOneArg((PyObject *)&PyUnicode_Type,
1786 &PyId_upper, name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001787 if (!uppercase_name) {
1788 goto finally;
1789 }
1790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001791 if (PyUnicode_READY(uppercase_name))
1792 goto finally;
1793 len = PyUnicode_GET_LENGTH(uppercase_name);
1794 kind = PyUnicode_KIND(uppercase_name);
1795 data = PyUnicode_DATA(uppercase_name);
1796 for (i=0; i<len; i++) {
1797 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1798 if ((ch >= '0' && ch <= '9')
1799 || (ch >= 'A' && ch <= 'Z')
1800 || (ch == '_'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001801 {
Victor Stinner35466c52010-04-22 11:23:23 +00001802 continue;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001803 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001804 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001805 goto finally;
1806 }
1807 }
1808
Serhiy Storchaka06515832016-11-20 09:13:07 +02001809 uppercase_name_str = PyUnicode_AsUTF8(uppercase_name);
Victor Stinner35466c52010-04-22 11:23:23 +00001810 if (!uppercase_name_str)
1811 goto finally;
1812
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001813 if (callable != Py_None && !PyCallable_Check(callable)) {
1814 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1815 goto finally;
1816 }
1817
1818 if (callable != Py_None) {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001819 if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
1820 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001821 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001822 if (PyDict_DelItem(self->collations, uppercase_name) == -1)
1823 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001824 }
1825
1826 rc = sqlite3_create_collation(self->db,
Victor Stinner35466c52010-04-22 11:23:23 +00001827 uppercase_name_str,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001828 SQLITE_UTF8,
1829 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001830 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001831 if (rc != SQLITE_OK) {
Serhiy Storchaka90731802021-01-31 17:42:38 +02001832 if (callable != Py_None) {
1833 if (PyDict_DelItem(self->collations, uppercase_name) < 0) {
1834 PyErr_Clear();
1835 }
1836 }
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001837 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001838 goto finally;
1839 }
1840
1841finally:
1842 Py_XDECREF(uppercase_name);
1843
1844 if (PyErr_Occurred()) {
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +01001845 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001846 }
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +01001847 return Py_NewRef(Py_None);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001848}
1849
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001850/*[clinic input]
1851_sqlite3.Connection.__enter__ as pysqlite_connection_enter
1852
1853Called when the connection is used as a context manager.
1854
1855Returns itself as a convenience to the caller.
1856[clinic start generated code]*/
1857
Christian Heimesbbe741d2008-03-28 10:53:29 +00001858static PyObject *
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001859pysqlite_connection_enter_impl(pysqlite_Connection *self)
1860/*[clinic end generated code: output=457b09726d3e9dcd input=127d7a4f17e86d8f]*/
Christian Heimesbbe741d2008-03-28 10:53:29 +00001861{
Erlend Egeberg Aaslandbf64d902020-12-27 12:05:33 +01001862 return Py_NewRef((PyObject *)self);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001863}
1864
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001865/*[clinic input]
1866_sqlite3.Connection.__exit__ as pysqlite_connection_exit
1867
1868 type as exc_type: object
1869 value as exc_value: object
1870 traceback as exc_tb: object
1871 /
1872
1873Called when the connection is used as a context manager.
1874
1875If there was any exception, a rollback takes place; otherwise we commit.
1876[clinic start generated code]*/
1877
Christian Heimesbbe741d2008-03-28 10:53:29 +00001878static PyObject *
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001879pysqlite_connection_exit_impl(pysqlite_Connection *self, PyObject *exc_type,
1880 PyObject *exc_value, PyObject *exc_tb)
1881/*[clinic end generated code: output=0705200e9321202a input=bd66f1532c9c54a7]*/
Christian Heimesbbe741d2008-03-28 10:53:29 +00001882{
Erlend Egeberg Aasland2a808932021-08-28 20:26:00 +02001883 int commit = 0;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001884 PyObject* result;
1885
Christian Heimesbbe741d2008-03-28 10:53:29 +00001886 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
Erlend Egeberg Aasland2a808932021-08-28 20:26:00 +02001887 commit = 1;
1888 result = pysqlite_connection_commit_impl(self);
1889 }
1890 else {
1891 result = pysqlite_connection_rollback_impl(self);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001892 }
1893
Erlend Egeberg Aasland2a808932021-08-28 20:26:00 +02001894 if (result == NULL) {
1895 if (commit) {
1896 /* Commit failed; try to rollback in order to unlock the database.
1897 * If rollback also fails, chain the exceptions. */
1898 PyObject *exc, *val, *tb;
1899 PyErr_Fetch(&exc, &val, &tb);
1900 result = pysqlite_connection_rollback_impl(self);
1901 if (result == NULL) {
1902 _PyErr_ChainExceptions(exc, val, tb);
1903 }
1904 else {
1905 Py_DECREF(result);
1906 PyErr_Restore(exc, val, tb);
1907 }
1908 }
Christian Heimesbbe741d2008-03-28 10:53:29 +00001909 return NULL;
1910 }
1911 Py_DECREF(result);
1912
1913 Py_RETURN_FALSE;
1914}
1915
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001916static const char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001917PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001918
1919static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001920 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1921 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Berker Peksag59da4b32016-09-12 07:16:43 +03001922 {"in_transaction", (getter)pysqlite_connection_get_in_transaction, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001923 {NULL}
1924};
1925
1926static PyMethodDef connection_methods[] = {
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001927 PYSQLITE_CONNECTION_BACKUP_METHODDEF
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001928 PYSQLITE_CONNECTION_CLOSE_METHODDEF
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001929 PYSQLITE_CONNECTION_COMMIT_METHODDEF
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001930 PYSQLITE_CONNECTION_CREATE_AGGREGATE_METHODDEF
1931 PYSQLITE_CONNECTION_CREATE_COLLATION_METHODDEF
1932 PYSQLITE_CONNECTION_CREATE_FUNCTION_METHODDEF
1933 PYSQLITE_CONNECTION_CURSOR_METHODDEF
1934 PYSQLITE_CONNECTION_ENABLE_LOAD_EXTENSION_METHODDEF
1935 PYSQLITE_CONNECTION_ENTER_METHODDEF
Erlend Egeberg Aasland3ccef1c2020-12-27 09:32:18 +01001936 PYSQLITE_CONNECTION_EXECUTEMANY_METHODDEF
1937 PYSQLITE_CONNECTION_EXECUTESCRIPT_METHODDEF
1938 PYSQLITE_CONNECTION_EXECUTE_METHODDEF
Erlend Egeberg Aasland1ba82bb2020-12-18 15:25:35 +01001939 PYSQLITE_CONNECTION_EXIT_METHODDEF
1940 PYSQLITE_CONNECTION_INTERRUPT_METHODDEF
1941 PYSQLITE_CONNECTION_ITERDUMP_METHODDEF
1942 PYSQLITE_CONNECTION_LOAD_EXTENSION_METHODDEF
1943 PYSQLITE_CONNECTION_ROLLBACK_METHODDEF
1944 PYSQLITE_CONNECTION_SET_AUTHORIZER_METHODDEF
1945 PYSQLITE_CONNECTION_SET_PROGRESS_HANDLER_METHODDEF
1946 PYSQLITE_CONNECTION_SET_TRACE_CALLBACK_METHODDEF
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001947 {NULL, NULL}
1948};
1949
1950static struct PyMemberDef connection_members[] =
1951{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001952 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1953 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1954 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1955 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1956 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1957 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1958 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1959 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1960 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1961 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001962 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1963 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001964 {NULL}
1965};
1966
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001967static PyType_Slot connection_slots[] = {
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -07001968 {Py_tp_dealloc, connection_dealloc},
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001969 {Py_tp_doc, (void *)connection_doc},
1970 {Py_tp_methods, connection_methods},
1971 {Py_tp_members, connection_members},
1972 {Py_tp_getset, connection_getset},
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001973 {Py_tp_init, pysqlite_connection_init},
1974 {Py_tp_call, pysqlite_connection_call},
Miss Islington (bot)e8d9df02021-05-25 11:08:39 -07001975 {Py_tp_traverse, connection_traverse},
1976 {Py_tp_clear, connection_clear},
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001977 {0, NULL},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001978};
1979
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001980static PyType_Spec connection_spec = {
1981 .name = MODULE_NAME ".Connection",
1982 .basicsize = sizeof(pysqlite_Connection),
Miss Islington (bot)7297d742021-06-17 03:19:44 -07001983 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1984 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001985 .slots = connection_slots,
1986};
1987
1988PyTypeObject *pysqlite_ConnectionType = NULL;
1989
Erlend Egeberg Aasland38b6c2a2021-02-21 11:07:49 +01001990int
1991pysqlite_connection_setup_types(PyObject *module)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001992{
Erlend Egeberg Aasland256e54a2020-10-01 16:03:21 +02001993 pysqlite_ConnectionType = (PyTypeObject *)PyType_FromModuleAndSpec(module, &connection_spec, NULL);
1994 if (pysqlite_ConnectionType == NULL) {
1995 return -1;
1996 }
1997 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001998}