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