blob: 1bf9710763a5abaf50425e32ae69364586542dd8 [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
Gerhard Häringf9cee222010-03-05 15:20:03 +000036#if SQLITE_VERSION_NUMBER >= 3003008
37#ifndef SQLITE_OMIT_LOAD_EXTENSION
38#define HAVE_LOAD_EXTENSION
39#endif
40#endif
41
Emanuele Gaifasd7aed412018-03-10 23:08:31 +010042#if SQLITE_VERSION_NUMBER >= 3006011
43#define HAVE_BACKUP_API
44#endif
45
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +020046#if SQLITE_VERSION_NUMBER >= 3014000
47#define HAVE_TRACE_V2
48#endif
49
Martin v. Löwise75fc142013-11-07 18:46:53 +010050_Py_IDENTIFIER(cursor);
51
Serhiy Storchaka28914922016-09-01 22:18:03 +030052static const char * const begin_statements[] = {
53 "BEGIN ",
54 "BEGIN DEFERRED",
55 "BEGIN IMMEDIATE",
56 "BEGIN EXCLUSIVE",
57 NULL
58};
59
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +020060static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored));
Gerhard Häringf9cee222010-03-05 15:20:03 +000061static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000062
Thomas Wouters0e3f5912006-08-11 14:57:12 +000063
Benjamin Petersond7b03282008-09-13 15:58:53 +000064static void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000065{
66 /* in older SQLite versions, calling sqlite3_result_error in callbacks
67 * triggers a bug in SQLite that leads either to irritating results or
68 * segfaults, depending on the SQLite version */
69#if SQLITE_VERSION_NUMBER >= 3003003
70 sqlite3_result_error(ctx, errmsg, len);
71#else
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000072 PyErr_SetString(pysqlite_OperationalError, errmsg);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073#endif
74}
75
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +000076int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000077{
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010078 static char *kwlist[] = {
79 "database", "timeout", "detect_types", "isolation_level",
80 "check_same_thread", "factory", "cached_statements", "uri",
81 NULL
82 };
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000083
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +030084 const char* database;
Anders Lorentsena22a1272017-11-07 01:47:43 +010085 PyObject* database_obj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000086 int detect_types = 0;
87 PyObject* isolation_level = NULL;
88 PyObject* factory = NULL;
89 int check_same_thread = 1;
90 int cached_statements = 100;
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010091 int uri = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000092 double timeout = 5.0;
93 int rc;
94
Anders Lorentsena22a1272017-11-07 01:47:43 +010095 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|diOiOip", kwlist,
96 PyUnicode_FSConverter, &database_obj, &timeout, &detect_types,
Antoine Pitrou902fc8b2013-02-10 00:02:44 +010097 &isolation_level, &check_same_thread,
98 &factory, &cached_statements, &uri))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000099 {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000100 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000101 }
102
Anders Lorentsena22a1272017-11-07 01:47:43 +0100103 database = PyBytes_AsString(database_obj);
104
Gerhard Häringf9cee222010-03-05 15:20:03 +0000105 self->initialized = 1;
106
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000107 self->begin_statement = NULL;
108
Oren Milman93c5a5d2017-10-10 22:27:46 +0300109 Py_CLEAR(self->statement_cache);
110 Py_CLEAR(self->statements);
111 Py_CLEAR(self->cursors);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000112
113 Py_INCREF(Py_None);
Oren Milman93c5a5d2017-10-10 22:27:46 +0300114 Py_XSETREF(self->row_factory, Py_None);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000115
116 Py_INCREF(&PyUnicode_Type);
Oren Milman93c5a5d2017-10-10 22:27:46 +0300117 Py_XSETREF(self->text_factory, (PyObject*)&PyUnicode_Type);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100119#ifdef SQLITE_OPEN_URI
120 Py_BEGIN_ALLOW_THREADS
121 rc = sqlite3_open_v2(database, &self->db,
122 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
123 (uri ? SQLITE_OPEN_URI : 0), NULL);
124#else
125 if (uri) {
126 PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
127 return -1;
128 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000129 Py_BEGIN_ALLOW_THREADS
Aviv Palivoda86a67052017-03-03 12:58:17 +0200130 /* No need to use sqlite3_open_v2 as sqlite3_open(filename, db) is the
131 same as sqlite3_open_v2(filename, db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL). */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000132 rc = sqlite3_open(database, &self->db);
Antoine Pitrou902fc8b2013-02-10 00:02:44 +0100133#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000134 Py_END_ALLOW_THREADS
135
Anders Lorentsena22a1272017-11-07 01:47:43 +0100136 Py_DECREF(database_obj);
137
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000138 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000139 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000140 return -1;
141 }
142
143 if (!isolation_level) {
Neal Norwitzefee9f52007-10-27 02:50:52 +0000144 isolation_level = PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000145 if (!isolation_level) {
146 return -1;
147 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000148 } else {
149 Py_INCREF(isolation_level);
150 }
Oren Milman93c5a5d2017-10-10 22:27:46 +0300151 Py_CLEAR(self->isolation_level);
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +0200152 if (pysqlite_connection_set_isolation_level(self, isolation_level, NULL) < 0) {
Victor Stinnercb1f74e2013-12-19 16:38:03 +0100153 Py_DECREF(isolation_level);
154 return -1;
155 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000156 Py_DECREF(isolation_level);
157
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000158 self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000159 if (PyErr_Occurred()) {
160 return -1;
161 }
162
Gerhard Häringf9cee222010-03-05 15:20:03 +0000163 self->created_statements = 0;
164 self->created_cursors = 0;
165
166 /* Create lists of weak references to statements/cursors */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000167 self->statements = PyList_New(0);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000168 self->cursors = PyList_New(0);
169 if (!self->statements || !self->cursors) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000170 return -1;
171 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000172
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000173 /* By default, the Cache class INCREFs the factory in its initializer, and
174 * decrefs it in its deallocator method. Since this would create a circular
175 * reference here, we're breaking it by decrementing self, and telling the
176 * cache class to not decref the factory (self) in its deallocator.
177 */
178 self->statement_cache->decref_factory = 0;
179 Py_DECREF(self);
180
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000181 self->detect_types = detect_types;
182 self->timeout = timeout;
183 (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184 self->thread_ident = PyThread_get_thread_ident();
Berker Peksag7bea2342016-06-12 14:09:51 +0300185 if (!check_same_thread && sqlite3_libversion_number() < 3003001) {
186 PyErr_SetString(pysqlite_NotSupportedError, "shared connections not available");
187 return -1;
188 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000189 self->check_same_thread = check_same_thread;
190
gescheitb9a03762019-07-13 06:15:49 +0300191 self->function_pinboard_trace_callback = NULL;
192 self->function_pinboard_progress_handler = NULL;
193 self->function_pinboard_authorizer_cb = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194
Oren Milman93c5a5d2017-10-10 22:27:46 +0300195 Py_XSETREF(self->collations, PyDict_New());
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000196 if (!self->collations) {
197 return -1;
198 }
199
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000200 self->Warning = pysqlite_Warning;
201 self->Error = pysqlite_Error;
202 self->InterfaceError = pysqlite_InterfaceError;
203 self->DatabaseError = pysqlite_DatabaseError;
204 self->DataError = pysqlite_DataError;
205 self->OperationalError = pysqlite_OperationalError;
206 self->IntegrityError = pysqlite_IntegrityError;
207 self->InternalError = pysqlite_InternalError;
208 self->ProgrammingError = pysqlite_ProgrammingError;
209 self->NotSupportedError = pysqlite_NotSupportedError;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210
211 return 0;
212}
213
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000214/* action in (ACTION_RESET, ACTION_FINALIZE) */
Gerhard Häringf9cee222010-03-05 15:20:03 +0000215void pysqlite_do_all_statements(pysqlite_Connection* self, int action, int reset_cursors)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000217 int i;
218 PyObject* weakref;
219 PyObject* statement;
Gerhard Häringf9cee222010-03-05 15:20:03 +0000220 pysqlite_Cursor* cursor;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000221
Thomas Wouters477c8d52006-05-27 19:21:47 +0000222 for (i = 0; i < PyList_Size(self->statements); i++) {
223 weakref = PyList_GetItem(self->statements, i);
224 statement = PyWeakref_GetObject(weakref);
225 if (statement != Py_None) {
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500226 Py_INCREF(statement);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000227 if (action == ACTION_RESET) {
228 (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
229 } else {
230 (void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
231 }
Benjamin Peterson5c2b09e2011-05-31 21:31:37 -0500232 Py_DECREF(statement);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000233 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000234 }
Gerhard Häringf9cee222010-03-05 15:20:03 +0000235
236 if (reset_cursors) {
237 for (i = 0; i < PyList_Size(self->cursors); i++) {
238 weakref = PyList_GetItem(self->cursors, i);
239 cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
240 if ((PyObject*)cursor != Py_None) {
241 cursor->reset = 1;
242 }
243 }
244 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000245}
246
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000247void pysqlite_connection_dealloc(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000248{
249 Py_XDECREF(self->statement_cache);
250
251 /* Clean up if user has not called .close() explicitly. */
252 if (self->db) {
Aviv Palivoda86a67052017-03-03 12:58:17 +0200253 SQLITE3_CLOSE(self->db);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000254 }
255
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000256 Py_XDECREF(self->isolation_level);
gescheitb9a03762019-07-13 06:15:49 +0300257 Py_XDECREF(self->function_pinboard_trace_callback);
258 Py_XDECREF(self->function_pinboard_progress_handler);
259 Py_XDECREF(self->function_pinboard_authorizer_cb);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000260 Py_XDECREF(self->row_factory);
261 Py_XDECREF(self->text_factory);
262 Py_XDECREF(self->collations);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000263 Py_XDECREF(self->statements);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000264 Py_XDECREF(self->cursors);
Christian Heimes90aa7642007-12-19 02:45:37 +0000265 Py_TYPE(self)->tp_free((PyObject*)self);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000266}
267
Gerhard Häringf9cee222010-03-05 15:20:03 +0000268/*
269 * Registers a cursor with the connection.
270 *
271 * 0 => error; 1 => ok
272 */
273int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
274{
275 PyObject* weakref;
276
277 weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
278 if (!weakref) {
279 goto error;
280 }
281
282 if (PyList_Append(connection->cursors, weakref) != 0) {
283 Py_CLEAR(weakref);
284 goto error;
285 }
286
287 Py_DECREF(weakref);
288
289 return 1;
290error:
291 return 0;
292}
293
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000294PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000295{
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300296 static char *kwlist[] = {"factory", NULL};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000297 PyObject* factory = NULL;
298 PyObject* cursor;
299
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000300 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
301 &factory)) {
302 return NULL;
303 }
304
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000305 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000306 return NULL;
307 }
308
309 if (factory == NULL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000310 factory = (PyObject*)&pysqlite_CursorType;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000311 }
312
Petr Viktorinffd97532020-02-11 17:46:57 +0100313 cursor = PyObject_CallOneArg(factory, (PyObject *)self);
Serhiy Storchakaef113cd2016-08-29 14:29:55 +0300314 if (cursor == NULL)
315 return NULL;
316 if (!PyObject_TypeCheck(cursor, &pysqlite_CursorType)) {
317 PyErr_Format(PyExc_TypeError,
318 "factory must return a cursor, not %.100s",
319 Py_TYPE(cursor)->tp_name);
320 Py_DECREF(cursor);
321 return NULL;
322 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000323
Gerhard Häringf9cee222010-03-05 15:20:03 +0000324 _pysqlite_drop_unused_cursor_references(self);
325
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000326 if (cursor && self->row_factory != Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000327 Py_INCREF(self->row_factory);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300328 Py_XSETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000329 }
330
331 return cursor;
332}
333
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000334PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000335{
336 int rc;
337
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000338 if (!pysqlite_check_thread(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000339 return NULL;
340 }
341
Gerhard Häringf9cee222010-03-05 15:20:03 +0000342 pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000343
344 if (self->db) {
Aviv Palivoda86a67052017-03-03 12:58:17 +0200345 rc = SQLITE3_CLOSE(self->db);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000346
347 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000348 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000349 return NULL;
350 } else {
351 self->db = NULL;
352 }
353 }
354
Berker Peksagfe21de92016-04-09 07:34:39 +0300355 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000356}
357
358/*
359 * Checks if a connection object is usable (i. e. not closed).
360 *
361 * 0 => error; 1 => ok
362 */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000363int pysqlite_check_connection(pysqlite_Connection* con)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000364{
Gerhard Häringf9cee222010-03-05 15:20:03 +0000365 if (!con->initialized) {
366 PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
367 return 0;
368 }
369
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000370 if (!con->db) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000371 PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000372 return 0;
373 } else {
374 return 1;
375 }
376}
377
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000378PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000379{
380 int rc;
381 const char* tail;
382 sqlite3_stmt* statement;
383
384 Py_BEGIN_ALLOW_THREADS
Benjamin Peterson52526942017-09-20 07:36:18 -0700385 rc = sqlite3_prepare_v2(self->db, self->begin_statement, -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000386 Py_END_ALLOW_THREADS
387
388 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000389 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000390 goto error;
391 }
392
Benjamin Petersond7b03282008-09-13 15:58:53 +0000393 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300394 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000395 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000396 }
397
398 Py_BEGIN_ALLOW_THREADS
399 rc = sqlite3_finalize(statement);
400 Py_END_ALLOW_THREADS
401
402 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000403 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000404 }
405
406error:
407 if (PyErr_Occurred()) {
408 return NULL;
409 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200410 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000411 }
412}
413
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000414PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000415{
416 int rc;
417 const char* tail;
418 sqlite3_stmt* statement;
419
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000420 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000421 return NULL;
422 }
423
Berker Peksag59da4b32016-09-12 07:16:43 +0300424 if (!sqlite3_get_autocommit(self->db)) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000425
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000426 Py_BEGIN_ALLOW_THREADS
Benjamin Peterson52526942017-09-20 07:36:18 -0700427 rc = sqlite3_prepare_v2(self->db, "COMMIT", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000428 Py_END_ALLOW_THREADS
429 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000430 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000431 goto error;
432 }
433
Benjamin Petersond7b03282008-09-13 15:58:53 +0000434 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300435 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000436 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000437 }
438
439 Py_BEGIN_ALLOW_THREADS
440 rc = sqlite3_finalize(statement);
441 Py_END_ALLOW_THREADS
442 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000443 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000444 }
445
446 }
447
448error:
449 if (PyErr_Occurred()) {
450 return NULL;
451 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200452 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000453 }
454}
455
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000456PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000457{
458 int rc;
459 const char* tail;
460 sqlite3_stmt* statement;
461
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000462 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000463 return NULL;
464 }
465
Berker Peksag59da4b32016-09-12 07:16:43 +0300466 if (!sqlite3_get_autocommit(self->db)) {
Gerhard Häringf9cee222010-03-05 15:20:03 +0000467 pysqlite_do_all_statements(self, ACTION_RESET, 1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000468
469 Py_BEGIN_ALLOW_THREADS
Benjamin Peterson52526942017-09-20 07:36:18 -0700470 rc = sqlite3_prepare_v2(self->db, "ROLLBACK", -1, &statement, &tail);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000471 Py_END_ALLOW_THREADS
472 if (rc != SQLITE_OK) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000473 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000474 goto error;
475 }
476
Benjamin Petersond7b03282008-09-13 15:58:53 +0000477 rc = pysqlite_step(statement, self);
Berker Peksag59da4b32016-09-12 07:16:43 +0300478 if (rc != SQLITE_DONE) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000479 _pysqlite_seterror(self->db, statement);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000480 }
481
482 Py_BEGIN_ALLOW_THREADS
483 rc = sqlite3_finalize(statement);
484 Py_END_ALLOW_THREADS
485 if (rc != SQLITE_OK && !PyErr_Occurred()) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000486 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000487 }
488
489 }
490
491error:
492 if (PyErr_Occurred()) {
493 return NULL;
494 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200495 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000496 }
497}
498
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200499static int
500_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000501{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200502 if (py_val == Py_None) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000503 sqlite3_result_null(context);
Christian Heimes217cfd12007-12-02 14:31:20 +0000504 } else if (PyLong_Check(py_val)) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200505 sqlite_int64 value = _pysqlite_long_as_int64(py_val);
506 if (value == -1 && PyErr_Occurred())
507 return -1;
508 sqlite3_result_int64(context, value);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000509 } else if (PyFloat_Check(py_val)) {
510 sqlite3_result_double(context, PyFloat_AsDouble(py_val));
Guido van Rossumbae07c92007-10-08 02:46:15 +0000511 } else if (PyUnicode_Check(py_val)) {
Serhiy Storchaka06515832016-11-20 09:13:07 +0200512 const char *str = PyUnicode_AsUTF8(py_val);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200513 if (str == NULL)
514 return -1;
515 sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT);
Guido van Rossumbae07c92007-10-08 02:46:15 +0000516 } else if (PyObject_CheckBuffer(py_val)) {
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200517 Py_buffer view;
518 if (PyObject_GetBuffer(py_val, &view, PyBUF_SIMPLE) != 0) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100519 PyErr_SetString(PyExc_ValueError,
520 "could not convert BLOB to buffer");
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200521 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000522 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200523 if (view.len > INT_MAX) {
Victor Stinner83ed42b2013-11-18 01:24:31 +0100524 PyErr_SetString(PyExc_OverflowError,
525 "BLOB longer than INT_MAX bytes");
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200526 PyBuffer_Release(&view);
Victor Stinner83ed42b2013-11-18 01:24:31 +0100527 return -1;
528 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200529 sqlite3_result_blob(context, view.buf, (int)view.len, SQLITE_TRANSIENT);
530 PyBuffer_Release(&view);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000531 } else {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200532 return -1;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000533 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200534 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000535}
536
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000537PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000538{
539 PyObject* args;
540 int i;
541 sqlite3_value* cur_value;
542 PyObject* cur_py_value;
543 const char* val_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000544 Py_ssize_t buflen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000545
546 args = PyTuple_New(argc);
547 if (!args) {
548 return NULL;
549 }
550
551 for (i = 0; i < argc; i++) {
552 cur_value = argv[i];
553 switch (sqlite3_value_type(argv[i])) {
554 case SQLITE_INTEGER:
Sergey Fedoseevb6f5b9d2019-10-23 13:09:01 +0500555 cur_py_value = PyLong_FromLongLong(sqlite3_value_int64(cur_value));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000556 break;
557 case SQLITE_FLOAT:
558 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
559 break;
560 case SQLITE_TEXT:
561 val_str = (const char*)sqlite3_value_text(cur_value);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000562 cur_py_value = PyUnicode_FromString(val_str);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000563 /* TODO: have a way to show errors here */
564 if (!cur_py_value) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000565 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000566 Py_INCREF(Py_None);
567 cur_py_value = Py_None;
568 }
569 break;
570 case SQLITE_BLOB:
571 buflen = sqlite3_value_bytes(cur_value);
Christian Heimes72b710a2008-05-26 13:28:38 +0000572 cur_py_value = PyBytes_FromStringAndSize(
Guido van Rossumbae07c92007-10-08 02:46:15 +0000573 sqlite3_value_blob(cur_value), buflen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000574 break;
575 case SQLITE_NULL:
576 default:
577 Py_INCREF(Py_None);
578 cur_py_value = Py_None;
579 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000580
581 if (!cur_py_value) {
582 Py_DECREF(args);
583 return NULL;
584 }
585
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000586 PyTuple_SetItem(args, i, cur_py_value);
587
588 }
589
590 return args;
591}
592
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000593void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000594{
595 PyObject* args;
596 PyObject* py_func;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000597 PyObject* py_retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200598 int ok;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000599
600 PyGILState_STATE threadstate;
601
602 threadstate = PyGILState_Ensure();
603
604 py_func = (PyObject*)sqlite3_user_data(context);
605
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000606 args = _pysqlite_build_py_params(context, argc, argv);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000607 if (args) {
608 py_retval = PyObject_CallObject(py_func, args);
609 Py_DECREF(args);
610 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000611
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200612 ok = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000613 if (py_retval) {
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200614 ok = _pysqlite_set_result(context, py_retval) == 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000615 Py_DECREF(py_retval);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200616 }
617 if (!ok) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700618 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000619 PyErr_Print();
620 } else {
621 PyErr_Clear();
622 }
623 _sqlite3_result_error(context, "user-defined function raised exception", -1);
624 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000625
626 PyGILState_Release(threadstate);
627}
628
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000629static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000630{
631 PyObject* args;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000632 PyObject* function_result = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000633 PyObject* aggregate_class;
634 PyObject** aggregate_instance;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000635 PyObject* stepmethod = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000636
637 PyGILState_STATE threadstate;
638
639 threadstate = PyGILState_Ensure();
640
641 aggregate_class = (PyObject*)sqlite3_user_data(context);
642
643 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
644
Serhiy Storchaka0b3ec192017-03-23 17:53:47 +0200645 if (*aggregate_instance == NULL) {
Victor Stinner070c4d72016-12-09 12:29:18 +0100646 *aggregate_instance = _PyObject_CallNoArg(aggregate_class);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000647
Thomas Wouters477c8d52006-05-27 19:21:47 +0000648 if (PyErr_Occurred()) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000649 *aggregate_instance = 0;
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700650 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000651 PyErr_Print();
652 } else {
653 PyErr_Clear();
654 }
655 _sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000656 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000657 }
658 }
659
660 stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000661 if (!stepmethod) {
662 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000663 }
664
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000665 args = _pysqlite_build_py_params(context, argc, params);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000666 if (!args) {
667 goto error;
668 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000669
670 function_result = PyObject_CallObject(stepmethod, args);
671 Py_DECREF(args);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000672
Thomas Wouters477c8d52006-05-27 19:21:47 +0000673 if (!function_result) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700674 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000675 PyErr_Print();
676 } else {
677 PyErr_Clear();
678 }
679 _sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000680 }
681
Thomas Wouters477c8d52006-05-27 19:21:47 +0000682error:
683 Py_XDECREF(stepmethod);
684 Py_XDECREF(function_result);
685
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000686 PyGILState_Release(threadstate);
687}
688
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000689void _pysqlite_final_callback(sqlite3_context* context)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000690{
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200691 PyObject* function_result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000692 PyObject** aggregate_instance;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200693 _Py_IDENTIFIER(finalize);
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200694 int ok;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200695 PyObject *exception, *value, *tb;
Victor Stinnerffff7632013-08-02 01:48:10 +0200696 int restore;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000697
698 PyGILState_STATE threadstate;
699
700 threadstate = PyGILState_Ensure();
701
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000702 aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
703 if (!*aggregate_instance) {
704 /* this branch is executed if there was an exception in the aggregate's
705 * __init__ */
706
Thomas Wouters477c8d52006-05-27 19:21:47 +0000707 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000708 }
709
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200710 /* Keep the exception (if any) of the last call to step() */
711 PyErr_Fetch(&exception, &value, &tb);
Victor Stinnerffff7632013-08-02 01:48:10 +0200712 restore = 1;
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200713
Jeroen Demeyer762f93f2019-07-08 10:19:25 +0200714 function_result = _PyObject_CallMethodIdNoArgs(*aggregate_instance, &PyId_finalize);
Victor Stinnere9af4cf2013-07-18 01:42:04 +0200715
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +0200716 Py_DECREF(*aggregate_instance);
717
718 ok = 0;
719 if (function_result) {
720 ok = _pysqlite_set_result(context, function_result) == 0;
721 Py_DECREF(function_result);
722 }
723 if (!ok) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700724 if (_pysqlite_enable_callback_tracebacks) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000725 PyErr_Print();
726 } else {
727 PyErr_Clear();
728 }
729 _sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
Victor Stinnerffff7632013-08-02 01:48:10 +0200730#if SQLITE_VERSION_NUMBER < 3003003
731 /* with old SQLite versions, _sqlite3_result_error() sets a new Python
732 exception, so don't restore the previous exception */
733 restore = 0;
734#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000735 }
736
Victor Stinnerffff7632013-08-02 01:48:10 +0200737 if (restore) {
738 /* Restore the exception (if any) of the last call to step(),
739 but clear also the current exception if finalize() failed */
740 PyErr_Restore(exception, value, tb);
741 }
Victor Stinner3a857322013-07-22 08:34:32 +0200742
Thomas Wouters477c8d52006-05-27 19:21:47 +0000743error:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000744 PyGILState_Release(threadstate);
745}
746
Gerhard Häringf9cee222010-03-05 15:20:03 +0000747static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000748{
749 PyObject* new_list;
750 PyObject* weakref;
751 int i;
752
753 /* we only need to do this once in a while */
754 if (self->created_statements++ < 200) {
755 return;
756 }
757
758 self->created_statements = 0;
759
760 new_list = PyList_New(0);
761 if (!new_list) {
762 return;
763 }
764
765 for (i = 0; i < PyList_Size(self->statements); i++) {
766 weakref = PyList_GetItem(self->statements, i);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000767 if (PyWeakref_GetObject(weakref) != Py_None) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000768 if (PyList_Append(new_list, weakref) != 0) {
769 Py_DECREF(new_list);
770 return;
771 }
772 }
773 }
774
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300775 Py_SETREF(self->statements, new_list);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000777
Gerhard Häringf9cee222010-03-05 15:20:03 +0000778static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
779{
780 PyObject* new_list;
781 PyObject* weakref;
782 int i;
783
784 /* we only need to do this once in a while */
785 if (self->created_cursors++ < 200) {
786 return;
787 }
788
789 self->created_cursors = 0;
790
791 new_list = PyList_New(0);
792 if (!new_list) {
793 return;
794 }
795
796 for (i = 0; i < PyList_Size(self->cursors); i++) {
797 weakref = PyList_GetItem(self->cursors, i);
798 if (PyWeakref_GetObject(weakref) != Py_None) {
799 if (PyList_Append(new_list, weakref) != 0) {
800 Py_DECREF(new_list);
801 return;
802 }
803 }
804 }
805
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300806 Py_SETREF(self->cursors, new_list);
Gerhard Häringf9cee222010-03-05 15:20:03 +0000807}
808
gescheitb9a03762019-07-13 06:15:49 +0300809static void _destructor(void* args)
810{
811 Py_DECREF((PyObject*)args);
812}
813
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000814PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000815{
Sergey Fedoseev08308582018-07-08 12:09:20 +0500816 static char *kwlist[] = {"name", "narg", "func", "deterministic", NULL};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000817
818 PyObject* func;
819 char* name;
820 int narg;
821 int rc;
Sergey Fedoseev08308582018-07-08 12:09:20 +0500822 int deterministic = 0;
823 int flags = SQLITE_UTF8;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000824
Gerhard Häringf9cee222010-03-05 15:20:03 +0000825 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
826 return NULL;
827 }
828
Sergey Fedoseev08308582018-07-08 12:09:20 +0500829 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO|$p", kwlist,
830 &name, &narg, &func, &deterministic))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831 {
832 return NULL;
833 }
834
Sergey Fedoseev08308582018-07-08 12:09:20 +0500835 if (deterministic) {
836#if SQLITE_VERSION_NUMBER < 3008003
837 PyErr_SetString(pysqlite_NotSupportedError,
838 "deterministic=True requires SQLite 3.8.3 or higher");
839 return NULL;
840#else
841 if (sqlite3_libversion_number() < 3008003) {
842 PyErr_SetString(pysqlite_NotSupportedError,
843 "deterministic=True requires SQLite 3.8.3 or higher");
844 return NULL;
845 }
846 flags |= SQLITE_DETERMINISTIC;
847#endif
848 }
gescheitb9a03762019-07-13 06:15:49 +0300849 Py_INCREF(func);
850 rc = sqlite3_create_function_v2(self->db,
851 name,
852 narg,
853 flags,
854 (void*)func,
855 _pysqlite_func_callback,
856 NULL,
857 NULL,
858 &_destructor); // will decref func
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000859
Thomas Wouters477c8d52006-05-27 19:21:47 +0000860 if (rc != SQLITE_OK) {
861 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000862 PyErr_SetString(pysqlite_OperationalError, "Error creating function");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000863 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000864 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +0500865 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000866}
867
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000868PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000869{
870 PyObject* aggregate_class;
871
872 int n_arg;
873 char* name;
874 static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
875 int rc;
876
Gerhard Häringf9cee222010-03-05 15:20:03 +0000877 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
878 return NULL;
879 }
880
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000881 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
882 kwlist, &name, &n_arg, &aggregate_class)) {
883 return NULL;
884 }
gescheitb9a03762019-07-13 06:15:49 +0300885 Py_INCREF(aggregate_class);
886 rc = sqlite3_create_function_v2(self->db,
887 name,
888 n_arg,
889 SQLITE_UTF8,
890 (void*)aggregate_class,
891 0,
892 &_pysqlite_step_callback,
893 &_pysqlite_final_callback,
894 &_destructor); // will decref func
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000895 if (rc != SQLITE_OK) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000896 /* Workaround for SQLite bug: no error code or string is available here */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000897 PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000898 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000899 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +0500900 Py_RETURN_NONE;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000901}
902
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000903static 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 +0000904{
905 PyObject *ret;
906 int rc;
907 PyGILState_STATE gilstate;
908
909 gilstate = PyGILState_Ensure();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000910
Victor Stinnerd4095d92013-07-26 22:23:33 +0200911 ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000912
Victor Stinnerd4095d92013-07-26 22:23:33 +0200913 if (ret == NULL) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700914 if (_pysqlite_enable_callback_tracebacks)
Victor Stinnerd4095d92013-07-26 22:23:33 +0200915 PyErr_Print();
916 else
917 PyErr_Clear();
Victor Stinner41801f52013-07-21 13:05:38 +0200918
Victor Stinnerd4095d92013-07-26 22:23:33 +0200919 rc = SQLITE_DENY;
Victor Stinner41801f52013-07-21 13:05:38 +0200920 }
921 else {
Victor Stinnerd4095d92013-07-26 22:23:33 +0200922 if (PyLong_Check(ret)) {
923 rc = _PyLong_AsInt(ret);
924 if (rc == -1 && PyErr_Occurred()) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700925 if (_pysqlite_enable_callback_tracebacks)
Victor Stinnerd4095d92013-07-26 22:23:33 +0200926 PyErr_Print();
927 else
928 PyErr_Clear();
929 rc = SQLITE_DENY;
930 }
931 }
932 else {
933 rc = SQLITE_DENY;
934 }
935 Py_DECREF(ret);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000936 }
937
938 PyGILState_Release(gilstate);
939 return rc;
940}
941
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000942static int _progress_handler(void* user_arg)
943{
944 int rc;
945 PyObject *ret;
946 PyGILState_STATE gilstate;
947
948 gilstate = PyGILState_Ensure();
Victor Stinner070c4d72016-12-09 12:29:18 +0100949 ret = _PyObject_CallNoArg((PyObject*)user_arg);
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000950
951 if (!ret) {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -0700952 if (_pysqlite_enable_callback_tracebacks) {
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000953 PyErr_Print();
954 } else {
955 PyErr_Clear();
956 }
957
Mark Dickinson934896d2009-02-21 20:59:32 +0000958 /* abort query if error occurred */
Victor Stinner86999502010-05-19 01:27:23 +0000959 rc = 1;
Gerhard Häringe7ea7452008-03-29 00:45:29 +0000960 } else {
961 rc = (int)PyObject_IsTrue(ret);
962 Py_DECREF(ret);
963 }
964
965 PyGILState_Release(gilstate);
966 return rc;
967}
968
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +0200969#ifdef HAVE_TRACE_V2
970/*
971 * From https://sqlite.org/c3ref/trace_v2.html:
972 * The integer return value from the callback is currently ignored, though this
973 * may change in future releases. Callback implementations should return zero
974 * to ensure future compatibility.
975 */
976static int _trace_callback(unsigned int type, void* user_arg, void* prepared_statement, void* statement_string)
977#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200978static void _trace_callback(void* user_arg, const char* statement_string)
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +0200979#endif
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200980{
981 PyObject *py_statement = NULL;
982 PyObject *ret = NULL;
983
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200984 PyGILState_STATE gilstate;
985
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +0200986#ifdef HAVE_TRACE_V2
987 if (type != SQLITE_TRACE_STMT) {
988 return 0;
989 }
990#endif
991
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200992 gilstate = PyGILState_Ensure();
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200993 py_statement = PyUnicode_DecodeUTF8(statement_string,
994 strlen(statement_string), "replace");
995 if (py_statement) {
Petr Viktorinffd97532020-02-11 17:46:57 +0100996 ret = PyObject_CallOneArg((PyObject*)user_arg, py_statement);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +0200997 Py_DECREF(py_statement);
998 }
999
1000 if (ret) {
1001 Py_DECREF(ret);
1002 } else {
Benjamin Peterson7762e4d2018-07-09 21:20:23 -07001003 if (_pysqlite_enable_callback_tracebacks) {
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001004 PyErr_Print();
1005 } else {
1006 PyErr_Clear();
1007 }
1008 }
1009
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001010 PyGILState_Release(gilstate);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001011#ifdef HAVE_TRACE_V2
1012 return 0;
1013#endif
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001014}
1015
Gerhard Häringf9cee222010-03-05 15:20:03 +00001016static PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001017{
1018 PyObject* authorizer_cb;
1019
1020 static char *kwlist[] = { "authorizer_callback", NULL };
1021 int rc;
1022
Gerhard Häringf9cee222010-03-05 15:20:03 +00001023 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1024 return NULL;
1025 }
1026
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001027 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
1028 kwlist, &authorizer_cb)) {
1029 return NULL;
1030 }
1031
1032 rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001033 if (rc != SQLITE_OK) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001034 PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
gescheitb9a03762019-07-13 06:15:49 +03001035 Py_XSETREF(self->function_pinboard_authorizer_cb, NULL);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001036 return NULL;
gescheitb9a03762019-07-13 06:15:49 +03001037 } else {
1038 Py_INCREF(authorizer_cb);
1039 Py_XSETREF(self->function_pinboard_authorizer_cb, authorizer_cb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001040 }
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +05001041 Py_RETURN_NONE;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001042}
1043
Gerhard Häringf9cee222010-03-05 15:20:03 +00001044static PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001045{
1046 PyObject* progress_handler;
1047 int n;
1048
1049 static char *kwlist[] = { "progress_handler", "n", NULL };
1050
Gerhard Häringf9cee222010-03-05 15:20:03 +00001051 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1052 return NULL;
1053 }
1054
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001055 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
1056 kwlist, &progress_handler, &n)) {
1057 return NULL;
1058 }
1059
1060 if (progress_handler == Py_None) {
1061 /* None clears the progress handler previously set */
1062 sqlite3_progress_handler(self->db, 0, 0, (void*)0);
gescheitb9a03762019-07-13 06:15:49 +03001063 Py_XSETREF(self->function_pinboard_progress_handler, NULL);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001064 } else {
Sergey Fedoseev5b25f1d2018-12-05 22:50:26 +05001065 sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
gescheitb9a03762019-07-13 06:15:49 +03001066 Py_INCREF(progress_handler);
1067 Py_XSETREF(self->function_pinboard_progress_handler, progress_handler);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001068 }
Berker Peksagfe21de92016-04-09 07:34:39 +03001069 Py_RETURN_NONE;
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001070}
1071
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001072/*
1073 * Ref.
1074 * - https://sqlite.org/c3ref/c_trace.html
1075 * - https://sqlite.org/c3ref/trace_v2.html
1076 */
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001077static PyObject* pysqlite_connection_set_trace_callback(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
1078{
1079 PyObject* trace_callback;
1080
1081 static char *kwlist[] = { "trace_callback", NULL };
1082
1083 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1084 return NULL;
1085 }
1086
1087 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_trace_callback",
1088 kwlist, &trace_callback)) {
1089 return NULL;
1090 }
1091
1092 if (trace_callback == Py_None) {
1093 /* None clears the trace callback previously set */
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001094#ifdef HAVE_TRACE_V2
1095 sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, 0, 0);
1096#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001097 sqlite3_trace(self->db, 0, (void*)0);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001098#endif
gescheitb9a03762019-07-13 06:15:49 +03001099 Py_XSETREF(self->function_pinboard_trace_callback, NULL);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001100 } else {
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001101#ifdef HAVE_TRACE_V2
1102 sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, _trace_callback, trace_callback);
1103#else
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001104 sqlite3_trace(self->db, _trace_callback, trace_callback);
Erlend Egeberg Aasland7f331c82020-09-05 22:43:31 +02001105#endif
gescheitb9a03762019-07-13 06:15:49 +03001106 Py_INCREF(trace_callback);
1107 Py_XSETREF(self->function_pinboard_trace_callback, trace_callback);
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001108 }
1109
Berker Peksagfe21de92016-04-09 07:34:39 +03001110 Py_RETURN_NONE;
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001111}
1112
Gerhard Häringf9cee222010-03-05 15:20:03 +00001113#ifdef HAVE_LOAD_EXTENSION
1114static PyObject* pysqlite_enable_load_extension(pysqlite_Connection* self, PyObject* args)
1115{
1116 int rc;
1117 int onoff;
1118
1119 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1120 return NULL;
1121 }
1122
1123 if (!PyArg_ParseTuple(args, "i", &onoff)) {
1124 return NULL;
1125 }
1126
1127 rc = sqlite3_enable_load_extension(self->db, onoff);
1128
1129 if (rc != SQLITE_OK) {
1130 PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
1131 return NULL;
1132 } else {
Berker Peksagfe21de92016-04-09 07:34:39 +03001133 Py_RETURN_NONE;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001134 }
1135}
1136
1137static PyObject* pysqlite_load_extension(pysqlite_Connection* self, PyObject* args)
1138{
1139 int rc;
1140 char* extension_name;
1141 char* errmsg;
1142
1143 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1144 return NULL;
1145 }
1146
1147 if (!PyArg_ParseTuple(args, "s", &extension_name)) {
1148 return NULL;
1149 }
1150
1151 rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1152 if (rc != 0) {
1153 PyErr_SetString(pysqlite_OperationalError, errmsg);
1154 return NULL;
1155 } else {
Berker Peksagfe21de92016-04-09 07:34:39 +03001156 Py_RETURN_NONE;
Gerhard Häringf9cee222010-03-05 15:20:03 +00001157 }
1158}
1159#endif
1160
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001161int pysqlite_check_thread(pysqlite_Connection* self)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001162{
1163 if (self->check_same_thread) {
1164 if (PyThread_get_thread_ident() != self->thread_ident) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001165 PyErr_Format(pysqlite_ProgrammingError,
Takuya Akiba030345c2018-03-27 00:14:00 +09001166 "SQLite objects created in a thread can only be used in that same thread. "
1167 "The object was created in thread id %lu and this is thread id %lu.",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001168 self->thread_ident, PyThread_get_thread_ident());
1169 return 0;
1170 }
1171
1172 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001173 return 1;
1174}
1175
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001176static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001177{
1178 Py_INCREF(self->isolation_level);
1179 return self->isolation_level;
1180}
1181
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001182static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001183{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001184 if (!pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001185 return NULL;
1186 } else {
1187 return Py_BuildValue("i", sqlite3_total_changes(self->db));
1188 }
1189}
1190
Berker Peksag59da4b32016-09-12 07:16:43 +03001191static PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
1192{
1193 if (!pysqlite_check_connection(self)) {
1194 return NULL;
1195 }
1196 if (!sqlite3_get_autocommit(self->db)) {
1197 Py_RETURN_TRUE;
1198 }
1199 Py_RETURN_FALSE;
1200}
1201
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +02001202static int
1203pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001204{
Zackery Spytz842acaa2018-12-17 07:52:45 -07001205 if (isolation_level == NULL) {
1206 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
1207 return -1;
1208 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001209 if (isolation_level == Py_None) {
Serhiy Storchaka28914922016-09-01 22:18:03 +03001210 PyObject *res = pysqlite_connection_commit(self, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001211 if (!res) {
1212 return -1;
1213 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001214 Py_DECREF(res);
1215
Serhiy Storchaka28914922016-09-01 22:18:03 +03001216 self->begin_statement = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001217 } else {
Serhiy Storchaka28914922016-09-01 22:18:03 +03001218 const char * const *candidate;
1219 PyObject *uppercase_level;
1220 _Py_IDENTIFIER(upper);
Neal Norwitzefee9f52007-10-27 02:50:52 +00001221
Serhiy Storchaka28914922016-09-01 22:18:03 +03001222 if (!PyUnicode_Check(isolation_level)) {
1223 PyErr_Format(PyExc_TypeError,
1224 "isolation_level must be a string or None, not %.100s",
1225 Py_TYPE(isolation_level)->tp_name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001226 return -1;
1227 }
1228
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001229 uppercase_level = _PyObject_CallMethodIdOneArg(
Serhiy Storchaka28914922016-09-01 22:18:03 +03001230 (PyObject *)&PyUnicode_Type, &PyId_upper,
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001231 isolation_level);
Serhiy Storchaka28914922016-09-01 22:18:03 +03001232 if (!uppercase_level) {
Georg Brandl3dbca812008-07-23 16:10:53 +00001233 return -1;
1234 }
Serhiy Storchaka28914922016-09-01 22:18:03 +03001235 for (candidate = begin_statements; *candidate; candidate++) {
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001236 if (_PyUnicode_EqualToASCIIString(uppercase_level, *candidate + 6))
Serhiy Storchaka28914922016-09-01 22:18:03 +03001237 break;
1238 }
1239 Py_DECREF(uppercase_level);
1240 if (!*candidate) {
1241 PyErr_SetString(PyExc_ValueError,
1242 "invalid value for isolation_level");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001243 return -1;
1244 }
Serhiy Storchaka28914922016-09-01 22:18:03 +03001245 self->begin_statement = *candidate;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001246 }
1247
Serhiy Storchaka28914922016-09-01 22:18:03 +03001248 Py_INCREF(isolation_level);
1249 Py_XSETREF(self->isolation_level, isolation_level);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001250 return 0;
1251}
1252
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001253PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001254{
1255 PyObject* sql;
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001256 pysqlite_Statement* statement;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257 PyObject* weakref;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001258 int rc;
1259
Gerhard Häringf9cee222010-03-05 15:20:03 +00001260 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1261 return NULL;
1262 }
1263
Serhiy Storchaka6cca5c82017-06-08 14:41:19 +03001264 if (!_PyArg_NoKeywords(MODULE_NAME ".Connection", kwargs))
Larry Hastings3b12e952015-05-08 07:45:10 -07001265 return NULL;
1266
Victor Stinnerc6a23202019-06-26 03:16:24 +02001267 if (!PyArg_ParseTuple(args, "U", &sql))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001268 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001269
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001270 _pysqlite_drop_unused_statement_references(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001271
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001272 statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001273 if (!statement) {
1274 return NULL;
1275 }
1276
Victor Stinner0201f442010-03-13 03:28:34 +00001277 statement->db = NULL;
1278 statement->st = NULL;
1279 statement->sql = NULL;
1280 statement->in_use = 0;
1281 statement->in_weakreflist = NULL;
1282
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001283 rc = pysqlite_statement_create(statement, self, sql);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001284 if (rc != SQLITE_OK) {
1285 if (rc == PYSQLITE_TOO_MUCH_SQL) {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001286 PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001287 } else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
Serhiy Storchaka42d67af2014-09-11 13:29:05 +03001288 if (PyErr_ExceptionMatches(PyExc_TypeError))
1289 PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001290 } else {
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001291 (void)pysqlite_statement_reset(statement);
1292 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001293 }
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001294 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001295 }
1296
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001297 weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
1298 if (weakref == NULL)
1299 goto error;
1300 if (PyList_Append(self->statements, weakref) != 0) {
1301 Py_DECREF(weakref);
1302 goto error;
1303 }
1304 Py_DECREF(weakref);
1305
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001306 return (PyObject*)statement;
Victor Stinnerb3e1ef12013-11-05 14:46:13 +01001307
1308error:
1309 Py_DECREF(statement);
1310 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001311}
1312
Larry Hastings01b08832015-05-08 07:37:49 -07001313PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001314{
1315 PyObject* cursor = 0;
1316 PyObject* result = 0;
1317 PyObject* method = 0;
1318
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001319 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001320 if (!cursor) {
1321 goto error;
1322 }
1323
1324 method = PyObject_GetAttrString(cursor, "execute");
1325 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001326 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001327 goto error;
1328 }
1329
1330 result = PyObject_CallObject(method, args);
1331 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001332 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001333 }
1334
1335error:
1336 Py_XDECREF(result);
1337 Py_XDECREF(method);
1338
1339 return cursor;
1340}
1341
Larry Hastings01b08832015-05-08 07:37:49 -07001342PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001343{
1344 PyObject* cursor = 0;
1345 PyObject* result = 0;
1346 PyObject* method = 0;
1347
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001348 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001349 if (!cursor) {
1350 goto error;
1351 }
1352
1353 method = PyObject_GetAttrString(cursor, "executemany");
1354 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001355 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001356 goto error;
1357 }
1358
1359 result = PyObject_CallObject(method, args);
1360 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001361 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001362 }
1363
1364error:
1365 Py_XDECREF(result);
1366 Py_XDECREF(method);
1367
1368 return cursor;
1369}
1370
Larry Hastings01b08832015-05-08 07:37:49 -07001371PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001372{
1373 PyObject* cursor = 0;
1374 PyObject* result = 0;
1375 PyObject* method = 0;
1376
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001377 cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001378 if (!cursor) {
1379 goto error;
1380 }
1381
1382 method = PyObject_GetAttrString(cursor, "executescript");
1383 if (!method) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001384 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001385 goto error;
1386 }
1387
1388 result = PyObject_CallObject(method, args);
1389 if (!result) {
Alexandre Vassalotti1839bac2008-07-13 21:57:48 +00001390 Py_CLEAR(cursor);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001391 }
1392
1393error:
1394 Py_XDECREF(result);
1395 Py_XDECREF(method);
1396
1397 return cursor;
1398}
1399
1400/* ------------------------- COLLATION CODE ------------------------ */
1401
1402static int
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001403pysqlite_collation_callback(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001404 void* context,
1405 int text1_length, const void* text1_data,
1406 int text2_length, const void* text2_data)
1407{
1408 PyObject* callback = (PyObject*)context;
1409 PyObject* string1 = 0;
1410 PyObject* string2 = 0;
1411 PyGILState_STATE gilstate;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001412 PyObject* retval = NULL;
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001413 long longval;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001414 int result = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001415 gilstate = PyGILState_Ensure();
1416
1417 if (PyErr_Occurred()) {
1418 goto finally;
1419 }
1420
Guido van Rossum98297ee2007-11-06 21:34:58 +00001421 string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1422 string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001423
1424 if (!string1 || !string2) {
1425 goto finally; /* failed to allocate strings */
1426 }
1427
1428 retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
1429
1430 if (!retval) {
1431 /* execution failed */
1432 goto finally;
1433 }
1434
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001435 longval = PyLong_AsLongAndOverflow(retval, &result);
1436 if (longval == -1 && PyErr_Occurred()) {
1437 PyErr_Clear();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001438 result = 0;
1439 }
Serhiy Storchaka3cf96ac2013-02-07 17:01:47 +02001440 else if (!result) {
1441 if (longval > 0)
1442 result = 1;
1443 else if (longval < 0)
1444 result = -1;
1445 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001446
1447finally:
1448 Py_XDECREF(string1);
1449 Py_XDECREF(string2);
1450 Py_XDECREF(retval);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001451 PyGILState_Release(gilstate);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001452 return result;
1453}
1454
1455static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001456pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001457{
1458 PyObject* retval = NULL;
1459
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001460 if (!pysqlite_check_connection(self)) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001461 goto finally;
1462 }
1463
1464 sqlite3_interrupt(self->db);
1465
1466 Py_INCREF(Py_None);
1467 retval = Py_None;
1468
1469finally:
1470 return retval;
1471}
1472
Christian Heimesbbe741d2008-03-28 10:53:29 +00001473/* Function author: Paul Kippes <kippesp@gmail.com>
1474 * Class method of Connection to call the Python function _iterdump
1475 * of the sqlite3 module.
1476 */
1477static PyObject *
1478pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
1479{
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001480 _Py_IDENTIFIER(_iterdump);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001481 PyObject* retval = NULL;
1482 PyObject* module = NULL;
1483 PyObject* module_dict;
1484 PyObject* pyfn_iterdump;
1485
1486 if (!pysqlite_check_connection(self)) {
1487 goto finally;
1488 }
1489
1490 module = PyImport_ImportModule(MODULE_NAME ".dump");
1491 if (!module) {
1492 goto finally;
1493 }
1494
1495 module_dict = PyModule_GetDict(module);
1496 if (!module_dict) {
1497 goto finally;
1498 }
1499
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001500 pyfn_iterdump = _PyDict_GetItemIdWithError(module_dict, &PyId__iterdump);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001501 if (!pyfn_iterdump) {
Serhiy Storchakafc662ac2018-12-10 16:06:08 +02001502 if (!PyErr_Occurred()) {
1503 PyErr_SetString(pysqlite_OperationalError,
1504 "Failed to obtain _iterdump() reference");
1505 }
Christian Heimesbbe741d2008-03-28 10:53:29 +00001506 goto finally;
1507 }
1508
Petr Viktorinffd97532020-02-11 17:46:57 +01001509 retval = PyObject_CallOneArg(pyfn_iterdump, (PyObject *)self);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001510
1511finally:
Christian Heimesbbe741d2008-03-28 10:53:29 +00001512 Py_XDECREF(module);
1513 return retval;
1514}
1515
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001516#ifdef HAVE_BACKUP_API
1517static PyObject *
1518pysqlite_connection_backup(pysqlite_Connection *self, PyObject *args, PyObject *kwds)
1519{
1520 PyObject *target = NULL;
1521 int pages = -1;
1522 PyObject *progress = Py_None;
1523 const char *name = "main";
1524 int rc;
1525 int callback_error = 0;
Victor Stinnerca405012018-04-30 12:22:17 +02001526 PyObject *sleep_obj = NULL;
1527 int sleep_ms = 250;
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001528 sqlite3 *bck_conn;
1529 sqlite3_backup *bck_handle;
1530 static char *keywords[] = {"target", "pages", "progress", "name", "sleep", NULL};
1531
Victor Stinnerca405012018-04-30 12:22:17 +02001532 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|$iOsO:backup", keywords,
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001533 &pysqlite_ConnectionType, &target,
Victor Stinnerca405012018-04-30 12:22:17 +02001534 &pages, &progress, &name, &sleep_obj)) {
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001535 return NULL;
1536 }
1537
Victor Stinnerca405012018-04-30 12:22:17 +02001538 if (sleep_obj != NULL) {
1539 _PyTime_t sleep_secs;
1540 if (_PyTime_FromSecondsObject(&sleep_secs, sleep_obj,
1541 _PyTime_ROUND_TIMEOUT)) {
1542 return NULL;
1543 }
1544 _PyTime_t ms = _PyTime_AsMilliseconds(sleep_secs,
1545 _PyTime_ROUND_TIMEOUT);
1546 if (ms < INT_MIN || ms > INT_MAX) {
1547 PyErr_SetString(PyExc_OverflowError, "sleep is too large");
1548 return NULL;
1549 }
1550 sleep_ms = (int)ms;
1551 }
1552
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001553 if (!pysqlite_check_connection((pysqlite_Connection *)target)) {
1554 return NULL;
1555 }
1556
1557 if ((pysqlite_Connection *)target == self) {
1558 PyErr_SetString(PyExc_ValueError, "target cannot be the same connection instance");
1559 return NULL;
1560 }
1561
Aviv Palivodabbf7bb72018-03-18 02:48:55 +02001562#if SQLITE_VERSION_NUMBER < 3008008
1563 /* Since 3.8.8 this is already done, per commit
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001564 https://www.sqlite.org/src/info/169b5505498c0a7e */
1565 if (!sqlite3_get_autocommit(((pysqlite_Connection *)target)->db)) {
1566 PyErr_SetString(pysqlite_OperationalError, "target is in transaction");
1567 return NULL;
1568 }
1569#endif
1570
1571 if (progress != Py_None && !PyCallable_Check(progress)) {
1572 PyErr_SetString(PyExc_TypeError, "progress argument must be a callable");
1573 return NULL;
1574 }
1575
1576 if (pages == 0) {
1577 pages = -1;
1578 }
1579
1580 bck_conn = ((pysqlite_Connection *)target)->db;
1581
1582 Py_BEGIN_ALLOW_THREADS
1583 bck_handle = sqlite3_backup_init(bck_conn, "main", self->db, name);
1584 Py_END_ALLOW_THREADS
1585
1586 if (bck_handle) {
1587 do {
1588 Py_BEGIN_ALLOW_THREADS
1589 rc = sqlite3_backup_step(bck_handle, pages);
1590 Py_END_ALLOW_THREADS
1591
1592 if (progress != Py_None) {
1593 PyObject *res;
1594
1595 res = PyObject_CallFunction(progress, "iii", rc,
1596 sqlite3_backup_remaining(bck_handle),
1597 sqlite3_backup_pagecount(bck_handle));
1598 if (res == NULL) {
1599 /* User's callback raised an error: interrupt the loop and
1600 propagate it. */
1601 callback_error = 1;
1602 rc = -1;
1603 } else {
1604 Py_DECREF(res);
1605 }
1606 }
1607
1608 /* Sleep for a while if there are still further pages to copy and
1609 the engine could not make any progress */
1610 if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) {
1611 Py_BEGIN_ALLOW_THREADS
Victor Stinnerca405012018-04-30 12:22:17 +02001612 sqlite3_sleep(sleep_ms);
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001613 Py_END_ALLOW_THREADS
1614 }
1615 } while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);
1616
1617 Py_BEGIN_ALLOW_THREADS
1618 rc = sqlite3_backup_finish(bck_handle);
1619 Py_END_ALLOW_THREADS
1620 } else {
1621 rc = _pysqlite_seterror(bck_conn, NULL);
1622 }
1623
1624 if (!callback_error && rc != SQLITE_OK) {
1625 /* We cannot use _pysqlite_seterror() here because the backup APIs do
1626 not set the error status on the connection object, but rather on
1627 the backup handle. */
1628 if (rc == SQLITE_NOMEM) {
1629 (void)PyErr_NoMemory();
1630 } else {
1631#if SQLITE_VERSION_NUMBER > 3007015
1632 PyErr_SetString(pysqlite_OperationalError, sqlite3_errstr(rc));
1633#else
1634 switch (rc) {
Berker Peksagb10a64d2018-09-20 14:14:33 +03001635 case SQLITE_ERROR:
1636 /* Description of SQLITE_ERROR in SQLite 3.7.14 and older
1637 releases. */
1638 PyErr_SetString(pysqlite_OperationalError,
1639 "SQL logic error or missing database");
1640 break;
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001641 case SQLITE_READONLY:
1642 PyErr_SetString(pysqlite_OperationalError,
1643 "attempt to write a readonly database");
1644 break;
1645 case SQLITE_BUSY:
1646 PyErr_SetString(pysqlite_OperationalError, "database is locked");
1647 break;
1648 case SQLITE_LOCKED:
1649 PyErr_SetString(pysqlite_OperationalError,
1650 "database table is locked");
1651 break;
1652 default:
1653 PyErr_Format(pysqlite_OperationalError,
1654 "unrecognized error code: %d", rc);
1655 break;
1656 }
1657#endif
1658 }
1659 }
1660
1661 if (!callback_error && rc == SQLITE_OK) {
1662 Py_RETURN_NONE;
1663 } else {
1664 return NULL;
1665 }
1666}
1667#endif
1668
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001669static PyObject *
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001670pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001671{
1672 PyObject* callable;
1673 PyObject* uppercase_name = 0;
1674 PyObject* name;
1675 PyObject* retval;
Victor Stinner35466c52010-04-22 11:23:23 +00001676 Py_ssize_t i, len;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001677 _Py_IDENTIFIER(upper);
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001678 const char *uppercase_name_str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001679 int rc;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001680 unsigned int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001681 const void *data;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001682
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001683 if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001684 goto finally;
1685 }
1686
Serhiy Storchaka407ac472016-09-27 00:10:03 +03001687 if (!PyArg_ParseTuple(args, "UO:create_collation(name, callback)",
1688 &name, &callable)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001689 goto finally;
1690 }
1691
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001692 uppercase_name = _PyObject_CallMethodIdOneArg((PyObject *)&PyUnicode_Type,
1693 &PyId_upper, name);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001694 if (!uppercase_name) {
1695 goto finally;
1696 }
1697
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001698 if (PyUnicode_READY(uppercase_name))
1699 goto finally;
1700 len = PyUnicode_GET_LENGTH(uppercase_name);
1701 kind = PyUnicode_KIND(uppercase_name);
1702 data = PyUnicode_DATA(uppercase_name);
1703 for (i=0; i<len; i++) {
1704 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
1705 if ((ch >= '0' && ch <= '9')
1706 || (ch >= 'A' && ch <= 'Z')
1707 || (ch == '_'))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001708 {
Victor Stinner35466c52010-04-22 11:23:23 +00001709 continue;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001710 } else {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001711 PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001712 goto finally;
1713 }
1714 }
1715
Serhiy Storchaka06515832016-11-20 09:13:07 +02001716 uppercase_name_str = PyUnicode_AsUTF8(uppercase_name);
Victor Stinner35466c52010-04-22 11:23:23 +00001717 if (!uppercase_name_str)
1718 goto finally;
1719
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001720 if (callable != Py_None && !PyCallable_Check(callable)) {
1721 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1722 goto finally;
1723 }
1724
1725 if (callable != Py_None) {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001726 if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
1727 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001728 } else {
Gerhard Häringf9cee222010-03-05 15:20:03 +00001729 if (PyDict_DelItem(self->collations, uppercase_name) == -1)
1730 goto finally;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001731 }
1732
1733 rc = sqlite3_create_collation(self->db,
Victor Stinner35466c52010-04-22 11:23:23 +00001734 uppercase_name_str,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001735 SQLITE_UTF8,
1736 (callable != Py_None) ? callable : NULL,
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001737 (callable != Py_None) ? pysqlite_collation_callback : NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001738 if (rc != SQLITE_OK) {
1739 PyDict_DelItem(self->collations, uppercase_name);
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001740 _pysqlite_seterror(self->db, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001741 goto finally;
1742 }
1743
1744finally:
1745 Py_XDECREF(uppercase_name);
1746
1747 if (PyErr_Occurred()) {
1748 retval = NULL;
1749 } else {
1750 Py_INCREF(Py_None);
1751 retval = Py_None;
1752 }
1753
1754 return retval;
1755}
1756
Christian Heimesbbe741d2008-03-28 10:53:29 +00001757/* Called when the connection is used as a context manager. Returns itself as a
1758 * convenience to the caller. */
1759static PyObject *
1760pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
1761{
1762 Py_INCREF(self);
1763 return (PyObject*)self;
1764}
1765
1766/** Called when the connection is used as a context manager. If there was any
1767 * exception, a rollback takes place; otherwise we commit. */
1768static PyObject *
1769pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
1770{
1771 PyObject* exc_type, *exc_value, *exc_tb;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001772 const char* method_name;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001773 PyObject* result;
1774
1775 if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
1776 return NULL;
1777 }
1778
1779 if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1780 method_name = "commit";
1781 } else {
1782 method_name = "rollback";
1783 }
1784
Victor Stinner3466bde2016-09-05 18:16:01 -07001785 result = PyObject_CallMethod((PyObject*)self, method_name, NULL);
Christian Heimesbbe741d2008-03-28 10:53:29 +00001786 if (!result) {
1787 return NULL;
1788 }
1789 Py_DECREF(result);
1790
1791 Py_RETURN_FALSE;
1792}
1793
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001794static const char connection_doc[] =
Thomas Wouters477c8d52006-05-27 19:21:47 +00001795PyDoc_STR("SQLite database connection object.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001796
1797static PyGetSetDef connection_getset[] = {
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001798 {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1799 {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
Berker Peksag59da4b32016-09-12 07:16:43 +03001800 {"in_transaction", (getter)pysqlite_connection_get_in_transaction, (setter)0},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001801 {NULL}
1802};
1803
1804static PyMethodDef connection_methods[] = {
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001805 {"cursor", (PyCFunction)(void(*)(void))pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001806 PyDoc_STR("Return a cursor for the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001807 {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001808 PyDoc_STR("Closes the connection.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001809 {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001810 PyDoc_STR("Commit the current transaction.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001811 {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001812 PyDoc_STR("Roll back the current transaction.")},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001813 {"create_function", (PyCFunction)(void(*)(void))pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001814 PyDoc_STR("Creates a new function. Non-standard.")},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001815 {"create_aggregate", (PyCFunction)(void(*)(void))pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001816 PyDoc_STR("Creates a new aggregate. Non-standard.")},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001817 {"set_authorizer", (PyCFunction)(void(*)(void))pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001818 PyDoc_STR("Sets authorizer callback. Non-standard.")},
Gerhard Häringf9cee222010-03-05 15:20:03 +00001819 #ifdef HAVE_LOAD_EXTENSION
1820 {"enable_load_extension", (PyCFunction)pysqlite_enable_load_extension, METH_VARARGS,
1821 PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
1822 {"load_extension", (PyCFunction)pysqlite_load_extension, METH_VARARGS,
1823 PyDoc_STR("Load SQLite extension module. Non-standard.")},
1824 #endif
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001825 {"set_progress_handler", (PyCFunction)(void(*)(void))pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
Gerhard Häringe7ea7452008-03-29 00:45:29 +00001826 PyDoc_STR("Sets progress handler callback. Non-standard.")},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001827 {"set_trace_callback", (PyCFunction)(void(*)(void))pysqlite_connection_set_trace_callback, METH_VARARGS|METH_KEYWORDS,
Antoine Pitrou5bfa0622011-04-04 00:12:04 +02001828 PyDoc_STR("Sets a trace callback called for each SQL statement (passed as unicode). Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001829 {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001830 PyDoc_STR("Executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001831 {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001832 PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001833 {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001834 PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001835 {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001836 PyDoc_STR("Creates a collation function. Non-standard.")},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001837 {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001838 PyDoc_STR("Abort any pending database operation. Non-standard.")},
Christian Heimesbbe741d2008-03-28 10:53:29 +00001839 {"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
Benjamin Petersond7b03282008-09-13 15:58:53 +00001840 PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001841 #ifdef HAVE_BACKUP_API
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001842 {"backup", (PyCFunction)(void(*)(void))pysqlite_connection_backup, METH_VARARGS | METH_KEYWORDS,
Emanuele Gaifasd7aed412018-03-10 23:08:31 +01001843 PyDoc_STR("Makes a backup of the database. Non-standard.")},
1844 #endif
Christian Heimesbbe741d2008-03-28 10:53:29 +00001845 {"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
1846 PyDoc_STR("For context manager. Non-standard.")},
1847 {"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
1848 PyDoc_STR("For context manager. Non-standard.")},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001849 {NULL, NULL}
1850};
1851
1852static struct PyMemberDef connection_members[] =
1853{
Guido van Rossum10f07c42007-08-11 15:32:55 +00001854 {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
1855 {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
1856 {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
1857 {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
1858 {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
1859 {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
1860 {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
1861 {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
1862 {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
1863 {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001864 {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
1865 {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001866 {NULL}
1867};
1868
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001869PyTypeObject pysqlite_ConnectionType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001870 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001871 MODULE_NAME ".Connection", /* tp_name */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001872 sizeof(pysqlite_Connection), /* tp_basicsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001873 0, /* tp_itemsize */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001874 (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001875 0, /* tp_vectorcall_offset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001876 0, /* tp_getattr */
1877 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001878 0, /* tp_as_async */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001879 0, /* tp_repr */
1880 0, /* tp_as_number */
1881 0, /* tp_as_sequence */
1882 0, /* tp_as_mapping */
1883 0, /* tp_hash */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001884 (ternaryfunc)pysqlite_connection_call, /* tp_call */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001885 0, /* tp_str */
1886 0, /* tp_getattro */
1887 0, /* tp_setattro */
1888 0, /* tp_as_buffer */
1889 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
1890 connection_doc, /* tp_doc */
1891 0, /* tp_traverse */
1892 0, /* tp_clear */
1893 0, /* tp_richcompare */
1894 0, /* tp_weaklistoffset */
1895 0, /* tp_iter */
1896 0, /* tp_iternext */
1897 connection_methods, /* tp_methods */
1898 connection_members, /* tp_members */
1899 connection_getset, /* tp_getset */
1900 0, /* tp_base */
1901 0, /* tp_dict */
1902 0, /* tp_descr_get */
1903 0, /* tp_descr_set */
1904 0, /* tp_dictoffset */
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001905 (initproc)pysqlite_connection_init, /* tp_init */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001906 0, /* tp_alloc */
1907 0, /* tp_new */
1908 0 /* tp_free */
1909};
1910
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001911extern int pysqlite_connection_setup_types(void)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001912{
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00001913 pysqlite_ConnectionType.tp_new = PyType_GenericNew;
1914 return PyType_Ready(&pysqlite_ConnectionType);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001915}