Branch data Line data Source code
1 : : /* connection.c - the connection type
2 : : *
3 : : * Copyright (C) 2004-2010 Gerhard Häring <gh@ghaering.de>
4 : : *
5 : : * This file is part of pysqlite.
6 : : *
7 : : * 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 "module.h"
25 : : #include "structmember.h" // PyMemberDef
26 : : #include "connection.h"
27 : : #include "statement.h"
28 : : #include "cursor.h"
29 : : #include "blob.h"
30 : : #include "prepare_protocol.h"
31 : : #include "util.h"
32 : :
33 : : #if SQLITE_VERSION_NUMBER >= 3014000
34 : : #define HAVE_TRACE_V2
35 : : #endif
36 : :
37 : : #if SQLITE_VERSION_NUMBER >= 3025000
38 : : #define HAVE_WINDOW_FUNCTIONS
39 : : #endif
40 : :
41 : : static const char *
42 : 0 : get_isolation_level(const char *level)
43 : : {
44 : : assert(level != NULL);
45 : : static const char *const allowed_levels[] = {
46 : : "",
47 : : "DEFERRED",
48 : : "IMMEDIATE",
49 : : "EXCLUSIVE",
50 : : NULL
51 : : };
52 [ # # ]: 0 : for (int i = 0; allowed_levels[i] != NULL; i++) {
53 : 0 : const char *candidate = allowed_levels[i];
54 [ # # ]: 0 : if (sqlite3_stricmp(level, candidate) == 0) {
55 : 0 : return candidate;
56 : : }
57 : : }
58 : 0 : PyErr_SetString(PyExc_ValueError,
59 : : "isolation_level string must be '', 'DEFERRED', "
60 : : "'IMMEDIATE', or 'EXCLUSIVE'");
61 : 0 : return NULL;
62 : : }
63 : :
64 : : static int
65 : 0 : isolation_level_converter(PyObject *str_or_none, const char **result)
66 : : {
67 [ # # ]: 0 : if (Py_IsNone(str_or_none)) {
68 : 0 : *result = NULL;
69 : : }
70 [ # # ]: 0 : else if (PyUnicode_Check(str_or_none)) {
71 : : Py_ssize_t sz;
72 : 0 : const char *str = PyUnicode_AsUTF8AndSize(str_or_none, &sz);
73 [ # # ]: 0 : if (str == NULL) {
74 : 0 : return 0;
75 : : }
76 [ # # ]: 0 : if (strlen(str) != (size_t)sz) {
77 : 0 : PyErr_SetString(PyExc_ValueError, "embedded null character");
78 : 0 : return 0;
79 : : }
80 : :
81 : 0 : const char *level = get_isolation_level(str);
82 [ # # ]: 0 : if (level == NULL) {
83 : 0 : return 0;
84 : : }
85 : 0 : *result = level;
86 : : }
87 : : else {
88 : 0 : PyErr_SetString(PyExc_TypeError,
89 : : "isolation_level must be str or None");
90 : 0 : return 0;
91 : : }
92 : 0 : return 1;
93 : : }
94 : :
95 : : static int
96 : 0 : autocommit_converter(PyObject *val, enum autocommit_mode *result)
97 : : {
98 [ # # ]: 0 : if (Py_IsTrue(val)) {
99 : 0 : *result = AUTOCOMMIT_ENABLED;
100 : 0 : return 1;
101 : : }
102 [ # # ]: 0 : if (Py_IsFalse(val)) {
103 : 0 : *result = AUTOCOMMIT_DISABLED;
104 : 0 : return 1;
105 : : }
106 [ # # # # ]: 0 : if (PyLong_Check(val) &&
107 : 0 : PyLong_AsLong(val) == LEGACY_TRANSACTION_CONTROL)
108 : : {
109 : 0 : *result = AUTOCOMMIT_LEGACY;
110 : 0 : return 1;
111 : : }
112 : :
113 : 0 : PyErr_SetString(PyExc_ValueError,
114 : : "autocommit must be True, False, or "
115 : : "sqlite3.LEGACY_TRANSACTION_CONTROL");
116 : 0 : return 0;
117 : : }
118 : :
119 : : #define clinic_state() (pysqlite_get_state_by_type(Py_TYPE(self)))
120 : : #include "clinic/connection.c.h"
121 : : #undef clinic_state
122 : :
123 : : /*[clinic input]
124 : : module _sqlite3
125 : : class _sqlite3.Connection "pysqlite_Connection *" "clinic_state()->ConnectionType"
126 : : [clinic start generated code]*/
127 : : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=67369db2faf80891]*/
128 : :
129 : : static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
130 : : static void free_callback_context(callback_context *ctx);
131 : : static void set_callback_context(callback_context **ctx_pp,
132 : : callback_context *ctx);
133 : : static void connection_close(pysqlite_Connection *self);
134 : : PyObject *_pysqlite_query_execute(pysqlite_Cursor *, int, PyObject *, PyObject *);
135 : :
136 : : static PyObject *
137 : 0 : new_statement_cache(pysqlite_Connection *self, pysqlite_state *state,
138 : : int maxsize)
139 : : {
140 : 0 : PyObject *args[] = { NULL, PyLong_FromLong(maxsize), };
141 [ # # ]: 0 : if (args[1] == NULL) {
142 : 0 : return NULL;
143 : : }
144 : 0 : PyObject *lru_cache = state->lru_cache;
145 : 0 : size_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
146 : 0 : PyObject *inner = PyObject_Vectorcall(lru_cache, args + 1, nargsf, NULL);
147 : 0 : Py_DECREF(args[1]);
148 [ # # ]: 0 : if (inner == NULL) {
149 : 0 : return NULL;
150 : : }
151 : :
152 : 0 : args[1] = (PyObject *)self; // Borrowed ref.
153 : 0 : nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
154 : 0 : PyObject *res = PyObject_Vectorcall(inner, args + 1, nargsf, NULL);
155 : 0 : Py_DECREF(inner);
156 : 0 : return res;
157 : : }
158 : :
159 : : static inline int
160 : 0 : connection_exec_stmt(pysqlite_Connection *self, const char *sql)
161 : : {
162 : : int rc;
163 : 0 : Py_BEGIN_ALLOW_THREADS
164 : 0 : int len = (int)strlen(sql) + 1;
165 : : sqlite3_stmt *stmt;
166 : 0 : rc = sqlite3_prepare_v2(self->db, sql, len, &stmt, NULL);
167 [ # # ]: 0 : if (rc == SQLITE_OK) {
168 : 0 : (void)sqlite3_step(stmt);
169 : 0 : rc = sqlite3_finalize(stmt);
170 : : }
171 : 0 : Py_END_ALLOW_THREADS
172 : :
173 [ # # ]: 0 : if (rc != SQLITE_OK) {
174 : 0 : (void)_pysqlite_seterror(self->state, self->db);
175 : 0 : return -1;
176 : : }
177 : 0 : return 0;
178 : : }
179 : :
180 : : /*[python input]
181 : : class IsolationLevel_converter(CConverter):
182 : : type = "const char *"
183 : : converter = "isolation_level_converter"
184 : :
185 : : class Autocommit_converter(CConverter):
186 : : type = "enum autocommit_mode"
187 : : converter = "autocommit_converter"
188 : :
189 : : [python start generated code]*/
190 : : /*[python end generated code: output=da39a3ee5e6b4b0d input=bc2aa6c7ba0c5f8f]*/
191 : :
192 : : // NB: This needs to be in sync with the sqlite3.connect docstring
193 : : /*[clinic input]
194 : : _sqlite3.Connection.__init__ as pysqlite_connection_init
195 : :
196 : : database: object
197 : : timeout: double = 5.0
198 : : detect_types: int = 0
199 : : isolation_level: IsolationLevel = ""
200 : : check_same_thread: bool = True
201 : : factory: object(c_default='(PyObject*)clinic_state()->ConnectionType') = ConnectionType
202 : : cached_statements as cache_size: int = 128
203 : : uri: bool = False
204 : : *
205 : : autocommit: Autocommit(c_default='LEGACY_TRANSACTION_CONTROL') = sqlite3.LEGACY_TRANSACTION_CONTROL
206 : : [clinic start generated code]*/
207 : :
208 : : static int
209 : 0 : pysqlite_connection_init_impl(pysqlite_Connection *self, PyObject *database,
210 : : double timeout, int detect_types,
211 : : const char *isolation_level,
212 : : int check_same_thread, PyObject *factory,
213 : : int cache_size, int uri,
214 : : enum autocommit_mode autocommit)
215 : : /*[clinic end generated code: output=cba057313ea7712f input=9b0ab6c12f674fa3]*/
216 : : {
217 [ # # ]: 0 : if (PySys_Audit("sqlite3.connect", "O", database) < 0) {
218 : 0 : return -1;
219 : : }
220 : :
221 : : PyObject *bytes;
222 [ # # ]: 0 : if (!PyUnicode_FSConverter(database, &bytes)) {
223 : 0 : return -1;
224 : : }
225 : :
226 [ # # ]: 0 : if (self->initialized) {
227 : 0 : PyTypeObject *tp = Py_TYPE(self);
228 : 0 : tp->tp_clear((PyObject *)self);
229 : 0 : connection_close(self);
230 : 0 : self->initialized = 0;
231 : : }
232 : :
233 : : // Create and configure SQLite database object.
234 : : sqlite3 *db;
235 : : int rc;
236 : 0 : Py_BEGIN_ALLOW_THREADS
237 [ # # ]: 0 : rc = sqlite3_open_v2(PyBytes_AS_STRING(bytes), &db,
238 : : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
239 : : (uri ? SQLITE_OPEN_URI : 0), NULL);
240 [ # # ]: 0 : if (rc == SQLITE_OK) {
241 : 0 : (void)sqlite3_busy_timeout(db, (int)(timeout*1000));
242 : : }
243 : 0 : Py_END_ALLOW_THREADS
244 : :
245 : 0 : Py_DECREF(bytes);
246 [ # # # # ]: 0 : if (db == NULL && rc == SQLITE_NOMEM) {
247 : 0 : PyErr_NoMemory();
248 : 0 : return -1;
249 : : }
250 : :
251 : 0 : pysqlite_state *state = pysqlite_get_state_by_type(Py_TYPE(self));
252 [ # # ]: 0 : if (rc != SQLITE_OK) {
253 : 0 : _pysqlite_seterror(state, db);
254 : 0 : goto error;
255 : : }
256 : :
257 : : // Create LRU statement cache; returns a new reference.
258 : 0 : PyObject *statement_cache = new_statement_cache(self, state, cache_size);
259 [ # # ]: 0 : if (statement_cache == NULL) {
260 : 0 : goto error;
261 : : }
262 : :
263 : : /* Create lists of weak references to cursors and blobs */
264 : 0 : PyObject *cursors = PyList_New(0);
265 [ # # ]: 0 : if (cursors == NULL) {
266 : 0 : Py_DECREF(statement_cache);
267 : 0 : goto error;
268 : : }
269 : :
270 : 0 : PyObject *blobs = PyList_New(0);
271 [ # # ]: 0 : if (blobs == NULL) {
272 : 0 : Py_DECREF(statement_cache);
273 : 0 : Py_DECREF(cursors);
274 : 0 : goto error;
275 : : }
276 : :
277 : : // Init connection state members.
278 : 0 : self->db = db;
279 : 0 : self->state = state;
280 : 0 : self->detect_types = detect_types;
281 : 0 : self->isolation_level = isolation_level;
282 : 0 : self->autocommit = autocommit;
283 : 0 : self->check_same_thread = check_same_thread;
284 : 0 : self->thread_ident = PyThread_get_thread_ident();
285 : 0 : self->statement_cache = statement_cache;
286 : 0 : self->cursors = cursors;
287 : 0 : self->blobs = blobs;
288 : 0 : self->created_cursors = 0;
289 : 0 : self->row_factory = Py_NewRef(Py_None);
290 : 0 : self->text_factory = Py_NewRef(&PyUnicode_Type);
291 : 0 : self->trace_ctx = NULL;
292 : 0 : self->progress_ctx = NULL;
293 : 0 : self->authorizer_ctx = NULL;
294 : :
295 : : // Borrowed refs
296 : 0 : self->Warning = state->Warning;
297 : 0 : self->Error = state->Error;
298 : 0 : self->InterfaceError = state->InterfaceError;
299 : 0 : self->DatabaseError = state->DatabaseError;
300 : 0 : self->DataError = state->DataError;
301 : 0 : self->OperationalError = state->OperationalError;
302 : 0 : self->IntegrityError = state->IntegrityError;
303 : 0 : self->InternalError = state->InternalError;
304 : 0 : self->ProgrammingError = state->ProgrammingError;
305 : 0 : self->NotSupportedError = state->NotSupportedError;
306 : :
307 [ # # ]: 0 : if (PySys_Audit("sqlite3.connect/handle", "O", self) < 0) {
308 : 0 : return -1; // Don't goto error; at this point, dealloc will clean up.
309 : : }
310 : :
311 : 0 : self->initialized = 1;
312 : :
313 [ # # ]: 0 : if (autocommit == AUTOCOMMIT_DISABLED) {
314 : 0 : (void)connection_exec_stmt(self, "BEGIN");
315 : : }
316 : 0 : return 0;
317 : :
318 : 0 : error:
319 : : // There are no statements or other SQLite objects attached to the
320 : : // database, so sqlite3_close() should always return SQLITE_OK.
321 : 0 : rc = sqlite3_close(db);
322 : : assert(rc == SQLITE_OK);
323 : 0 : return -1;
324 : : }
325 : :
326 : : #define VISIT_CALLBACK_CONTEXT(ctx) \
327 : : do { \
328 : : if (ctx) { \
329 : : Py_VISIT(ctx->callable); \
330 : : Py_VISIT(ctx->module); \
331 : : } \
332 : : } while (0)
333 : :
334 : : static int
335 : 0 : connection_traverse(pysqlite_Connection *self, visitproc visit, void *arg)
336 : : {
337 [ # # # # ]: 0 : Py_VISIT(Py_TYPE(self));
338 [ # # # # ]: 0 : Py_VISIT(self->statement_cache);
339 [ # # # # ]: 0 : Py_VISIT(self->cursors);
340 [ # # # # ]: 0 : Py_VISIT(self->blobs);
341 [ # # # # ]: 0 : Py_VISIT(self->row_factory);
342 [ # # # # ]: 0 : Py_VISIT(self->text_factory);
343 [ # # # # : 0 : VISIT_CALLBACK_CONTEXT(self->trace_ctx);
# # # # #
# ]
344 [ # # # # : 0 : VISIT_CALLBACK_CONTEXT(self->progress_ctx);
# # # # #
# ]
345 [ # # # # : 0 : VISIT_CALLBACK_CONTEXT(self->authorizer_ctx);
# # # # #
# ]
346 : : #undef VISIT_CALLBACK_CONTEXT
347 : 0 : return 0;
348 : : }
349 : :
350 : : static inline void
351 : 0 : clear_callback_context(callback_context *ctx)
352 : : {
353 [ # # ]: 0 : if (ctx != NULL) {
354 [ # # ]: 0 : Py_CLEAR(ctx->callable);
355 [ # # ]: 0 : Py_CLEAR(ctx->module);
356 : : }
357 : 0 : }
358 : :
359 : : static int
360 : 0 : connection_clear(pysqlite_Connection *self)
361 : : {
362 [ # # ]: 0 : Py_CLEAR(self->statement_cache);
363 [ # # ]: 0 : Py_CLEAR(self->cursors);
364 [ # # ]: 0 : Py_CLEAR(self->blobs);
365 [ # # ]: 0 : Py_CLEAR(self->row_factory);
366 [ # # ]: 0 : Py_CLEAR(self->text_factory);
367 : 0 : clear_callback_context(self->trace_ctx);
368 : 0 : clear_callback_context(self->progress_ctx);
369 : 0 : clear_callback_context(self->authorizer_ctx);
370 : 0 : return 0;
371 : : }
372 : :
373 : : static void
374 : 0 : free_callback_contexts(pysqlite_Connection *self)
375 : : {
376 : 0 : set_callback_context(&self->trace_ctx, NULL);
377 : 0 : set_callback_context(&self->progress_ctx, NULL);
378 : 0 : set_callback_context(&self->authorizer_ctx, NULL);
379 : 0 : }
380 : :
381 : : static void
382 : 0 : remove_callbacks(sqlite3 *db)
383 : : {
384 : : #ifdef HAVE_TRACE_V2
385 : 0 : sqlite3_trace_v2(db, SQLITE_TRACE_STMT, 0, 0);
386 : : #else
387 : : sqlite3_trace(db, 0, (void*)0);
388 : : #endif
389 : 0 : sqlite3_progress_handler(db, 0, 0, (void *)0);
390 : 0 : (void)sqlite3_set_authorizer(db, NULL, NULL);
391 : 0 : }
392 : :
393 : : static void
394 : 0 : connection_close(pysqlite_Connection *self)
395 : : {
396 [ # # ]: 0 : if (self->db) {
397 [ # # # # ]: 0 : if (self->autocommit == AUTOCOMMIT_DISABLED &&
398 : 0 : !sqlite3_get_autocommit(self->db))
399 : : {
400 : : /* If close is implicitly called as a result of interpreter
401 : : * tear-down, we must not call back into Python. */
402 [ # # ]: 0 : if (_Py_IsFinalizing()) {
403 : 0 : remove_callbacks(self->db);
404 : : }
405 : 0 : (void)connection_exec_stmt(self, "ROLLBACK");
406 : : }
407 : :
408 : 0 : free_callback_contexts(self);
409 : :
410 : 0 : sqlite3 *db = self->db;
411 : 0 : self->db = NULL;
412 : :
413 : 0 : Py_BEGIN_ALLOW_THREADS
414 : 0 : int rc = sqlite3_close_v2(db);
415 : : assert(rc == SQLITE_OK), (void)rc;
416 : 0 : Py_END_ALLOW_THREADS
417 : : }
418 : 0 : }
419 : :
420 : : static void
421 : 0 : connection_dealloc(pysqlite_Connection *self)
422 : : {
423 : 0 : PyTypeObject *tp = Py_TYPE(self);
424 : 0 : PyObject_GC_UnTrack(self);
425 : 0 : tp->tp_clear((PyObject *)self);
426 : :
427 : : /* Clean up if user has not called .close() explicitly. */
428 : 0 : connection_close(self);
429 : :
430 : 0 : tp->tp_free(self);
431 : 0 : Py_DECREF(tp);
432 : 0 : }
433 : :
434 : : /*[clinic input]
435 : : _sqlite3.Connection.cursor as pysqlite_connection_cursor
436 : :
437 : : factory: object = NULL
438 : :
439 : : Return a cursor for the connection.
440 : : [clinic start generated code]*/
441 : :
442 : : static PyObject *
443 : 0 : pysqlite_connection_cursor_impl(pysqlite_Connection *self, PyObject *factory)
444 : : /*[clinic end generated code: output=562432a9e6af2aa1 input=4127345aa091b650]*/
445 : : {
446 : : PyObject* cursor;
447 : :
448 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
449 : 0 : return NULL;
450 : : }
451 : :
452 [ # # ]: 0 : if (factory == NULL) {
453 : 0 : factory = (PyObject *)self->state->CursorType;
454 : : }
455 : :
456 : 0 : cursor = PyObject_CallOneArg(factory, (PyObject *)self);
457 [ # # ]: 0 : if (cursor == NULL)
458 : 0 : return NULL;
459 [ # # ]: 0 : if (!PyObject_TypeCheck(cursor, self->state->CursorType)) {
460 : 0 : PyErr_Format(PyExc_TypeError,
461 : : "factory must return a cursor, not %.100s",
462 : 0 : Py_TYPE(cursor)->tp_name);
463 : 0 : Py_DECREF(cursor);
464 : 0 : return NULL;
465 : : }
466 : :
467 : 0 : _pysqlite_drop_unused_cursor_references(self);
468 : :
469 [ # # # # ]: 0 : if (cursor && self->row_factory != Py_None) {
470 : 0 : Py_INCREF(self->row_factory);
471 : 0 : Py_XSETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory);
472 : : }
473 : :
474 : 0 : return cursor;
475 : : }
476 : :
477 : : /*[clinic input]
478 : : _sqlite3.Connection.blobopen as blobopen
479 : :
480 : : table: str
481 : : Table name.
482 : : column as col: str
483 : : Column name.
484 : : row: int
485 : : Row index.
486 : : /
487 : : *
488 : : readonly: bool = False
489 : : Open the BLOB without write permissions.
490 : : name: str = "main"
491 : : Database name.
492 : :
493 : : Open and return a BLOB object.
494 : : [clinic start generated code]*/
495 : :
496 : : static PyObject *
497 : 0 : blobopen_impl(pysqlite_Connection *self, const char *table, const char *col,
498 : : int row, int readonly, const char *name)
499 : : /*[clinic end generated code: output=0c8e2e58516d0b5c input=fa73c83aa7a7ddee]*/
500 : : {
501 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
502 : 0 : return NULL;
503 : : }
504 : :
505 : : int rc;
506 : : sqlite3_blob *blob;
507 : :
508 : 0 : Py_BEGIN_ALLOW_THREADS
509 : 0 : rc = sqlite3_blob_open(self->db, name, table, col, row, !readonly, &blob);
510 : 0 : Py_END_ALLOW_THREADS
511 : :
512 [ # # ]: 0 : if (rc == SQLITE_MISUSE) {
513 : 0 : PyErr_Format(self->state->InterfaceError, sqlite3_errstr(rc));
514 : 0 : return NULL;
515 : : }
516 [ # # ]: 0 : else if (rc != SQLITE_OK) {
517 : 0 : _pysqlite_seterror(self->state, self->db);
518 : 0 : return NULL;
519 : : }
520 : :
521 : 0 : pysqlite_Blob *obj = PyObject_GC_New(pysqlite_Blob, self->state->BlobType);
522 [ # # ]: 0 : if (obj == NULL) {
523 : 0 : goto error;
524 : : }
525 : :
526 : 0 : obj->connection = (pysqlite_Connection *)Py_NewRef(self);
527 : 0 : obj->blob = blob;
528 : 0 : obj->offset = 0;
529 : 0 : obj->in_weakreflist = NULL;
530 : :
531 : 0 : PyObject_GC_Track(obj);
532 : :
533 : : // Add our blob to connection blobs list
534 : 0 : PyObject *weakref = PyWeakref_NewRef((PyObject *)obj, NULL);
535 [ # # ]: 0 : if (weakref == NULL) {
536 : 0 : goto error;
537 : : }
538 : 0 : rc = PyList_Append(self->blobs, weakref);
539 : 0 : Py_DECREF(weakref);
540 [ # # ]: 0 : if (rc < 0) {
541 : 0 : goto error;
542 : : }
543 : :
544 : 0 : return (PyObject *)obj;
545 : :
546 : 0 : error:
547 : 0 : Py_XDECREF(obj);
548 : 0 : return NULL;
549 : : }
550 : :
551 : : /*[clinic input]
552 : : _sqlite3.Connection.close as pysqlite_connection_close
553 : :
554 : : Close the database connection.
555 : :
556 : : Any pending transaction is not committed implicitly.
557 : : [clinic start generated code]*/
558 : :
559 : : static PyObject *
560 : 0 : pysqlite_connection_close_impl(pysqlite_Connection *self)
561 : : /*[clinic end generated code: output=a546a0da212c9b97 input=b3ed5b74f6fefc06]*/
562 : : {
563 [ # # ]: 0 : if (!pysqlite_check_thread(self)) {
564 : 0 : return NULL;
565 : : }
566 : :
567 [ # # ]: 0 : if (!self->initialized) {
568 : 0 : PyTypeObject *tp = Py_TYPE(self);
569 : 0 : pysqlite_state *state = pysqlite_get_state_by_type(tp);
570 : 0 : PyErr_SetString(state->ProgrammingError,
571 : : "Base Connection.__init__ not called.");
572 : 0 : return NULL;
573 : : }
574 : :
575 : 0 : pysqlite_close_all_blobs(self);
576 [ # # ]: 0 : Py_CLEAR(self->statement_cache);
577 : 0 : connection_close(self);
578 : :
579 : 0 : Py_RETURN_NONE;
580 : : }
581 : :
582 : : /*
583 : : * Checks if a connection object is usable (i. e. not closed).
584 : : *
585 : : * 0 => error; 1 => ok
586 : : */
587 : 0 : int pysqlite_check_connection(pysqlite_Connection* con)
588 : : {
589 [ # # ]: 0 : if (!con->initialized) {
590 : 0 : pysqlite_state *state = pysqlite_get_state_by_type(Py_TYPE(con));
591 : 0 : PyErr_SetString(state->ProgrammingError,
592 : : "Base Connection.__init__ not called.");
593 : 0 : return 0;
594 : : }
595 : :
596 [ # # ]: 0 : if (!con->db) {
597 : 0 : PyErr_SetString(con->state->ProgrammingError,
598 : : "Cannot operate on a closed database.");
599 : 0 : return 0;
600 : : } else {
601 : 0 : return 1;
602 : : }
603 : : }
604 : :
605 : : /*[clinic input]
606 : : _sqlite3.Connection.commit as pysqlite_connection_commit
607 : :
608 : : Commit any pending transaction to the database.
609 : :
610 : : If there is no open transaction, this method is a no-op.
611 : : [clinic start generated code]*/
612 : :
613 : : static PyObject *
614 : 0 : pysqlite_connection_commit_impl(pysqlite_Connection *self)
615 : : /*[clinic end generated code: output=3da45579e89407f2 input=c8793c97c3446065]*/
616 : : {
617 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
618 : 0 : return NULL;
619 : : }
620 : :
621 [ # # ]: 0 : if (self->autocommit == AUTOCOMMIT_LEGACY) {
622 [ # # ]: 0 : if (!sqlite3_get_autocommit(self->db)) {
623 [ # # ]: 0 : if (connection_exec_stmt(self, "COMMIT") < 0) {
624 : 0 : return NULL;
625 : : }
626 : : }
627 : : }
628 [ # # ]: 0 : else if (self->autocommit == AUTOCOMMIT_DISABLED) {
629 [ # # ]: 0 : if (connection_exec_stmt(self, "COMMIT") < 0) {
630 : 0 : return NULL;
631 : : }
632 [ # # ]: 0 : if (connection_exec_stmt(self, "BEGIN") < 0) {
633 : 0 : return NULL;
634 : : }
635 : : }
636 : 0 : Py_RETURN_NONE;
637 : : }
638 : :
639 : : /*[clinic input]
640 : : _sqlite3.Connection.rollback as pysqlite_connection_rollback
641 : :
642 : : Roll back to the start of any pending transaction.
643 : :
644 : : If there is no open transaction, this method is a no-op.
645 : : [clinic start generated code]*/
646 : :
647 : : static PyObject *
648 : 0 : pysqlite_connection_rollback_impl(pysqlite_Connection *self)
649 : : /*[clinic end generated code: output=b66fa0d43e7ef305 input=7f60a2f1076f16b3]*/
650 : : {
651 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
652 : 0 : return NULL;
653 : : }
654 : :
655 [ # # ]: 0 : if (self->autocommit == AUTOCOMMIT_LEGACY) {
656 [ # # ]: 0 : if (!sqlite3_get_autocommit(self->db)) {
657 [ # # ]: 0 : if (connection_exec_stmt(self, "ROLLBACK") < 0) {
658 : 0 : return NULL;
659 : : }
660 : : }
661 : : }
662 [ # # ]: 0 : else if (self->autocommit == AUTOCOMMIT_DISABLED) {
663 [ # # ]: 0 : if (connection_exec_stmt(self, "ROLLBACK") < 0) {
664 : 0 : return NULL;
665 : : }
666 [ # # ]: 0 : if (connection_exec_stmt(self, "BEGIN") < 0) {
667 : 0 : return NULL;
668 : : }
669 : : }
670 : 0 : Py_RETURN_NONE;
671 : : }
672 : :
673 : : static int
674 : 0 : _pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
675 : : {
676 [ # # ]: 0 : if (py_val == Py_None) {
677 : 0 : sqlite3_result_null(context);
678 [ # # ]: 0 : } else if (PyLong_Check(py_val)) {
679 : 0 : sqlite_int64 value = _pysqlite_long_as_int64(py_val);
680 [ # # # # ]: 0 : if (value == -1 && PyErr_Occurred())
681 : 0 : return -1;
682 : 0 : sqlite3_result_int64(context, value);
683 [ # # ]: 0 : } else if (PyFloat_Check(py_val)) {
684 : 0 : double value = PyFloat_AsDouble(py_val);
685 [ # # # # ]: 0 : if (value == -1 && PyErr_Occurred()) {
686 : 0 : return -1;
687 : : }
688 : 0 : sqlite3_result_double(context, value);
689 [ # # ]: 0 : } else if (PyUnicode_Check(py_val)) {
690 : : Py_ssize_t sz;
691 : 0 : const char *str = PyUnicode_AsUTF8AndSize(py_val, &sz);
692 [ # # ]: 0 : if (str == NULL) {
693 : 0 : return -1;
694 : : }
695 [ # # ]: 0 : if (sz > INT_MAX) {
696 : 0 : PyErr_SetString(PyExc_OverflowError,
697 : : "string is longer than INT_MAX bytes");
698 : 0 : return -1;
699 : : }
700 : 0 : sqlite3_result_text(context, str, (int)sz, SQLITE_TRANSIENT);
701 [ # # ]: 0 : } else if (PyObject_CheckBuffer(py_val)) {
702 : : Py_buffer view;
703 [ # # ]: 0 : if (PyObject_GetBuffer(py_val, &view, PyBUF_SIMPLE) != 0) {
704 : 0 : return -1;
705 : : }
706 [ # # ]: 0 : if (view.len > INT_MAX) {
707 : 0 : PyErr_SetString(PyExc_OverflowError,
708 : : "BLOB longer than INT_MAX bytes");
709 : 0 : PyBuffer_Release(&view);
710 : 0 : return -1;
711 : : }
712 : 0 : sqlite3_result_blob(context, view.buf, (int)view.len, SQLITE_TRANSIENT);
713 : 0 : PyBuffer_Release(&view);
714 : : } else {
715 : 0 : callback_context *ctx = (callback_context *)sqlite3_user_data(context);
716 : 0 : PyErr_Format(ctx->state->ProgrammingError,
717 : : "User-defined functions cannot return '%s' values to "
718 : : "SQLite",
719 : 0 : Py_TYPE(py_val)->tp_name);
720 : 0 : return -1;
721 : : }
722 : 0 : return 0;
723 : : }
724 : :
725 : : static PyObject *
726 : 0 : _pysqlite_build_py_params(sqlite3_context *context, int argc,
727 : : sqlite3_value **argv)
728 : : {
729 : : PyObject* args;
730 : : int i;
731 : : sqlite3_value* cur_value;
732 : : PyObject* cur_py_value;
733 : :
734 : 0 : args = PyTuple_New(argc);
735 [ # # ]: 0 : if (!args) {
736 : 0 : return NULL;
737 : : }
738 : :
739 [ # # ]: 0 : for (i = 0; i < argc; i++) {
740 : 0 : cur_value = argv[i];
741 [ # # # # : 0 : switch (sqlite3_value_type(argv[i])) {
# ]
742 : 0 : case SQLITE_INTEGER:
743 : 0 : cur_py_value = PyLong_FromLongLong(sqlite3_value_int64(cur_value));
744 : 0 : break;
745 : 0 : case SQLITE_FLOAT:
746 : 0 : cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
747 : 0 : break;
748 : 0 : case SQLITE_TEXT: {
749 : 0 : sqlite3 *db = sqlite3_context_db_handle(context);
750 : 0 : const char *text = (const char *)sqlite3_value_text(cur_value);
751 : :
752 [ # # # # ]: 0 : if (text == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
753 : 0 : PyErr_NoMemory();
754 : 0 : goto error;
755 : : }
756 : :
757 : 0 : Py_ssize_t size = sqlite3_value_bytes(cur_value);
758 : 0 : cur_py_value = PyUnicode_FromStringAndSize(text, size);
759 : 0 : break;
760 : : }
761 : 0 : case SQLITE_BLOB: {
762 : 0 : sqlite3 *db = sqlite3_context_db_handle(context);
763 : 0 : const void *blob = sqlite3_value_blob(cur_value);
764 : :
765 [ # # # # ]: 0 : if (blob == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
766 : 0 : PyErr_NoMemory();
767 : 0 : goto error;
768 : : }
769 : :
770 : 0 : Py_ssize_t size = sqlite3_value_bytes(cur_value);
771 : 0 : cur_py_value = PyBytes_FromStringAndSize(blob, size);
772 : 0 : break;
773 : : }
774 : 0 : case SQLITE_NULL:
775 : : default:
776 : 0 : cur_py_value = Py_NewRef(Py_None);
777 : : }
778 : :
779 [ # # ]: 0 : if (!cur_py_value) {
780 : 0 : goto error;
781 : : }
782 : :
783 : 0 : PyTuple_SET_ITEM(args, i, cur_py_value);
784 : : }
785 : :
786 : 0 : return args;
787 : :
788 : 0 : error:
789 : 0 : Py_DECREF(args);
790 : 0 : return NULL;
791 : : }
792 : :
793 : : static void
794 : 0 : print_or_clear_traceback(callback_context *ctx)
795 : : {
796 : : assert(ctx != NULL);
797 : : assert(ctx->state != NULL);
798 [ # # ]: 0 : if (ctx->state->enable_callback_tracebacks) {
799 : 0 : PyErr_WriteUnraisable(ctx->callable);
800 : : }
801 : : else {
802 : 0 : PyErr_Clear();
803 : : }
804 : 0 : }
805 : :
806 : : // Checks the Python exception and sets the appropriate SQLite error code.
807 : : static void
808 : 0 : set_sqlite_error(sqlite3_context *context, const char *msg)
809 : : {
810 : : assert(PyErr_Occurred());
811 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
812 : 0 : sqlite3_result_error_nomem(context);
813 : : }
814 [ # # ]: 0 : else if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
815 : 0 : sqlite3_result_error_toobig(context);
816 : : }
817 : : else {
818 : 0 : sqlite3_result_error(context, msg, -1);
819 : : }
820 : 0 : callback_context *ctx = (callback_context *)sqlite3_user_data(context);
821 : 0 : print_or_clear_traceback(ctx);
822 : 0 : }
823 : :
824 : : static void
825 : 0 : func_callback(sqlite3_context *context, int argc, sqlite3_value **argv)
826 : : {
827 : 0 : PyGILState_STATE threadstate = PyGILState_Ensure();
828 : :
829 : : PyObject* args;
830 : 0 : PyObject* py_retval = NULL;
831 : : int ok;
832 : :
833 : 0 : args = _pysqlite_build_py_params(context, argc, argv);
834 [ # # ]: 0 : if (args) {
835 : 0 : callback_context *ctx = (callback_context *)sqlite3_user_data(context);
836 : : assert(ctx != NULL);
837 : 0 : py_retval = PyObject_CallObject(ctx->callable, args);
838 : 0 : Py_DECREF(args);
839 : : }
840 : :
841 : 0 : ok = 0;
842 [ # # ]: 0 : if (py_retval) {
843 : 0 : ok = _pysqlite_set_result(context, py_retval) == 0;
844 : 0 : Py_DECREF(py_retval);
845 : : }
846 [ # # ]: 0 : if (!ok) {
847 : 0 : set_sqlite_error(context, "user-defined function raised exception");
848 : : }
849 : :
850 : 0 : PyGILState_Release(threadstate);
851 : 0 : }
852 : :
853 : : static void
854 : 0 : step_callback(sqlite3_context *context, int argc, sqlite3_value **params)
855 : : {
856 : 0 : PyGILState_STATE threadstate = PyGILState_Ensure();
857 : :
858 : : PyObject* args;
859 : 0 : PyObject* function_result = NULL;
860 : : PyObject** aggregate_instance;
861 : 0 : PyObject* stepmethod = NULL;
862 : :
863 : 0 : callback_context *ctx = (callback_context *)sqlite3_user_data(context);
864 : : assert(ctx != NULL);
865 : :
866 : 0 : aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
867 [ # # ]: 0 : if (*aggregate_instance == NULL) {
868 : 0 : *aggregate_instance = PyObject_CallNoArgs(ctx->callable);
869 [ # # ]: 0 : if (!*aggregate_instance) {
870 : 0 : set_sqlite_error(context,
871 : : "user-defined aggregate's '__init__' method raised error");
872 : 0 : goto error;
873 : : }
874 : : }
875 : :
876 : 0 : stepmethod = PyObject_GetAttr(*aggregate_instance, ctx->state->str_step);
877 [ # # ]: 0 : if (!stepmethod) {
878 : 0 : set_sqlite_error(context,
879 : : "user-defined aggregate's 'step' method not defined");
880 : 0 : goto error;
881 : : }
882 : :
883 : 0 : args = _pysqlite_build_py_params(context, argc, params);
884 [ # # ]: 0 : if (!args) {
885 : 0 : goto error;
886 : : }
887 : :
888 : 0 : function_result = PyObject_CallObject(stepmethod, args);
889 : 0 : Py_DECREF(args);
890 : :
891 [ # # ]: 0 : if (!function_result) {
892 : 0 : set_sqlite_error(context,
893 : : "user-defined aggregate's 'step' method raised error");
894 : : }
895 : :
896 : 0 : error:
897 : 0 : Py_XDECREF(stepmethod);
898 : 0 : Py_XDECREF(function_result);
899 : :
900 : 0 : PyGILState_Release(threadstate);
901 : 0 : }
902 : :
903 : : static void
904 : 0 : final_callback(sqlite3_context *context)
905 : : {
906 : 0 : PyGILState_STATE threadstate = PyGILState_Ensure();
907 : :
908 : : PyObject* function_result;
909 : : PyObject** aggregate_instance;
910 : : int ok;
911 : :
912 : 0 : aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, 0);
913 [ # # ]: 0 : if (aggregate_instance == NULL) {
914 : : /* No rows matched the query; the step handler was never called. */
915 : 0 : goto error;
916 : : }
917 [ # # ]: 0 : else if (!*aggregate_instance) {
918 : : /* this branch is executed if there was an exception in the aggregate's
919 : : * __init__ */
920 : :
921 : 0 : goto error;
922 : : }
923 : :
924 : : // Keep the exception (if any) of the last call to step, value, or inverse
925 : 0 : PyObject *exc = PyErr_GetRaisedException();
926 : :
927 : 0 : callback_context *ctx = (callback_context *)sqlite3_user_data(context);
928 : : assert(ctx != NULL);
929 : 0 : function_result = PyObject_CallMethodNoArgs(*aggregate_instance,
930 : 0 : ctx->state->str_finalize);
931 : 0 : Py_DECREF(*aggregate_instance);
932 : :
933 : 0 : ok = 0;
934 [ # # ]: 0 : if (function_result) {
935 : 0 : ok = _pysqlite_set_result(context, function_result) == 0;
936 : 0 : Py_DECREF(function_result);
937 : : }
938 [ # # ]: 0 : if (!ok) {
939 : 0 : int attr_err = PyErr_ExceptionMatches(PyExc_AttributeError);
940 : 0 : _PyErr_ChainExceptions1(exc);
941 : :
942 : : /* Note: contrary to the step, value, and inverse callbacks, SQLite
943 : : * does _not_, as of SQLite 3.38.0, propagate errors to sqlite3_step()
944 : : * from the finalize callback. This implies that execute*() will not
945 : : * raise OperationalError, as it normally would. */
946 [ # # ]: 0 : set_sqlite_error(context, attr_err
947 : : ? "user-defined aggregate's 'finalize' method not defined"
948 : : : "user-defined aggregate's 'finalize' method raised error");
949 : : }
950 : : else {
951 : 0 : PyErr_SetRaisedException(exc);
952 : : }
953 : :
954 : 0 : error:
955 : 0 : PyGILState_Release(threadstate);
956 : 0 : }
957 : :
958 : 0 : static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
959 : : {
960 : : PyObject* new_list;
961 : : PyObject* weakref;
962 : : int i;
963 : :
964 : : /* we only need to do this once in a while */
965 [ # # ]: 0 : if (self->created_cursors++ < 200) {
966 : 0 : return;
967 : : }
968 : :
969 : 0 : self->created_cursors = 0;
970 : :
971 : 0 : new_list = PyList_New(0);
972 [ # # ]: 0 : if (!new_list) {
973 : 0 : return;
974 : : }
975 : :
976 [ # # ]: 0 : for (i = 0; i < PyList_Size(self->cursors); i++) {
977 : 0 : weakref = PyList_GetItem(self->cursors, i);
978 [ # # ]: 0 : if (PyWeakref_GetObject(weakref) != Py_None) {
979 [ # # ]: 0 : if (PyList_Append(new_list, weakref) != 0) {
980 : 0 : Py_DECREF(new_list);
981 : 0 : return;
982 : : }
983 : : }
984 : : }
985 : :
986 : 0 : Py_SETREF(self->cursors, new_list);
987 : : }
988 : :
989 : : /* Allocate a UDF/callback context structure. In order to ensure that the state
990 : : * pointer always outlives the callback context, we make sure it owns a
991 : : * reference to the module itself. create_callback_context() is always called
992 : : * from connection methods, so we use the defining class to fetch the module
993 : : * pointer.
994 : : */
995 : : static callback_context *
996 : 0 : create_callback_context(PyTypeObject *cls, PyObject *callable)
997 : : {
998 : 0 : callback_context *ctx = PyMem_Malloc(sizeof(callback_context));
999 [ # # ]: 0 : if (ctx != NULL) {
1000 : 0 : PyObject *module = PyType_GetModule(cls);
1001 : 0 : ctx->callable = Py_NewRef(callable);
1002 : 0 : ctx->module = Py_NewRef(module);
1003 : 0 : ctx->state = pysqlite_get_state(module);
1004 : : }
1005 : 0 : return ctx;
1006 : : }
1007 : :
1008 : : static void
1009 : 0 : free_callback_context(callback_context *ctx)
1010 : : {
1011 : : assert(ctx != NULL);
1012 : 0 : Py_XDECREF(ctx->callable);
1013 : 0 : Py_XDECREF(ctx->module);
1014 : 0 : PyMem_Free(ctx);
1015 : 0 : }
1016 : :
1017 : : static void
1018 : 0 : set_callback_context(callback_context **ctx_pp, callback_context *ctx)
1019 : : {
1020 : : assert(ctx_pp != NULL);
1021 : 0 : callback_context *tmp = *ctx_pp;
1022 : 0 : *ctx_pp = ctx;
1023 [ # # ]: 0 : if (tmp != NULL) {
1024 : 0 : free_callback_context(tmp);
1025 : : }
1026 : 0 : }
1027 : :
1028 : : static void
1029 : 0 : destructor_callback(void *ctx)
1030 : : {
1031 [ # # ]: 0 : if (ctx != NULL) {
1032 : : // This function may be called without the GIL held, so we need to
1033 : : // ensure that we destroy 'ctx' with the GIL held.
1034 : 0 : PyGILState_STATE gstate = PyGILState_Ensure();
1035 : 0 : free_callback_context((callback_context *)ctx);
1036 : 0 : PyGILState_Release(gstate);
1037 : : }
1038 : 0 : }
1039 : :
1040 : : /*[clinic input]
1041 : : _sqlite3.Connection.create_function as pysqlite_connection_create_function
1042 : :
1043 : : cls: defining_class
1044 : : /
1045 : : name: str
1046 : : narg: int
1047 : : func: object
1048 : : *
1049 : : deterministic: bool = False
1050 : :
1051 : : Creates a new function.
1052 : : [clinic start generated code]*/
1053 : :
1054 : : static PyObject *
1055 : 0 : pysqlite_connection_create_function_impl(pysqlite_Connection *self,
1056 : : PyTypeObject *cls, const char *name,
1057 : : int narg, PyObject *func,
1058 : : int deterministic)
1059 : : /*[clinic end generated code: output=8a811529287ad240 input=b3e8e1d8ddaffbef]*/
1060 : : {
1061 : : int rc;
1062 : 0 : int flags = SQLITE_UTF8;
1063 : :
1064 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1065 : 0 : return NULL;
1066 : : }
1067 : :
1068 [ # # ]: 0 : if (deterministic) {
1069 : : #if SQLITE_VERSION_NUMBER < 3008003
1070 : : PyErr_SetString(self->NotSupportedError,
1071 : : "deterministic=True requires SQLite 3.8.3 or higher");
1072 : : return NULL;
1073 : : #else
1074 [ # # ]: 0 : if (sqlite3_libversion_number() < 3008003) {
1075 : 0 : PyErr_SetString(self->NotSupportedError,
1076 : : "deterministic=True requires SQLite 3.8.3 or higher");
1077 : 0 : return NULL;
1078 : : }
1079 : 0 : flags |= SQLITE_DETERMINISTIC;
1080 : : #endif
1081 : : }
1082 : 0 : callback_context *ctx = create_callback_context(cls, func);
1083 [ # # ]: 0 : if (ctx == NULL) {
1084 : 0 : return NULL;
1085 : : }
1086 : 0 : rc = sqlite3_create_function_v2(self->db, name, narg, flags, ctx,
1087 : : func_callback,
1088 : : NULL,
1089 : : NULL,
1090 : : &destructor_callback); // will decref func
1091 : :
1092 [ # # ]: 0 : if (rc != SQLITE_OK) {
1093 : : /* Workaround for SQLite bug: no error code or string is available here */
1094 : 0 : PyErr_SetString(self->OperationalError, "Error creating function");
1095 : 0 : return NULL;
1096 : : }
1097 : 0 : Py_RETURN_NONE;
1098 : : }
1099 : :
1100 : : #ifdef HAVE_WINDOW_FUNCTIONS
1101 : : /*
1102 : : * Regarding the 'inverse' aggregate callback:
1103 : : * This method is only required by window aggregate functions, not
1104 : : * ordinary aggregate function implementations. It is invoked to remove
1105 : : * a row from the current window. The function arguments, if any,
1106 : : * correspond to the row being removed.
1107 : : */
1108 : : static void
1109 : 0 : inverse_callback(sqlite3_context *context, int argc, sqlite3_value **params)
1110 : : {
1111 : 0 : PyGILState_STATE gilstate = PyGILState_Ensure();
1112 : :
1113 : 0 : callback_context *ctx = (callback_context *)sqlite3_user_data(context);
1114 : : assert(ctx != NULL);
1115 : :
1116 : 0 : int size = sizeof(PyObject *);
1117 : 0 : PyObject **cls = (PyObject **)sqlite3_aggregate_context(context, size);
1118 : : assert(cls != NULL);
1119 : : assert(*cls != NULL);
1120 : :
1121 : 0 : PyObject *method = PyObject_GetAttr(*cls, ctx->state->str_inverse);
1122 [ # # ]: 0 : if (method == NULL) {
1123 : 0 : set_sqlite_error(context,
1124 : : "user-defined aggregate's 'inverse' method not defined");
1125 : 0 : goto exit;
1126 : : }
1127 : :
1128 : 0 : PyObject *args = _pysqlite_build_py_params(context, argc, params);
1129 [ # # ]: 0 : if (args == NULL) {
1130 : 0 : set_sqlite_error(context,
1131 : : "unable to build arguments for user-defined aggregate's "
1132 : : "'inverse' method");
1133 : 0 : goto exit;
1134 : : }
1135 : :
1136 : 0 : PyObject *res = PyObject_CallObject(method, args);
1137 : 0 : Py_DECREF(args);
1138 [ # # ]: 0 : if (res == NULL) {
1139 : 0 : set_sqlite_error(context,
1140 : : "user-defined aggregate's 'inverse' method raised error");
1141 : 0 : goto exit;
1142 : : }
1143 : 0 : Py_DECREF(res);
1144 : :
1145 : 0 : exit:
1146 : 0 : Py_XDECREF(method);
1147 : 0 : PyGILState_Release(gilstate);
1148 : 0 : }
1149 : :
1150 : : /*
1151 : : * Regarding the 'value' aggregate callback:
1152 : : * This method is only required by window aggregate functions, not
1153 : : * ordinary aggregate function implementations. It is invoked to return
1154 : : * the current value of the aggregate.
1155 : : */
1156 : : static void
1157 : 0 : value_callback(sqlite3_context *context)
1158 : : {
1159 : 0 : PyGILState_STATE gilstate = PyGILState_Ensure();
1160 : :
1161 : 0 : callback_context *ctx = (callback_context *)sqlite3_user_data(context);
1162 : : assert(ctx != NULL);
1163 : :
1164 : 0 : int size = sizeof(PyObject *);
1165 : 0 : PyObject **cls = (PyObject **)sqlite3_aggregate_context(context, size);
1166 : : assert(cls != NULL);
1167 : : assert(*cls != NULL);
1168 : :
1169 : 0 : PyObject *res = PyObject_CallMethodNoArgs(*cls, ctx->state->str_value);
1170 [ # # ]: 0 : if (res == NULL) {
1171 : 0 : int attr_err = PyErr_ExceptionMatches(PyExc_AttributeError);
1172 [ # # ]: 0 : set_sqlite_error(context, attr_err
1173 : : ? "user-defined aggregate's 'value' method not defined"
1174 : : : "user-defined aggregate's 'value' method raised error");
1175 : : }
1176 : : else {
1177 : 0 : int rc = _pysqlite_set_result(context, res);
1178 : 0 : Py_DECREF(res);
1179 [ # # ]: 0 : if (rc < 0) {
1180 : 0 : set_sqlite_error(context,
1181 : : "unable to set result from user-defined aggregate's "
1182 : : "'value' method");
1183 : : }
1184 : : }
1185 : :
1186 : 0 : PyGILState_Release(gilstate);
1187 : 0 : }
1188 : :
1189 : : /*[clinic input]
1190 : : _sqlite3.Connection.create_window_function as create_window_function
1191 : :
1192 : : cls: defining_class
1193 : : name: str
1194 : : The name of the SQL aggregate window function to be created or
1195 : : redefined.
1196 : : num_params: int
1197 : : The number of arguments the step and inverse methods takes.
1198 : : aggregate_class: object
1199 : : A class with step(), finalize(), value(), and inverse() methods.
1200 : : Set to None to clear the window function.
1201 : : /
1202 : :
1203 : : Creates or redefines an aggregate window function. Non-standard.
1204 : : [clinic start generated code]*/
1205 : :
1206 : : static PyObject *
1207 : 0 : create_window_function_impl(pysqlite_Connection *self, PyTypeObject *cls,
1208 : : const char *name, int num_params,
1209 : : PyObject *aggregate_class)
1210 : : /*[clinic end generated code: output=5332cd9464522235 input=46d57a54225b5228]*/
1211 : : {
1212 [ # # ]: 0 : if (sqlite3_libversion_number() < 3025000) {
1213 : 0 : PyErr_SetString(self->NotSupportedError,
1214 : : "create_window_function() requires "
1215 : : "SQLite 3.25.0 or higher");
1216 : 0 : return NULL;
1217 : : }
1218 : :
1219 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1220 : 0 : return NULL;
1221 : : }
1222 : :
1223 : 0 : int flags = SQLITE_UTF8;
1224 : : int rc;
1225 [ # # ]: 0 : if (Py_IsNone(aggregate_class)) {
1226 : 0 : rc = sqlite3_create_window_function(self->db, name, num_params, flags,
1227 : : 0, 0, 0, 0, 0, 0);
1228 : : }
1229 : : else {
1230 : 0 : callback_context *ctx = create_callback_context(cls, aggregate_class);
1231 [ # # ]: 0 : if (ctx == NULL) {
1232 : 0 : return NULL;
1233 : : }
1234 : 0 : rc = sqlite3_create_window_function(self->db, name, num_params, flags,
1235 : : ctx,
1236 : : &step_callback,
1237 : : &final_callback,
1238 : : &value_callback,
1239 : : &inverse_callback,
1240 : : &destructor_callback);
1241 : : }
1242 : :
1243 [ # # ]: 0 : if (rc != SQLITE_OK) {
1244 : : // Errors are not set on the database connection, so we cannot
1245 : : // use _pysqlite_seterror().
1246 : 0 : PyErr_SetString(self->ProgrammingError, sqlite3_errstr(rc));
1247 : 0 : return NULL;
1248 : : }
1249 : 0 : Py_RETURN_NONE;
1250 : : }
1251 : : #endif
1252 : :
1253 : : /*[clinic input]
1254 : : _sqlite3.Connection.create_aggregate as pysqlite_connection_create_aggregate
1255 : :
1256 : : cls: defining_class
1257 : : /
1258 : : name: str
1259 : : n_arg: int
1260 : : aggregate_class: object
1261 : :
1262 : : Creates a new aggregate.
1263 : : [clinic start generated code]*/
1264 : :
1265 : : static PyObject *
1266 : 0 : pysqlite_connection_create_aggregate_impl(pysqlite_Connection *self,
1267 : : PyTypeObject *cls,
1268 : : const char *name, int n_arg,
1269 : : PyObject *aggregate_class)
1270 : : /*[clinic end generated code: output=1b02d0f0aec7ff96 input=68a2a26366d4c686]*/
1271 : : {
1272 : : int rc;
1273 : :
1274 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1275 : 0 : return NULL;
1276 : : }
1277 : :
1278 : 0 : callback_context *ctx = create_callback_context(cls, aggregate_class);
1279 [ # # ]: 0 : if (ctx == NULL) {
1280 : 0 : return NULL;
1281 : : }
1282 : 0 : rc = sqlite3_create_function_v2(self->db, name, n_arg, SQLITE_UTF8, ctx,
1283 : : 0,
1284 : : &step_callback,
1285 : : &final_callback,
1286 : : &destructor_callback); // will decref func
1287 [ # # ]: 0 : if (rc != SQLITE_OK) {
1288 : : /* Workaround for SQLite bug: no error code or string is available here */
1289 : 0 : PyErr_SetString(self->OperationalError, "Error creating aggregate");
1290 : 0 : return NULL;
1291 : : }
1292 : 0 : Py_RETURN_NONE;
1293 : : }
1294 : :
1295 : : static int
1296 : 0 : authorizer_callback(void *ctx, int action, const char *arg1,
1297 : : const char *arg2 , const char *dbname,
1298 : : const char *access_attempt_source)
1299 : : {
1300 : 0 : PyGILState_STATE gilstate = PyGILState_Ensure();
1301 : :
1302 : : PyObject *ret;
1303 : 0 : int rc = SQLITE_DENY;
1304 : :
1305 : : assert(ctx != NULL);
1306 : 0 : PyObject *callable = ((callback_context *)ctx)->callable;
1307 : 0 : ret = PyObject_CallFunction(callable, "issss", action, arg1, arg2, dbname,
1308 : : access_attempt_source);
1309 : :
1310 [ # # ]: 0 : if (ret == NULL) {
1311 : 0 : print_or_clear_traceback(ctx);
1312 : 0 : rc = SQLITE_DENY;
1313 : : }
1314 : : else {
1315 [ # # ]: 0 : if (PyLong_Check(ret)) {
1316 : 0 : rc = _PyLong_AsInt(ret);
1317 [ # # # # ]: 0 : if (rc == -1 && PyErr_Occurred()) {
1318 : 0 : print_or_clear_traceback(ctx);
1319 : 0 : rc = SQLITE_DENY;
1320 : : }
1321 : : }
1322 : : else {
1323 : 0 : rc = SQLITE_DENY;
1324 : : }
1325 : 0 : Py_DECREF(ret);
1326 : : }
1327 : :
1328 : 0 : PyGILState_Release(gilstate);
1329 : 0 : return rc;
1330 : : }
1331 : :
1332 : : static int
1333 : 0 : progress_callback(void *ctx)
1334 : : {
1335 : 0 : PyGILState_STATE gilstate = PyGILState_Ensure();
1336 : :
1337 : : int rc;
1338 : : PyObject *ret;
1339 : :
1340 : : assert(ctx != NULL);
1341 : 0 : PyObject *callable = ((callback_context *)ctx)->callable;
1342 : 0 : ret = PyObject_CallNoArgs(callable);
1343 [ # # ]: 0 : if (!ret) {
1344 : : /* abort query if error occurred */
1345 : 0 : rc = -1;
1346 : : }
1347 : : else {
1348 : 0 : rc = PyObject_IsTrue(ret);
1349 : 0 : Py_DECREF(ret);
1350 : : }
1351 [ # # ]: 0 : if (rc < 0) {
1352 : 0 : print_or_clear_traceback(ctx);
1353 : : }
1354 : :
1355 : 0 : PyGILState_Release(gilstate);
1356 : 0 : return rc;
1357 : : }
1358 : :
1359 : : #ifdef HAVE_TRACE_V2
1360 : : /*
1361 : : * From https://sqlite.org/c3ref/trace_v2.html:
1362 : : * The integer return value from the callback is currently ignored, though this
1363 : : * may change in future releases. Callback implementations should return zero
1364 : : * to ensure future compatibility.
1365 : : */
1366 : : static int
1367 : 0 : trace_callback(unsigned int type, void *ctx, void *stmt, void *sql)
1368 : : #else
1369 : : static void
1370 : : trace_callback(void *ctx, const char *sql)
1371 : : #endif
1372 : : {
1373 : : #ifdef HAVE_TRACE_V2
1374 [ # # ]: 0 : if (type != SQLITE_TRACE_STMT) {
1375 : 0 : return 0;
1376 : : }
1377 : : #endif
1378 : :
1379 : 0 : PyGILState_STATE gilstate = PyGILState_Ensure();
1380 : :
1381 : : assert(ctx != NULL);
1382 : 0 : pysqlite_state *state = ((callback_context *)ctx)->state;
1383 : : assert(state != NULL);
1384 : :
1385 : 0 : PyObject *py_statement = NULL;
1386 : : #ifdef HAVE_TRACE_V2
1387 : 0 : const char *expanded_sql = sqlite3_expanded_sql((sqlite3_stmt *)stmt);
1388 [ # # ]: 0 : if (expanded_sql == NULL) {
1389 : 0 : sqlite3 *db = sqlite3_db_handle((sqlite3_stmt *)stmt);
1390 [ # # ]: 0 : if (sqlite3_errcode(db) == SQLITE_NOMEM) {
1391 : 0 : (void)PyErr_NoMemory();
1392 : 0 : goto exit;
1393 : : }
1394 : :
1395 : 0 : PyErr_SetString(state->DataError,
1396 : : "Expanded SQL string exceeds the maximum string length");
1397 : 0 : print_or_clear_traceback((callback_context *)ctx);
1398 : :
1399 : : // Fall back to unexpanded sql
1400 : 0 : py_statement = PyUnicode_FromString((const char *)sql);
1401 : : }
1402 : : else {
1403 : 0 : py_statement = PyUnicode_FromString(expanded_sql);
1404 : 0 : sqlite3_free((void *)expanded_sql);
1405 : : }
1406 : : #else
1407 : : if (sql == NULL) {
1408 : : PyErr_SetString(state->DataError,
1409 : : "Expanded SQL string exceeds the maximum string length");
1410 : : print_or_clear_traceback((callback_context *)ctx);
1411 : : goto exit;
1412 : : }
1413 : : py_statement = PyUnicode_FromString(sql);
1414 : : #endif
1415 [ # # ]: 0 : if (py_statement) {
1416 : 0 : PyObject *callable = ((callback_context *)ctx)->callable;
1417 : 0 : PyObject *ret = PyObject_CallOneArg(callable, py_statement);
1418 : 0 : Py_DECREF(py_statement);
1419 : 0 : Py_XDECREF(ret);
1420 : : }
1421 [ # # ]: 0 : if (PyErr_Occurred()) {
1422 : 0 : print_or_clear_traceback((callback_context *)ctx);
1423 : : }
1424 : :
1425 : 0 : exit:
1426 : 0 : PyGILState_Release(gilstate);
1427 : : #ifdef HAVE_TRACE_V2
1428 : 0 : return 0;
1429 : : #endif
1430 : : }
1431 : :
1432 : : /*[clinic input]
1433 : : _sqlite3.Connection.set_authorizer as pysqlite_connection_set_authorizer
1434 : :
1435 : : cls: defining_class
1436 : : /
1437 : : authorizer_callback as callable: object
1438 : :
1439 : : Sets authorizer callback.
1440 : : [clinic start generated code]*/
1441 : :
1442 : : static PyObject *
1443 : 0 : pysqlite_connection_set_authorizer_impl(pysqlite_Connection *self,
1444 : : PyTypeObject *cls,
1445 : : PyObject *callable)
1446 : : /*[clinic end generated code: output=75fa60114fc971c3 input=605d32ba92dd3eca]*/
1447 : : {
1448 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1449 : 0 : return NULL;
1450 : : }
1451 : :
1452 : : int rc;
1453 [ # # ]: 0 : if (callable == Py_None) {
1454 : 0 : rc = sqlite3_set_authorizer(self->db, NULL, NULL);
1455 : 0 : set_callback_context(&self->authorizer_ctx, NULL);
1456 : : }
1457 : : else {
1458 : 0 : callback_context *ctx = create_callback_context(cls, callable);
1459 [ # # ]: 0 : if (ctx == NULL) {
1460 : 0 : return NULL;
1461 : : }
1462 : 0 : rc = sqlite3_set_authorizer(self->db, authorizer_callback, ctx);
1463 : 0 : set_callback_context(&self->authorizer_ctx, ctx);
1464 : : }
1465 [ # # ]: 0 : if (rc != SQLITE_OK) {
1466 : 0 : PyErr_SetString(self->OperationalError,
1467 : : "Error setting authorizer callback");
1468 : 0 : set_callback_context(&self->authorizer_ctx, NULL);
1469 : 0 : return NULL;
1470 : : }
1471 : 0 : Py_RETURN_NONE;
1472 : : }
1473 : :
1474 : : /*[clinic input]
1475 : : _sqlite3.Connection.set_progress_handler as pysqlite_connection_set_progress_handler
1476 : :
1477 : : cls: defining_class
1478 : : /
1479 : : progress_handler as callable: object
1480 : : n: int
1481 : :
1482 : : Sets progress handler callback.
1483 : : [clinic start generated code]*/
1484 : :
1485 : : static PyObject *
1486 : 0 : pysqlite_connection_set_progress_handler_impl(pysqlite_Connection *self,
1487 : : PyTypeObject *cls,
1488 : : PyObject *callable, int n)
1489 : : /*[clinic end generated code: output=0739957fd8034a50 input=f7c1837984bd86db]*/
1490 : : {
1491 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1492 : 0 : return NULL;
1493 : : }
1494 : :
1495 [ # # ]: 0 : if (callable == Py_None) {
1496 : : /* None clears the progress handler previously set */
1497 : 0 : sqlite3_progress_handler(self->db, 0, 0, (void*)0);
1498 : 0 : set_callback_context(&self->progress_ctx, NULL);
1499 : : }
1500 : : else {
1501 : 0 : callback_context *ctx = create_callback_context(cls, callable);
1502 [ # # ]: 0 : if (ctx == NULL) {
1503 : 0 : return NULL;
1504 : : }
1505 : 0 : sqlite3_progress_handler(self->db, n, progress_callback, ctx);
1506 : 0 : set_callback_context(&self->progress_ctx, ctx);
1507 : : }
1508 : 0 : Py_RETURN_NONE;
1509 : : }
1510 : :
1511 : : /*[clinic input]
1512 : : _sqlite3.Connection.set_trace_callback as pysqlite_connection_set_trace_callback
1513 : :
1514 : : cls: defining_class
1515 : : /
1516 : : trace_callback as callable: object
1517 : :
1518 : : Sets a trace callback called for each SQL statement (passed as unicode).
1519 : : [clinic start generated code]*/
1520 : :
1521 : : static PyObject *
1522 : 0 : pysqlite_connection_set_trace_callback_impl(pysqlite_Connection *self,
1523 : : PyTypeObject *cls,
1524 : : PyObject *callable)
1525 : : /*[clinic end generated code: output=d91048c03bfcee05 input=351a94210c5f81bb]*/
1526 : : {
1527 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1528 : 0 : return NULL;
1529 : : }
1530 : :
1531 [ # # ]: 0 : if (callable == Py_None) {
1532 : : /*
1533 : : * None clears the trace callback previously set
1534 : : *
1535 : : * Ref.
1536 : : * - https://sqlite.org/c3ref/c_trace.html
1537 : : * - https://sqlite.org/c3ref/trace_v2.html
1538 : : */
1539 : : #ifdef HAVE_TRACE_V2
1540 : 0 : sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, 0, 0);
1541 : : #else
1542 : : sqlite3_trace(self->db, 0, (void*)0);
1543 : : #endif
1544 : 0 : set_callback_context(&self->trace_ctx, NULL);
1545 : : }
1546 : : else {
1547 : 0 : callback_context *ctx = create_callback_context(cls, callable);
1548 [ # # ]: 0 : if (ctx == NULL) {
1549 : 0 : return NULL;
1550 : : }
1551 : : #ifdef HAVE_TRACE_V2
1552 : 0 : sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, trace_callback, ctx);
1553 : : #else
1554 : : sqlite3_trace(self->db, trace_callback, ctx);
1555 : : #endif
1556 : 0 : set_callback_context(&self->trace_ctx, ctx);
1557 : : }
1558 : :
1559 : 0 : Py_RETURN_NONE;
1560 : : }
1561 : :
1562 : : #ifdef PY_SQLITE_ENABLE_LOAD_EXTENSION
1563 : : /*[clinic input]
1564 : : _sqlite3.Connection.enable_load_extension as pysqlite_connection_enable_load_extension
1565 : :
1566 : : enable as onoff: bool
1567 : : /
1568 : :
1569 : : Enable dynamic loading of SQLite extension modules.
1570 : : [clinic start generated code]*/
1571 : :
1572 : : static PyObject *
1573 : : pysqlite_connection_enable_load_extension_impl(pysqlite_Connection *self,
1574 : : int onoff)
1575 : : /*[clinic end generated code: output=9cac37190d388baf input=2a1e87931486380f]*/
1576 : : {
1577 : : int rc;
1578 : :
1579 : : if (PySys_Audit("sqlite3.enable_load_extension",
1580 : : "OO", self, onoff ? Py_True : Py_False) < 0) {
1581 : : return NULL;
1582 : : }
1583 : :
1584 : : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1585 : : return NULL;
1586 : : }
1587 : :
1588 : : rc = sqlite3_enable_load_extension(self->db, onoff);
1589 : :
1590 : : if (rc != SQLITE_OK) {
1591 : : PyErr_SetString(self->OperationalError,
1592 : : "Error enabling load extension");
1593 : : return NULL;
1594 : : } else {
1595 : : Py_RETURN_NONE;
1596 : : }
1597 : : }
1598 : :
1599 : : /*[clinic input]
1600 : : _sqlite3.Connection.load_extension as pysqlite_connection_load_extension
1601 : :
1602 : : name as extension_name: str
1603 : : /
1604 : :
1605 : : Load SQLite extension module.
1606 : : [clinic start generated code]*/
1607 : :
1608 : : static PyObject *
1609 : : pysqlite_connection_load_extension_impl(pysqlite_Connection *self,
1610 : : const char *extension_name)
1611 : : /*[clinic end generated code: output=47eb1d7312bc97a7 input=edd507389d89d621]*/
1612 : : {
1613 : : int rc;
1614 : : char* errmsg;
1615 : :
1616 : : if (PySys_Audit("sqlite3.load_extension", "Os", self, extension_name) < 0) {
1617 : : return NULL;
1618 : : }
1619 : :
1620 : : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1621 : : return NULL;
1622 : : }
1623 : :
1624 : : rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1625 : : if (rc != 0) {
1626 : : PyErr_SetString(self->OperationalError, errmsg);
1627 : : return NULL;
1628 : : } else {
1629 : : Py_RETURN_NONE;
1630 : : }
1631 : : }
1632 : : #endif
1633 : :
1634 : 0 : int pysqlite_check_thread(pysqlite_Connection* self)
1635 : : {
1636 [ # # ]: 0 : if (self->check_same_thread) {
1637 [ # # ]: 0 : if (PyThread_get_thread_ident() != self->thread_ident) {
1638 : 0 : PyErr_Format(self->ProgrammingError,
1639 : : "SQLite objects created in a thread can only be used in that same thread. "
1640 : : "The object was created in thread id %lu and this is thread id %lu.",
1641 : : self->thread_ident, PyThread_get_thread_ident());
1642 : 0 : return 0;
1643 : : }
1644 : :
1645 : : }
1646 : 0 : return 1;
1647 : : }
1648 : :
1649 : 0 : static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
1650 : : {
1651 [ # # ]: 0 : if (!pysqlite_check_connection(self)) {
1652 : 0 : return NULL;
1653 : : }
1654 [ # # ]: 0 : if (self->isolation_level != NULL) {
1655 : 0 : return PyUnicode_FromString(self->isolation_level);
1656 : : }
1657 : 0 : Py_RETURN_NONE;
1658 : : }
1659 : :
1660 : 0 : static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
1661 : : {
1662 [ # # ]: 0 : if (!pysqlite_check_connection(self)) {
1663 : 0 : return NULL;
1664 : : }
1665 : 0 : return PyLong_FromLong(sqlite3_total_changes(self->db));
1666 : : }
1667 : :
1668 : 0 : static PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
1669 : : {
1670 [ # # ]: 0 : if (!pysqlite_check_connection(self)) {
1671 : 0 : return NULL;
1672 : : }
1673 [ # # ]: 0 : if (!sqlite3_get_autocommit(self->db)) {
1674 : 0 : Py_RETURN_TRUE;
1675 : : }
1676 : 0 : Py_RETURN_FALSE;
1677 : : }
1678 : :
1679 : : static int
1680 : 0 : pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored))
1681 : : {
1682 [ # # ]: 0 : if (isolation_level == NULL) {
1683 : 0 : PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
1684 : 0 : return -1;
1685 : : }
1686 [ # # ]: 0 : if (Py_IsNone(isolation_level)) {
1687 : 0 : self->isolation_level = NULL;
1688 : :
1689 : : // Execute a COMMIT to re-enable autocommit mode
1690 : 0 : PyObject *res = pysqlite_connection_commit_impl(self);
1691 [ # # ]: 0 : if (res == NULL) {
1692 : 0 : return -1;
1693 : : }
1694 : 0 : Py_DECREF(res);
1695 : 0 : return 0;
1696 : : }
1697 [ # # ]: 0 : if (!isolation_level_converter(isolation_level, &self->isolation_level)) {
1698 : 0 : return -1;
1699 : : }
1700 : 0 : return 0;
1701 : : }
1702 : :
1703 : : static PyObject *
1704 : 0 : pysqlite_connection_call(pysqlite_Connection *self, PyObject *args,
1705 : : PyObject *kwargs)
1706 : : {
1707 : : PyObject* sql;
1708 : : pysqlite_Statement* statement;
1709 : :
1710 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1711 : 0 : return NULL;
1712 : : }
1713 : :
1714 [ # # # # ]: 0 : if (!_PyArg_NoKeywords(MODULE_NAME ".Connection", kwargs))
1715 : 0 : return NULL;
1716 : :
1717 [ # # ]: 0 : if (!PyArg_ParseTuple(args, "U", &sql))
1718 : 0 : return NULL;
1719 : :
1720 : 0 : statement = pysqlite_statement_create(self, sql);
1721 [ # # ]: 0 : if (statement == NULL) {
1722 : 0 : return NULL;
1723 : : }
1724 : :
1725 : 0 : return (PyObject*)statement;
1726 : : }
1727 : :
1728 : : /*[clinic input]
1729 : : _sqlite3.Connection.execute as pysqlite_connection_execute
1730 : :
1731 : : sql: unicode
1732 : : parameters: object = NULL
1733 : : /
1734 : :
1735 : : Executes an SQL statement.
1736 : : [clinic start generated code]*/
1737 : :
1738 : : static PyObject *
1739 : 0 : pysqlite_connection_execute_impl(pysqlite_Connection *self, PyObject *sql,
1740 : : PyObject *parameters)
1741 : : /*[clinic end generated code: output=5be05ae01ee17ee4 input=27aa7792681ddba2]*/
1742 : : {
1743 : 0 : PyObject* result = 0;
1744 : :
1745 : 0 : PyObject *cursor = pysqlite_connection_cursor_impl(self, NULL);
1746 [ # # ]: 0 : if (!cursor) {
1747 : 0 : goto error;
1748 : : }
1749 : :
1750 : 0 : result = _pysqlite_query_execute((pysqlite_Cursor *)cursor, 0, sql, parameters);
1751 [ # # ]: 0 : if (!result) {
1752 [ # # ]: 0 : Py_CLEAR(cursor);
1753 : : }
1754 : :
1755 : 0 : error:
1756 : 0 : Py_XDECREF(result);
1757 : :
1758 : 0 : return cursor;
1759 : : }
1760 : :
1761 : : /*[clinic input]
1762 : : _sqlite3.Connection.executemany as pysqlite_connection_executemany
1763 : :
1764 : : sql: unicode
1765 : : parameters: object
1766 : : /
1767 : :
1768 : : Repeatedly executes an SQL statement.
1769 : : [clinic start generated code]*/
1770 : :
1771 : : static PyObject *
1772 : 0 : pysqlite_connection_executemany_impl(pysqlite_Connection *self,
1773 : : PyObject *sql, PyObject *parameters)
1774 : : /*[clinic end generated code: output=776cd2fd20bfe71f input=495be76551d525db]*/
1775 : : {
1776 : 0 : PyObject* result = 0;
1777 : :
1778 : 0 : PyObject *cursor = pysqlite_connection_cursor_impl(self, NULL);
1779 [ # # ]: 0 : if (!cursor) {
1780 : 0 : goto error;
1781 : : }
1782 : :
1783 : 0 : result = _pysqlite_query_execute((pysqlite_Cursor *)cursor, 1, sql, parameters);
1784 [ # # ]: 0 : if (!result) {
1785 [ # # ]: 0 : Py_CLEAR(cursor);
1786 : : }
1787 : :
1788 : 0 : error:
1789 : 0 : Py_XDECREF(result);
1790 : :
1791 : 0 : return cursor;
1792 : : }
1793 : :
1794 : : /*[clinic input]
1795 : : _sqlite3.Connection.executescript as pysqlite_connection_executescript
1796 : :
1797 : : sql_script as script_obj: object
1798 : : /
1799 : :
1800 : : Executes multiple SQL statements at once.
1801 : : [clinic start generated code]*/
1802 : :
1803 : : static PyObject *
1804 : 0 : pysqlite_connection_executescript(pysqlite_Connection *self,
1805 : : PyObject *script_obj)
1806 : : /*[clinic end generated code: output=4c4f9d77aa0ae37d input=f6e5f1ccfa313db4]*/
1807 : : {
1808 : 0 : PyObject* result = 0;
1809 : :
1810 : 0 : PyObject *cursor = pysqlite_connection_cursor_impl(self, NULL);
1811 [ # # ]: 0 : if (!cursor) {
1812 : 0 : goto error;
1813 : : }
1814 : :
1815 : 0 : PyObject *meth = self->state->str_executescript; // borrowed ref.
1816 : 0 : result = PyObject_CallMethodObjArgs(cursor, meth, script_obj, NULL);
1817 [ # # ]: 0 : if (!result) {
1818 [ # # ]: 0 : Py_CLEAR(cursor);
1819 : : }
1820 : :
1821 : 0 : error:
1822 : 0 : Py_XDECREF(result);
1823 : :
1824 : 0 : return cursor;
1825 : : }
1826 : :
1827 : : /* ------------------------- COLLATION CODE ------------------------ */
1828 : :
1829 : : static int
1830 : 0 : collation_callback(void *context, int text1_length, const void *text1_data,
1831 : : int text2_length, const void *text2_data)
1832 : : {
1833 : 0 : PyGILState_STATE gilstate = PyGILState_Ensure();
1834 : :
1835 : 0 : PyObject* string1 = 0;
1836 : 0 : PyObject* string2 = 0;
1837 : 0 : PyObject* retval = NULL;
1838 : : long longval;
1839 : 0 : int result = 0;
1840 : :
1841 : : /* This callback may be executed multiple times per sqlite3_step(). Bail if
1842 : : * the previous call failed */
1843 [ # # ]: 0 : if (PyErr_Occurred()) {
1844 : 0 : goto finally;
1845 : : }
1846 : :
1847 : 0 : string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1848 : 0 : string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
1849 : :
1850 [ # # # # ]: 0 : if (!string1 || !string2) {
1851 : 0 : goto finally; /* failed to allocate strings */
1852 : : }
1853 : :
1854 : 0 : callback_context *ctx = (callback_context *)context;
1855 : : assert(ctx != NULL);
1856 : 0 : PyObject *args[] = { NULL, string1, string2 }; // Borrowed refs.
1857 : 0 : size_t nargsf = 2 | PY_VECTORCALL_ARGUMENTS_OFFSET;
1858 : 0 : retval = PyObject_Vectorcall(ctx->callable, args + 1, nargsf, NULL);
1859 [ # # ]: 0 : if (retval == NULL) {
1860 : : /* execution failed */
1861 : 0 : goto finally;
1862 : : }
1863 : :
1864 : 0 : longval = PyLong_AsLongAndOverflow(retval, &result);
1865 [ # # # # ]: 0 : if (longval == -1 && PyErr_Occurred()) {
1866 : 0 : PyErr_Clear();
1867 : 0 : result = 0;
1868 : : }
1869 [ # # ]: 0 : else if (!result) {
1870 [ # # ]: 0 : if (longval > 0)
1871 : 0 : result = 1;
1872 [ # # ]: 0 : else if (longval < 0)
1873 : 0 : result = -1;
1874 : : }
1875 : :
1876 : 0 : finally:
1877 : 0 : Py_XDECREF(string1);
1878 : 0 : Py_XDECREF(string2);
1879 : 0 : Py_XDECREF(retval);
1880 : 0 : PyGILState_Release(gilstate);
1881 : 0 : return result;
1882 : : }
1883 : :
1884 : : /*[clinic input]
1885 : : _sqlite3.Connection.interrupt as pysqlite_connection_interrupt
1886 : :
1887 : : Abort any pending database operation.
1888 : : [clinic start generated code]*/
1889 : :
1890 : : static PyObject *
1891 : 0 : pysqlite_connection_interrupt_impl(pysqlite_Connection *self)
1892 : : /*[clinic end generated code: output=f193204bc9e70b47 input=75ad03ade7012859]*/
1893 : : {
1894 : 0 : PyObject* retval = NULL;
1895 : :
1896 [ # # ]: 0 : if (!pysqlite_check_connection(self)) {
1897 : 0 : goto finally;
1898 : : }
1899 : :
1900 : 0 : sqlite3_interrupt(self->db);
1901 : :
1902 : 0 : retval = Py_NewRef(Py_None);
1903 : :
1904 : 0 : finally:
1905 : 0 : return retval;
1906 : : }
1907 : :
1908 : : /* Function author: Paul Kippes <kippesp@gmail.com>
1909 : : * Class method of Connection to call the Python function _iterdump
1910 : : * of the sqlite3 module.
1911 : : */
1912 : : /*[clinic input]
1913 : : _sqlite3.Connection.iterdump as pysqlite_connection_iterdump
1914 : :
1915 : : Returns iterator to the dump of the database in an SQL text format.
1916 : : [clinic start generated code]*/
1917 : :
1918 : : static PyObject *
1919 : 0 : pysqlite_connection_iterdump_impl(pysqlite_Connection *self)
1920 : : /*[clinic end generated code: output=586997aaf9808768 input=1911ca756066da89]*/
1921 : : {
1922 [ # # ]: 0 : if (!pysqlite_check_connection(self)) {
1923 : 0 : return NULL;
1924 : : }
1925 : :
1926 : 0 : PyObject *iterdump = _PyImport_GetModuleAttrString(MODULE_NAME ".dump", "_iterdump");
1927 [ # # ]: 0 : if (!iterdump) {
1928 [ # # ]: 0 : if (!PyErr_Occurred()) {
1929 : 0 : PyErr_SetString(self->OperationalError,
1930 : : "Failed to obtain _iterdump() reference");
1931 : : }
1932 : 0 : return NULL;
1933 : : }
1934 : :
1935 : 0 : PyObject *retval = PyObject_CallOneArg(iterdump, (PyObject *)self);
1936 : 0 : Py_DECREF(iterdump);
1937 : 0 : return retval;
1938 : : }
1939 : :
1940 : : /*[clinic input]
1941 : : _sqlite3.Connection.backup as pysqlite_connection_backup
1942 : :
1943 : : target: object(type='pysqlite_Connection *', subclass_of='clinic_state()->ConnectionType')
1944 : : *
1945 : : pages: int = -1
1946 : : progress: object = None
1947 : : name: str = "main"
1948 : : sleep: double = 0.250
1949 : :
1950 : : Makes a backup of the database.
1951 : : [clinic start generated code]*/
1952 : :
1953 : : static PyObject *
1954 : 0 : pysqlite_connection_backup_impl(pysqlite_Connection *self,
1955 : : pysqlite_Connection *target, int pages,
1956 : : PyObject *progress, const char *name,
1957 : : double sleep)
1958 : : /*[clinic end generated code: output=306a3e6a38c36334 input=c6519d0f59d0fd7f]*/
1959 : : {
1960 : : int rc;
1961 : 0 : int sleep_ms = (int)(sleep * 1000.0);
1962 : : sqlite3 *bck_conn;
1963 : : sqlite3_backup *bck_handle;
1964 : :
1965 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1966 : 0 : return NULL;
1967 : : }
1968 : :
1969 [ # # ]: 0 : if (!pysqlite_check_connection(target)) {
1970 : 0 : return NULL;
1971 : : }
1972 : :
1973 [ # # ]: 0 : if (target == self) {
1974 : 0 : PyErr_SetString(PyExc_ValueError, "target cannot be the same connection instance");
1975 : 0 : return NULL;
1976 : : }
1977 : :
1978 : : #if SQLITE_VERSION_NUMBER < 3008008
1979 : : /* Since 3.8.8 this is already done, per commit
1980 : : https://www.sqlite.org/src/info/169b5505498c0a7e */
1981 : : if (!sqlite3_get_autocommit(target->db)) {
1982 : : PyErr_SetString(self->OperationalError, "target is in transaction");
1983 : : return NULL;
1984 : : }
1985 : : #endif
1986 : :
1987 [ # # # # ]: 0 : if (progress != Py_None && !PyCallable_Check(progress)) {
1988 : 0 : PyErr_SetString(PyExc_TypeError, "progress argument must be a callable");
1989 : 0 : return NULL;
1990 : : }
1991 : :
1992 [ # # ]: 0 : if (pages == 0) {
1993 : 0 : pages = -1;
1994 : : }
1995 : :
1996 : 0 : bck_conn = target->db;
1997 : :
1998 : 0 : Py_BEGIN_ALLOW_THREADS
1999 : 0 : bck_handle = sqlite3_backup_init(bck_conn, "main", self->db, name);
2000 : 0 : Py_END_ALLOW_THREADS
2001 : :
2002 [ # # ]: 0 : if (bck_handle == NULL) {
2003 : 0 : _pysqlite_seterror(self->state, bck_conn);
2004 : 0 : return NULL;
2005 : : }
2006 : :
2007 : : do {
2008 : 0 : Py_BEGIN_ALLOW_THREADS
2009 : 0 : rc = sqlite3_backup_step(bck_handle, pages);
2010 : 0 : Py_END_ALLOW_THREADS
2011 : :
2012 [ # # ]: 0 : if (progress != Py_None) {
2013 : 0 : int remaining = sqlite3_backup_remaining(bck_handle);
2014 : 0 : int pagecount = sqlite3_backup_pagecount(bck_handle);
2015 : 0 : PyObject *res = PyObject_CallFunction(progress, "iii", rc,
2016 : : remaining, pagecount);
2017 [ # # ]: 0 : if (res == NULL) {
2018 : : /* Callback failed: abort backup and bail. */
2019 : 0 : Py_BEGIN_ALLOW_THREADS
2020 : 0 : sqlite3_backup_finish(bck_handle);
2021 : 0 : Py_END_ALLOW_THREADS
2022 : 0 : return NULL;
2023 : : }
2024 : 0 : Py_DECREF(res);
2025 : : }
2026 : :
2027 : : /* Sleep for a while if there are still further pages to copy and
2028 : : the engine could not make any progress */
2029 [ # # # # ]: 0 : if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) {
2030 : 0 : Py_BEGIN_ALLOW_THREADS
2031 : 0 : sqlite3_sleep(sleep_ms);
2032 : 0 : Py_END_ALLOW_THREADS
2033 : : }
2034 [ # # # # : 0 : } while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);
# # ]
2035 : :
2036 : 0 : Py_BEGIN_ALLOW_THREADS
2037 : 0 : rc = sqlite3_backup_finish(bck_handle);
2038 : 0 : Py_END_ALLOW_THREADS
2039 : :
2040 [ # # ]: 0 : if (rc != SQLITE_OK) {
2041 : 0 : _pysqlite_seterror(self->state, bck_conn);
2042 : 0 : return NULL;
2043 : : }
2044 : :
2045 : 0 : Py_RETURN_NONE;
2046 : : }
2047 : :
2048 : : /*[clinic input]
2049 : : _sqlite3.Connection.create_collation as pysqlite_connection_create_collation
2050 : :
2051 : : cls: defining_class
2052 : : name: str
2053 : : callback as callable: object
2054 : : /
2055 : :
2056 : : Creates a collation function.
2057 : : [clinic start generated code]*/
2058 : :
2059 : : static PyObject *
2060 : 0 : pysqlite_connection_create_collation_impl(pysqlite_Connection *self,
2061 : : PyTypeObject *cls,
2062 : : const char *name,
2063 : : PyObject *callable)
2064 : : /*[clinic end generated code: output=32d339e97869c378 input=f67ecd2e31e61ad3]*/
2065 : : {
2066 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
2067 : 0 : return NULL;
2068 : : }
2069 : :
2070 : 0 : callback_context *ctx = NULL;
2071 : : int rc;
2072 : 0 : int flags = SQLITE_UTF8;
2073 [ # # ]: 0 : if (callable == Py_None) {
2074 : 0 : rc = sqlite3_create_collation_v2(self->db, name, flags,
2075 : : NULL, NULL, NULL);
2076 : : }
2077 : : else {
2078 [ # # ]: 0 : if (!PyCallable_Check(callable)) {
2079 : 0 : PyErr_SetString(PyExc_TypeError, "parameter must be callable");
2080 : 0 : return NULL;
2081 : : }
2082 : 0 : ctx = create_callback_context(cls, callable);
2083 [ # # ]: 0 : if (ctx == NULL) {
2084 : 0 : return NULL;
2085 : : }
2086 : 0 : rc = sqlite3_create_collation_v2(self->db, name, flags, ctx,
2087 : : &collation_callback,
2088 : : &destructor_callback);
2089 : : }
2090 : :
2091 [ # # ]: 0 : if (rc != SQLITE_OK) {
2092 : : /* Unlike other sqlite3_* functions, the destructor callback is _not_
2093 : : * called if sqlite3_create_collation_v2() fails, so we have to free
2094 : : * the context before returning.
2095 : : */
2096 [ # # ]: 0 : if (callable != Py_None) {
2097 : 0 : free_callback_context(ctx);
2098 : : }
2099 : 0 : _pysqlite_seterror(self->state, self->db);
2100 : 0 : return NULL;
2101 : : }
2102 : :
2103 : 0 : Py_RETURN_NONE;
2104 : : }
2105 : :
2106 : : #ifdef PY_SQLITE_HAVE_SERIALIZE
2107 : : /*[clinic input]
2108 : : _sqlite3.Connection.serialize as serialize
2109 : :
2110 : : *
2111 : : name: str = "main"
2112 : : Which database to serialize.
2113 : :
2114 : : Serialize a database into a byte string.
2115 : :
2116 : : For an ordinary on-disk database file, the serialization is just a copy of the
2117 : : disk file. For an in-memory database or a "temp" database, the serialization is
2118 : : the same sequence of bytes which would be written to disk if that database
2119 : : were backed up to disk.
2120 : : [clinic start generated code]*/
2121 : :
2122 : : static PyObject *
2123 : : serialize_impl(pysqlite_Connection *self, const char *name)
2124 : : /*[clinic end generated code: output=97342b0e55239dd3 input=d2eb5194a65abe2b]*/
2125 : : {
2126 : : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
2127 : : return NULL;
2128 : : }
2129 : :
2130 : : /* If SQLite has a contiguous memory representation of the database, we can
2131 : : * avoid memory allocations, so we try with the no-copy flag first.
2132 : : */
2133 : : sqlite3_int64 size;
2134 : : unsigned int flags = SQLITE_SERIALIZE_NOCOPY;
2135 : : const char *data;
2136 : :
2137 : : Py_BEGIN_ALLOW_THREADS
2138 : : data = (const char *)sqlite3_serialize(self->db, name, &size, flags);
2139 : : if (data == NULL) {
2140 : : flags &= ~SQLITE_SERIALIZE_NOCOPY;
2141 : : data = (const char *)sqlite3_serialize(self->db, name, &size, flags);
2142 : : }
2143 : : Py_END_ALLOW_THREADS
2144 : :
2145 : : if (data == NULL) {
2146 : : PyErr_Format(self->OperationalError, "unable to serialize '%s'",
2147 : : name);
2148 : : return NULL;
2149 : : }
2150 : : PyObject *res = PyBytes_FromStringAndSize(data, (Py_ssize_t)size);
2151 : : if (!(flags & SQLITE_SERIALIZE_NOCOPY)) {
2152 : : sqlite3_free((void *)data);
2153 : : }
2154 : : return res;
2155 : : }
2156 : :
2157 : : /*[clinic input]
2158 : : _sqlite3.Connection.deserialize as deserialize
2159 : :
2160 : : data: Py_buffer(accept={buffer, str})
2161 : : The serialized database content.
2162 : : /
2163 : : *
2164 : : name: str = "main"
2165 : : Which database to reopen with the deserialization.
2166 : :
2167 : : Load a serialized database.
2168 : :
2169 : : The deserialize interface causes the database connection to disconnect from the
2170 : : target database, and then reopen it as an in-memory database based on the given
2171 : : serialized data.
2172 : :
2173 : : The deserialize interface will fail with SQLITE_BUSY if the database is
2174 : : currently in a read transaction or is involved in a backup operation.
2175 : : [clinic start generated code]*/
2176 : :
2177 : : static PyObject *
2178 : : deserialize_impl(pysqlite_Connection *self, Py_buffer *data,
2179 : : const char *name)
2180 : : /*[clinic end generated code: output=e394c798b98bad89 input=1be4ca1faacf28f2]*/
2181 : : {
2182 : : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
2183 : : return NULL;
2184 : : }
2185 : :
2186 : : /* Transfer ownership of the buffer to SQLite:
2187 : : * - Move buffer from Py to SQLite
2188 : : * - Tell SQLite to free buffer memory
2189 : : * - Tell SQLite that it is permitted to grow the resulting database
2190 : : *
2191 : : * Make sure we don't overflow sqlite3_deserialize(); it accepts a signed
2192 : : * 64-bit int as its data size argument.
2193 : : *
2194 : : * We can safely use sqlite3_malloc64 here, since it was introduced before
2195 : : * the serialize APIs.
2196 : : */
2197 : : if (data->len > 9223372036854775807) { // (1 << 63) - 1
2198 : : PyErr_SetString(PyExc_OverflowError, "'data' is too large");
2199 : : return NULL;
2200 : : }
2201 : :
2202 : : sqlite3_int64 size = (sqlite3_int64)data->len;
2203 : : unsigned char *buf = sqlite3_malloc64(size);
2204 : : if (buf == NULL) {
2205 : : return PyErr_NoMemory();
2206 : : }
2207 : :
2208 : : const unsigned int flags = SQLITE_DESERIALIZE_FREEONCLOSE |
2209 : : SQLITE_DESERIALIZE_RESIZEABLE;
2210 : : int rc;
2211 : : Py_BEGIN_ALLOW_THREADS
2212 : : (void)memcpy(buf, data->buf, data->len);
2213 : : rc = sqlite3_deserialize(self->db, name, buf, size, size, flags);
2214 : : Py_END_ALLOW_THREADS
2215 : :
2216 : : if (rc != SQLITE_OK) {
2217 : : (void)_pysqlite_seterror(self->state, self->db);
2218 : : return NULL;
2219 : : }
2220 : : Py_RETURN_NONE;
2221 : : }
2222 : : #endif // PY_SQLITE_HAVE_SERIALIZE
2223 : :
2224 : :
2225 : : /*[clinic input]
2226 : : _sqlite3.Connection.__enter__ as pysqlite_connection_enter
2227 : :
2228 : : Called when the connection is used as a context manager.
2229 : :
2230 : : Returns itself as a convenience to the caller.
2231 : : [clinic start generated code]*/
2232 : :
2233 : : static PyObject *
2234 : 0 : pysqlite_connection_enter_impl(pysqlite_Connection *self)
2235 : : /*[clinic end generated code: output=457b09726d3e9dcd input=127d7a4f17e86d8f]*/
2236 : : {
2237 [ # # ]: 0 : if (!pysqlite_check_connection(self)) {
2238 : 0 : return NULL;
2239 : : }
2240 : 0 : return Py_NewRef((PyObject *)self);
2241 : : }
2242 : :
2243 : : /*[clinic input]
2244 : : _sqlite3.Connection.__exit__ as pysqlite_connection_exit
2245 : :
2246 : : type as exc_type: object
2247 : : value as exc_value: object
2248 : : traceback as exc_tb: object
2249 : : /
2250 : :
2251 : : Called when the connection is used as a context manager.
2252 : :
2253 : : If there was any exception, a rollback takes place; otherwise we commit.
2254 : : [clinic start generated code]*/
2255 : :
2256 : : static PyObject *
2257 : 0 : pysqlite_connection_exit_impl(pysqlite_Connection *self, PyObject *exc_type,
2258 : : PyObject *exc_value, PyObject *exc_tb)
2259 : : /*[clinic end generated code: output=0705200e9321202a input=bd66f1532c9c54a7]*/
2260 : : {
2261 : 0 : int commit = 0;
2262 : : PyObject* result;
2263 : :
2264 [ # # # # : 0 : if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
# # ]
2265 : 0 : commit = 1;
2266 : 0 : result = pysqlite_connection_commit_impl(self);
2267 : : }
2268 : : else {
2269 : 0 : result = pysqlite_connection_rollback_impl(self);
2270 : : }
2271 : :
2272 [ # # ]: 0 : if (result == NULL) {
2273 [ # # ]: 0 : if (commit) {
2274 : : /* Commit failed; try to rollback in order to unlock the database.
2275 : : * If rollback also fails, chain the exceptions. */
2276 : 0 : PyObject *exc = PyErr_GetRaisedException();
2277 : 0 : result = pysqlite_connection_rollback_impl(self);
2278 [ # # ]: 0 : if (result == NULL) {
2279 : 0 : _PyErr_ChainExceptions1(exc);
2280 : : }
2281 : : else {
2282 : 0 : Py_DECREF(result);
2283 : 0 : PyErr_SetRaisedException(exc);
2284 : : }
2285 : : }
2286 : 0 : return NULL;
2287 : : }
2288 : 0 : Py_DECREF(result);
2289 : :
2290 : 0 : Py_RETURN_FALSE;
2291 : : }
2292 : :
2293 : : /*[clinic input]
2294 : : _sqlite3.Connection.setlimit as setlimit
2295 : :
2296 : : category: int
2297 : : The limit category to be set.
2298 : : limit: int
2299 : : The new limit. If the new limit is a negative number, the limit is
2300 : : unchanged.
2301 : : /
2302 : :
2303 : : Set connection run-time limits.
2304 : :
2305 : : Attempts to increase a limit above its hard upper bound are silently truncated
2306 : : to the hard upper bound. Regardless of whether or not the limit was changed,
2307 : : the prior value of the limit is returned.
2308 : : [clinic start generated code]*/
2309 : :
2310 : : static PyObject *
2311 : 0 : setlimit_impl(pysqlite_Connection *self, int category, int limit)
2312 : : /*[clinic end generated code: output=0d208213f8d68ccd input=9bd469537e195635]*/
2313 : : {
2314 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
2315 : 0 : return NULL;
2316 : : }
2317 : :
2318 : 0 : int old_limit = sqlite3_limit(self->db, category, limit);
2319 [ # # ]: 0 : if (old_limit < 0) {
2320 : 0 : PyErr_SetString(self->ProgrammingError, "'category' is out of bounds");
2321 : 0 : return NULL;
2322 : : }
2323 : 0 : return PyLong_FromLong(old_limit);
2324 : : }
2325 : :
2326 : : /*[clinic input]
2327 : : _sqlite3.Connection.getlimit as getlimit
2328 : :
2329 : : category: int
2330 : : The limit category to be queried.
2331 : : /
2332 : :
2333 : : Get connection run-time limits.
2334 : : [clinic start generated code]*/
2335 : :
2336 : : static PyObject *
2337 : 0 : getlimit_impl(pysqlite_Connection *self, int category)
2338 : : /*[clinic end generated code: output=7c3f5d11f24cecb1 input=61e0849fb4fb058f]*/
2339 : : {
2340 : 0 : return setlimit_impl(self, category, -1);
2341 : : }
2342 : :
2343 : :
2344 : : static PyObject *
2345 : 0 : get_autocommit(pysqlite_Connection *self, void *Py_UNUSED(ctx))
2346 : : {
2347 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
2348 : 0 : return NULL;
2349 : : }
2350 [ # # ]: 0 : if (self->autocommit == AUTOCOMMIT_ENABLED) {
2351 : 0 : Py_RETURN_TRUE;
2352 : : }
2353 [ # # ]: 0 : if (self->autocommit == AUTOCOMMIT_DISABLED) {
2354 : 0 : Py_RETURN_FALSE;
2355 : : }
2356 : 0 : return PyLong_FromLong(LEGACY_TRANSACTION_CONTROL);
2357 : : }
2358 : :
2359 : : static int
2360 : 0 : set_autocommit(pysqlite_Connection *self, PyObject *val, void *Py_UNUSED(ctx))
2361 : : {
2362 [ # # # # ]: 0 : if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
2363 : 0 : return -1;
2364 : : }
2365 [ # # ]: 0 : if (!autocommit_converter(val, &self->autocommit)) {
2366 : 0 : return -1;
2367 : : }
2368 [ # # ]: 0 : if (self->autocommit == AUTOCOMMIT_ENABLED) {
2369 [ # # ]: 0 : if (!sqlite3_get_autocommit(self->db)) {
2370 [ # # ]: 0 : if (connection_exec_stmt(self, "COMMIT") < 0) {
2371 : 0 : return -1;
2372 : : }
2373 : : }
2374 : : }
2375 [ # # ]: 0 : else if (self->autocommit == AUTOCOMMIT_DISABLED) {
2376 [ # # ]: 0 : if (sqlite3_get_autocommit(self->db)) {
2377 [ # # ]: 0 : if (connection_exec_stmt(self, "BEGIN") < 0) {
2378 : 0 : return -1;
2379 : : }
2380 : : }
2381 : : }
2382 : 0 : return 0;
2383 : : }
2384 : :
2385 : :
2386 : : static const char connection_doc[] =
2387 : : PyDoc_STR("SQLite database connection object.");
2388 : :
2389 : : static PyGetSetDef connection_getset[] = {
2390 : : {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
2391 : : {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
2392 : : {"in_transaction", (getter)pysqlite_connection_get_in_transaction, (setter)0},
2393 : : {"autocommit", (getter)get_autocommit, (setter)set_autocommit},
2394 : : {NULL}
2395 : : };
2396 : :
2397 : : static PyMethodDef connection_methods[] = {
2398 : : PYSQLITE_CONNECTION_BACKUP_METHODDEF
2399 : : PYSQLITE_CONNECTION_CLOSE_METHODDEF
2400 : : PYSQLITE_CONNECTION_COMMIT_METHODDEF
2401 : : PYSQLITE_CONNECTION_CREATE_AGGREGATE_METHODDEF
2402 : : PYSQLITE_CONNECTION_CREATE_COLLATION_METHODDEF
2403 : : PYSQLITE_CONNECTION_CREATE_FUNCTION_METHODDEF
2404 : : PYSQLITE_CONNECTION_CURSOR_METHODDEF
2405 : : PYSQLITE_CONNECTION_ENABLE_LOAD_EXTENSION_METHODDEF
2406 : : PYSQLITE_CONNECTION_ENTER_METHODDEF
2407 : : PYSQLITE_CONNECTION_EXECUTEMANY_METHODDEF
2408 : : PYSQLITE_CONNECTION_EXECUTESCRIPT_METHODDEF
2409 : : PYSQLITE_CONNECTION_EXECUTE_METHODDEF
2410 : : PYSQLITE_CONNECTION_EXIT_METHODDEF
2411 : : PYSQLITE_CONNECTION_INTERRUPT_METHODDEF
2412 : : PYSQLITE_CONNECTION_ITERDUMP_METHODDEF
2413 : : PYSQLITE_CONNECTION_LOAD_EXTENSION_METHODDEF
2414 : : PYSQLITE_CONNECTION_ROLLBACK_METHODDEF
2415 : : PYSQLITE_CONNECTION_SET_AUTHORIZER_METHODDEF
2416 : : PYSQLITE_CONNECTION_SET_PROGRESS_HANDLER_METHODDEF
2417 : : PYSQLITE_CONNECTION_SET_TRACE_CALLBACK_METHODDEF
2418 : : SETLIMIT_METHODDEF
2419 : : GETLIMIT_METHODDEF
2420 : : SERIALIZE_METHODDEF
2421 : : DESERIALIZE_METHODDEF
2422 : : CREATE_WINDOW_FUNCTION_METHODDEF
2423 : : BLOBOPEN_METHODDEF
2424 : : {NULL, NULL}
2425 : : };
2426 : :
2427 : : static struct PyMemberDef connection_members[] =
2428 : : {
2429 : : {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
2430 : : {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
2431 : : {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
2432 : : {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
2433 : : {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
2434 : : {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
2435 : : {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
2436 : : {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
2437 : : {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
2438 : : {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
2439 : : {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
2440 : : {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
2441 : : {NULL}
2442 : : };
2443 : :
2444 : : static PyType_Slot connection_slots[] = {
2445 : : {Py_tp_dealloc, connection_dealloc},
2446 : : {Py_tp_doc, (void *)connection_doc},
2447 : : {Py_tp_methods, connection_methods},
2448 : : {Py_tp_members, connection_members},
2449 : : {Py_tp_getset, connection_getset},
2450 : : {Py_tp_init, pysqlite_connection_init},
2451 : : {Py_tp_call, pysqlite_connection_call},
2452 : : {Py_tp_traverse, connection_traverse},
2453 : : {Py_tp_clear, connection_clear},
2454 : : {0, NULL},
2455 : : };
2456 : :
2457 : : static PyType_Spec connection_spec = {
2458 : : .name = MODULE_NAME ".Connection",
2459 : : .basicsize = sizeof(pysqlite_Connection),
2460 : : .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
2461 : : Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
2462 : : .slots = connection_slots,
2463 : : };
2464 : :
2465 : : int
2466 : 1 : pysqlite_connection_setup_types(PyObject *module)
2467 : : {
2468 : 1 : PyObject *type = PyType_FromModuleAndSpec(module, &connection_spec, NULL);
2469 [ - + ]: 1 : if (type == NULL) {
2470 : 0 : return -1;
2471 : : }
2472 : 1 : pysqlite_state *state = pysqlite_get_state(module);
2473 : 1 : state->ConnectionType = (PyTypeObject *)type;
2474 : 1 : return 0;
2475 : : }
|