Debian Codegraph @

Modules/_sqlite/connection.c

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