1 /* connection.c - the connection type
2  *
3  * Copyright (C) 2004-2010 Gerhard Häring <gh@ghaering.de>
4  *
5  * This file is part of pysqlite.
6  *
7  * This software is provided 'as-is', without any express or implied
8  * warranty.  In no event will the authors be held liable for any damages
9  * arising from the use of this software.
10  *
11  * Permission is granted to anyone to use this software for any purpose,
12  * including commercial applications, and to alter it and redistribute it
13  * freely, subject to the following restrictions:
14  *
15  * 1. The origin of this software must not be misrepresented; you must not
16  *    claim that you wrote the original software. If you use this software
17  *    in a product, an acknowledgment in the product documentation would be
18  *    appreciated but is not required.
19  * 2. Altered source versions must be plainly marked as such, and must not be
20  *    misrepresented as being the original software.
21  * 3. This notice may not be removed or altered from any source distribution.
22  */
23 
24 #include "module.h"
25 #include "structmember.h"         // PyMemberDef
26 #include "connection.h"
27 #include "statement.h"
28 #include "cursor.h"
29 #include "prepare_protocol.h"
30 #include "util.h"
31 
32 #if SQLITE_VERSION_NUMBER >= 3014000
33 #define HAVE_TRACE_V2
34 #endif
35 
36 static const char *
get_isolation_level(const char * level)37 get_isolation_level(const char *level)
38 {
39     assert(level != NULL);
40     static const char *const allowed_levels[] = {
41         "",
42         "DEFERRED",
43         "IMMEDIATE",
44         "EXCLUSIVE",
45         NULL
46     };
47     for (int i = 0; allowed_levels[i] != NULL; i++) {
48         const char *candidate = allowed_levels[i];
49         if (sqlite3_stricmp(level, candidate) == 0) {
50             return candidate;
51         }
52     }
53     PyErr_SetString(PyExc_ValueError,
54                     "isolation_level string must be '', 'DEFERRED', "
55                     "'IMMEDIATE', or 'EXCLUSIVE'");
56     return NULL;
57 }
58 
59 static int
isolation_level_converter(PyObject * str_or_none,const char ** result)60 isolation_level_converter(PyObject *str_or_none, const char **result)
61 {
62     if (Py_IsNone(str_or_none)) {
63         *result = NULL;
64     }
65     else if (PyUnicode_Check(str_or_none)) {
66         Py_ssize_t sz;
67         const char *str = PyUnicode_AsUTF8AndSize(str_or_none, &sz);
68         if (str == NULL) {
69             return 0;
70         }
71         if (strlen(str) != (size_t)sz) {
72             PyErr_SetString(PyExc_ValueError, "embedded null character");
73             return 0;
74         }
75 
76         const char *level = get_isolation_level(str);
77         if (level == NULL) {
78             return 0;
79         }
80         *result = level;
81     }
82     else {
83         PyErr_SetString(PyExc_TypeError,
84                         "isolation_level must be str or None");
85         return 0;
86     }
87     return 1;
88 }
89 
90 static int
clinic_fsconverter(PyObject * pathlike,const char ** result)91 clinic_fsconverter(PyObject *pathlike, const char **result)
92 {
93     PyObject *bytes = NULL;
94     Py_ssize_t len;
95     char *str;
96 
97     if (!PyUnicode_FSConverter(pathlike, &bytes)) {
98         goto error;
99     }
100     if (PyBytes_AsStringAndSize(bytes, &str, &len) < 0) {
101         goto error;
102     }
103     if ((*result = (const char *)PyMem_Malloc(len+1)) == NULL) {
104         goto error;
105     }
106 
107     memcpy((void *)(*result), str, len+1);
108     Py_DECREF(bytes);
109     return 1;
110 
111 error:
112     Py_XDECREF(bytes);
113     return 0;
114 }
115 
116 #define clinic_state() (pysqlite_get_state_by_type(Py_TYPE(self)))
117 #include "clinic/connection.c.h"
118 #undef clinic_state
119 
120 /*[clinic input]
121 module _sqlite3
122 class _sqlite3.Connection "pysqlite_Connection *" "clinic_state()->ConnectionType"
123 [clinic start generated code]*/
124 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=67369db2faf80891]*/
125 
126 _Py_IDENTIFIER(cursor);
127 
128 static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
129 static void free_callback_context(callback_context *ctx);
130 static void set_callback_context(callback_context **ctx_pp,
131                                  callback_context *ctx);
132 static void connection_close(pysqlite_Connection *self);
133 
134 static PyObject *
new_statement_cache(pysqlite_Connection * self,pysqlite_state * state,int maxsize)135 new_statement_cache(pysqlite_Connection *self, pysqlite_state *state,
136                     int maxsize)
137 {
138     PyObject *args[] = { NULL, PyLong_FromLong(maxsize), };
139     if (args[1] == NULL) {
140         return NULL;
141     }
142     PyObject *lru_cache = state->lru_cache;
143     size_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
144     PyObject *inner = PyObject_Vectorcall(lru_cache, args + 1, nargsf, NULL);
145     Py_DECREF(args[1]);
146     if (inner == NULL) {
147         return NULL;
148     }
149 
150     args[1] = (PyObject *)self;  // Borrowed ref.
151     nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
152     PyObject *res = PyObject_Vectorcall(inner, args + 1, nargsf, NULL);
153     Py_DECREF(inner);
154     return res;
155 }
156 
157 /*[python input]
158 class FSConverter_converter(CConverter):
159     type = "const char *"
160     converter = "clinic_fsconverter"
161     def converter_init(self):
162         self.c_default = "NULL"
163     def cleanup(self):
164         return f"PyMem_Free((void *){self.name});\n"
165 
166 class IsolationLevel_converter(CConverter):
167     type = "const char *"
168     converter = "isolation_level_converter"
169 
170 [python start generated code]*/
171 /*[python end generated code: output=da39a3ee5e6b4b0d input=be142323885672ab]*/
172 
173 /*[clinic input]
174 _sqlite3.Connection.__init__ as pysqlite_connection_init
175 
176     database: FSConverter
177     timeout: double = 5.0
178     detect_types: int = 0
179     isolation_level: IsolationLevel = ""
180     check_same_thread: bool(accept={int}) = True
181     factory: object(c_default='(PyObject*)clinic_state()->ConnectionType') = ConnectionType
182     cached_statements as cache_size: int = 128
183     uri: bool = False
184 [clinic start generated code]*/
185 
186 static int
pysqlite_connection_init_impl(pysqlite_Connection * self,const char * database,double timeout,int detect_types,const char * isolation_level,int check_same_thread,PyObject * factory,int cache_size,int uri)187 pysqlite_connection_init_impl(pysqlite_Connection *self,
188                               const char *database, double timeout,
189                               int detect_types, const char *isolation_level,
190                               int check_same_thread, PyObject *factory,
191                               int cache_size, int uri)
192 /*[clinic end generated code: output=7d640ae1d83abfd4 input=342173993434ba1e]*/
193 {
194     if (PySys_Audit("sqlite3.connect", "s", database) < 0) {
195         return -1;
196     }
197 
198     if (self->initialized) {
199         PyTypeObject *tp = Py_TYPE(self);
200         tp->tp_clear((PyObject *)self);
201         connection_close(self);
202         self->initialized = 0;
203     }
204 
205     // Create and configure SQLite database object.
206     sqlite3 *db;
207     int rc;
208     Py_BEGIN_ALLOW_THREADS
209     rc = sqlite3_open_v2(database, &db,
210                          SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
211                          (uri ? SQLITE_OPEN_URI : 0), NULL);
212     if (rc == SQLITE_OK) {
213         (void)sqlite3_busy_timeout(db, (int)(timeout*1000));
214     }
215     Py_END_ALLOW_THREADS
216 
217     if (db == NULL && rc == SQLITE_NOMEM) {
218         PyErr_NoMemory();
219         return -1;
220     }
221 
222     pysqlite_state *state = pysqlite_get_state_by_type(Py_TYPE(self));
223     if (rc != SQLITE_OK) {
224         _pysqlite_seterror(state, db);
225         return -1;
226     }
227 
228     // Create LRU statement cache; returns a new reference.
229     PyObject *statement_cache = new_statement_cache(self, state, cache_size);
230     if (statement_cache == NULL) {
231         return -1;
232     }
233 
234     // Create list of weak references to cursors.
235     PyObject *cursors = PyList_New(0);
236     if (cursors == NULL) {
237         Py_DECREF(statement_cache);
238         return -1;
239     }
240 
241     // Init connection state members.
242     self->db = db;
243     self->state = state;
244     self->detect_types = detect_types;
245     self->isolation_level = isolation_level;
246     self->check_same_thread = check_same_thread;
247     self->thread_ident = PyThread_get_thread_ident();
248     self->statement_cache = statement_cache;
249     self->cursors = cursors;
250     self->created_cursors = 0;
251     self->row_factory = Py_NewRef(Py_None);
252     self->text_factory = Py_NewRef(&PyUnicode_Type);
253     self->trace_ctx = NULL;
254     self->progress_ctx = NULL;
255     self->authorizer_ctx = NULL;
256 
257     // Borrowed refs
258     self->Warning               = state->Warning;
259     self->Error                 = state->Error;
260     self->InterfaceError        = state->InterfaceError;
261     self->DatabaseError         = state->DatabaseError;
262     self->DataError             = state->DataError;
263     self->OperationalError      = state->OperationalError;
264     self->IntegrityError        = state->IntegrityError;
265     self->InternalError         = state->InternalError;
266     self->ProgrammingError      = state->ProgrammingError;
267     self->NotSupportedError     = state->NotSupportedError;
268 
269     if (PySys_Audit("sqlite3.connect/handle", "O", self) < 0) {
270         return -1;
271     }
272 
273     self->initialized = 1;
274     return 0;
275 }
276 
277 static void
pysqlite_do_all_statements(pysqlite_Connection * self)278 pysqlite_do_all_statements(pysqlite_Connection *self)
279 {
280     // Reset all statements
281     sqlite3_stmt *stmt = NULL;
282     while ((stmt = sqlite3_next_stmt(self->db, stmt))) {
283         if (sqlite3_stmt_busy(stmt)) {
284             (void)sqlite3_reset(stmt);
285         }
286     }
287 
288     // Reset all cursors
289     for (int i = 0; i < PyList_Size(self->cursors); i++) {
290         PyObject *weakref = PyList_GetItem(self->cursors, i);
291         PyObject *object = PyWeakref_GetObject(weakref);
292         if (object != Py_None) {
293             pysqlite_Cursor *cursor = (pysqlite_Cursor *)object;
294             cursor->reset = 1;
295         }
296     }
297 }
298 
299 #define VISIT_CALLBACK_CONTEXT(ctx) \
300 do {                                \
301     if (ctx) {                      \
302         Py_VISIT(ctx->callable);    \
303         Py_VISIT(ctx->module);      \
304     }                               \
305 } while (0)
306 
307 static int
connection_traverse(pysqlite_Connection * self,visitproc visit,void * arg)308 connection_traverse(pysqlite_Connection *self, visitproc visit, void *arg)
309 {
310     Py_VISIT(Py_TYPE(self));
311     Py_VISIT(self->statement_cache);
312     Py_VISIT(self->cursors);
313     Py_VISIT(self->row_factory);
314     Py_VISIT(self->text_factory);
315     VISIT_CALLBACK_CONTEXT(self->trace_ctx);
316     VISIT_CALLBACK_CONTEXT(self->progress_ctx);
317     VISIT_CALLBACK_CONTEXT(self->authorizer_ctx);
318 #undef VISIT_CALLBACK_CONTEXT
319     return 0;
320 }
321 
322 static inline void
clear_callback_context(callback_context * ctx)323 clear_callback_context(callback_context *ctx)
324 {
325     if (ctx != NULL) {
326         Py_CLEAR(ctx->callable);
327         Py_CLEAR(ctx->module);
328     }
329 }
330 
331 static int
connection_clear(pysqlite_Connection * self)332 connection_clear(pysqlite_Connection *self)
333 {
334     Py_CLEAR(self->statement_cache);
335     Py_CLEAR(self->cursors);
336     Py_CLEAR(self->row_factory);
337     Py_CLEAR(self->text_factory);
338     clear_callback_context(self->trace_ctx);
339     clear_callback_context(self->progress_ctx);
340     clear_callback_context(self->authorizer_ctx);
341     return 0;
342 }
343 
344 static void
free_callback_contexts(pysqlite_Connection * self)345 free_callback_contexts(pysqlite_Connection *self)
346 {
347     set_callback_context(&self->trace_ctx, NULL);
348     set_callback_context(&self->progress_ctx, NULL);
349     set_callback_context(&self->authorizer_ctx, NULL);
350 }
351 
352 static void
connection_close(pysqlite_Connection * self)353 connection_close(pysqlite_Connection *self)
354 {
355     if (self->db) {
356         free_callback_contexts(self);
357 
358         sqlite3 *db = self->db;
359         self->db = NULL;
360 
361         Py_BEGIN_ALLOW_THREADS
362         int rc = sqlite3_close_v2(db);
363         assert(rc == SQLITE_OK), (void)rc;
364         Py_END_ALLOW_THREADS
365     }
366 }
367 
368 static void
connection_dealloc(pysqlite_Connection * self)369 connection_dealloc(pysqlite_Connection *self)
370 {
371     PyTypeObject *tp = Py_TYPE(self);
372     PyObject_GC_UnTrack(self);
373     tp->tp_clear((PyObject *)self);
374 
375     /* Clean up if user has not called .close() explicitly. */
376     connection_close(self);
377 
378     tp->tp_free(self);
379     Py_DECREF(tp);
380 }
381 
382 /*
383  * Registers a cursor with the connection.
384  *
385  * 0 => error; 1 => ok
386  */
pysqlite_connection_register_cursor(pysqlite_Connection * connection,PyObject * cursor)387 int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
388 {
389     PyObject* weakref;
390 
391     weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
392     if (!weakref) {
393         goto error;
394     }
395 
396     if (PyList_Append(connection->cursors, weakref) != 0) {
397         Py_CLEAR(weakref);
398         goto error;
399     }
400 
401     Py_DECREF(weakref);
402 
403     return 1;
404 error:
405     return 0;
406 }
407 
408 /*[clinic input]
409 _sqlite3.Connection.cursor as pysqlite_connection_cursor
410 
411     factory: object = NULL
412 
413 Return a cursor for the connection.
414 [clinic start generated code]*/
415 
416 static PyObject *
pysqlite_connection_cursor_impl(pysqlite_Connection * self,PyObject * factory)417 pysqlite_connection_cursor_impl(pysqlite_Connection *self, PyObject *factory)
418 /*[clinic end generated code: output=562432a9e6af2aa1 input=4127345aa091b650]*/
419 {
420     PyObject* cursor;
421 
422     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
423         return NULL;
424     }
425 
426     if (factory == NULL) {
427         factory = (PyObject *)self->state->CursorType;
428     }
429 
430     cursor = PyObject_CallOneArg(factory, (PyObject *)self);
431     if (cursor == NULL)
432         return NULL;
433     if (!PyObject_TypeCheck(cursor, self->state->CursorType)) {
434         PyErr_Format(PyExc_TypeError,
435                      "factory must return a cursor, not %.100s",
436                      Py_TYPE(cursor)->tp_name);
437         Py_DECREF(cursor);
438         return NULL;
439     }
440 
441     _pysqlite_drop_unused_cursor_references(self);
442 
443     if (cursor && self->row_factory != Py_None) {
444         Py_INCREF(self->row_factory);
445         Py_XSETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory);
446     }
447 
448     return cursor;
449 }
450 
451 /*[clinic input]
452 _sqlite3.Connection.close as pysqlite_connection_close
453 
454 Closes the connection.
455 [clinic start generated code]*/
456 
457 static PyObject *
pysqlite_connection_close_impl(pysqlite_Connection * self)458 pysqlite_connection_close_impl(pysqlite_Connection *self)
459 /*[clinic end generated code: output=a546a0da212c9b97 input=3d58064bbffaa3d3]*/
460 {
461     if (!pysqlite_check_thread(self)) {
462         return NULL;
463     }
464 
465     if (!self->initialized) {
466         PyTypeObject *tp = Py_TYPE(self);
467         pysqlite_state *state = pysqlite_get_state_by_type(tp);
468         PyErr_SetString(state->ProgrammingError,
469                         "Base Connection.__init__ not called.");
470         return NULL;
471     }
472 
473     Py_CLEAR(self->statement_cache);
474     connection_close(self);
475 
476     Py_RETURN_NONE;
477 }
478 
479 /*
480  * Checks if a connection object is usable (i. e. not closed).
481  *
482  * 0 => error; 1 => ok
483  */
pysqlite_check_connection(pysqlite_Connection * con)484 int pysqlite_check_connection(pysqlite_Connection* con)
485 {
486     if (!con->initialized) {
487         pysqlite_state *state = pysqlite_get_state_by_type(Py_TYPE(con));
488         PyErr_SetString(state->ProgrammingError,
489                         "Base Connection.__init__ not called.");
490         return 0;
491     }
492 
493     if (!con->db) {
494         PyErr_SetString(con->state->ProgrammingError,
495                         "Cannot operate on a closed database.");
496         return 0;
497     } else {
498         return 1;
499     }
500 }
501 
502 /*[clinic input]
503 _sqlite3.Connection.commit as pysqlite_connection_commit
504 
505 Commit the current transaction.
506 [clinic start generated code]*/
507 
508 static PyObject *
pysqlite_connection_commit_impl(pysqlite_Connection * self)509 pysqlite_connection_commit_impl(pysqlite_Connection *self)
510 /*[clinic end generated code: output=3da45579e89407f2 input=39c12c04dda276a8]*/
511 {
512     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
513         return NULL;
514     }
515 
516     if (!sqlite3_get_autocommit(self->db)) {
517         int rc;
518 
519         Py_BEGIN_ALLOW_THREADS
520         sqlite3_stmt *statement;
521         rc = sqlite3_prepare_v2(self->db, "COMMIT", 7, &statement, NULL);
522         if (rc == SQLITE_OK) {
523             (void)sqlite3_step(statement);
524             rc = sqlite3_finalize(statement);
525         }
526         Py_END_ALLOW_THREADS
527 
528         if (rc != SQLITE_OK) {
529             (void)_pysqlite_seterror(self->state, self->db);
530             return NULL;
531         }
532     }
533 
534     Py_RETURN_NONE;
535 }
536 
537 /*[clinic input]
538 _sqlite3.Connection.rollback as pysqlite_connection_rollback
539 
540 Roll back the current transaction.
541 [clinic start generated code]*/
542 
543 static PyObject *
pysqlite_connection_rollback_impl(pysqlite_Connection * self)544 pysqlite_connection_rollback_impl(pysqlite_Connection *self)
545 /*[clinic end generated code: output=b66fa0d43e7ef305 input=12d4e8d068942830]*/
546 {
547     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
548         return NULL;
549     }
550 
551     if (!sqlite3_get_autocommit(self->db)) {
552         pysqlite_do_all_statements(self);
553 
554         int rc;
555 
556         Py_BEGIN_ALLOW_THREADS
557         sqlite3_stmt *statement;
558         rc = sqlite3_prepare_v2(self->db, "ROLLBACK", 9, &statement, NULL);
559         if (rc == SQLITE_OK) {
560             (void)sqlite3_step(statement);
561             rc = sqlite3_finalize(statement);
562         }
563         Py_END_ALLOW_THREADS
564 
565         if (rc != SQLITE_OK) {
566             (void)_pysqlite_seterror(self->state, self->db);
567             return NULL;
568         }
569 
570     }
571 
572     Py_RETURN_NONE;
573 }
574 
575 static int
_pysqlite_set_result(sqlite3_context * context,PyObject * py_val)576 _pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
577 {
578     if (py_val == Py_None) {
579         sqlite3_result_null(context);
580     } else if (PyLong_Check(py_val)) {
581         sqlite_int64 value = _pysqlite_long_as_int64(py_val);
582         if (value == -1 && PyErr_Occurred())
583             return -1;
584         sqlite3_result_int64(context, value);
585     } else if (PyFloat_Check(py_val)) {
586         sqlite3_result_double(context, PyFloat_AsDouble(py_val));
587     } else if (PyUnicode_Check(py_val)) {
588         Py_ssize_t sz;
589         const char *str = PyUnicode_AsUTF8AndSize(py_val, &sz);
590         if (str == NULL) {
591             return -1;
592         }
593         if (sz > INT_MAX) {
594             PyErr_SetString(PyExc_OverflowError,
595                             "string is longer than INT_MAX bytes");
596             return -1;
597         }
598         sqlite3_result_text(context, str, (int)sz, SQLITE_TRANSIENT);
599     } else if (PyObject_CheckBuffer(py_val)) {
600         Py_buffer view;
601         if (PyObject_GetBuffer(py_val, &view, PyBUF_SIMPLE) != 0) {
602             PyErr_SetString(PyExc_ValueError,
603                             "could not convert BLOB to buffer");
604             return -1;
605         }
606         if (view.len > INT_MAX) {
607             PyErr_SetString(PyExc_OverflowError,
608                             "BLOB longer than INT_MAX bytes");
609             PyBuffer_Release(&view);
610             return -1;
611         }
612         sqlite3_result_blob(context, view.buf, (int)view.len, SQLITE_TRANSIENT);
613         PyBuffer_Release(&view);
614     } else {
615         return -1;
616     }
617     return 0;
618 }
619 
620 static PyObject *
_pysqlite_build_py_params(sqlite3_context * context,int argc,sqlite3_value ** argv)621 _pysqlite_build_py_params(sqlite3_context *context, int argc,
622                           sqlite3_value **argv)
623 {
624     PyObject* args;
625     int i;
626     sqlite3_value* cur_value;
627     PyObject* cur_py_value;
628 
629     args = PyTuple_New(argc);
630     if (!args) {
631         return NULL;
632     }
633 
634     for (i = 0; i < argc; i++) {
635         cur_value = argv[i];
636         switch (sqlite3_value_type(argv[i])) {
637             case SQLITE_INTEGER:
638                 cur_py_value = PyLong_FromLongLong(sqlite3_value_int64(cur_value));
639                 break;
640             case SQLITE_FLOAT:
641                 cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
642                 break;
643             case SQLITE_TEXT: {
644                 sqlite3 *db = sqlite3_context_db_handle(context);
645                 const char *text = (const char *)sqlite3_value_text(cur_value);
646 
647                 if (text == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
648                     PyErr_NoMemory();
649                     goto error;
650                 }
651 
652                 Py_ssize_t size = sqlite3_value_bytes(cur_value);
653                 cur_py_value = PyUnicode_FromStringAndSize(text, size);
654                 break;
655             }
656             case SQLITE_BLOB: {
657                 sqlite3 *db = sqlite3_context_db_handle(context);
658                 const void *blob = sqlite3_value_blob(cur_value);
659 
660                 if (blob == NULL && sqlite3_errcode(db) == SQLITE_NOMEM) {
661                     PyErr_NoMemory();
662                     goto error;
663                 }
664 
665                 Py_ssize_t size = sqlite3_value_bytes(cur_value);
666                 cur_py_value = PyBytes_FromStringAndSize(blob, size);
667                 break;
668             }
669             case SQLITE_NULL:
670             default:
671                 cur_py_value = Py_NewRef(Py_None);
672         }
673 
674         if (!cur_py_value) {
675             goto error;
676         }
677 
678         PyTuple_SET_ITEM(args, i, cur_py_value);
679     }
680 
681     return args;
682 
683 error:
684     Py_DECREF(args);
685     return NULL;
686 }
687 
688 static void
print_or_clear_traceback(callback_context * ctx)689 print_or_clear_traceback(callback_context *ctx)
690 {
691     assert(ctx != NULL);
692     assert(ctx->state != NULL);
693     if (ctx->state->enable_callback_tracebacks) {
694         PyErr_WriteUnraisable(ctx->callable);
695     }
696     else {
697         PyErr_Clear();
698     }
699 }
700 
701 // Checks the Python exception and sets the appropriate SQLite error code.
702 static void
set_sqlite_error(sqlite3_context * context,const char * msg)703 set_sqlite_error(sqlite3_context *context, const char *msg)
704 {
705     assert(PyErr_Occurred());
706     if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
707         sqlite3_result_error_nomem(context);
708     }
709     else if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
710         sqlite3_result_error_toobig(context);
711     }
712     else {
713         sqlite3_result_error(context, msg, -1);
714     }
715     callback_context *ctx = (callback_context *)sqlite3_user_data(context);
716     print_or_clear_traceback(ctx);
717 }
718 
719 static void
func_callback(sqlite3_context * context,int argc,sqlite3_value ** argv)720 func_callback(sqlite3_context *context, int argc, sqlite3_value **argv)
721 {
722     PyGILState_STATE threadstate = PyGILState_Ensure();
723 
724     PyObject* args;
725     PyObject* py_retval = NULL;
726     int ok;
727 
728     args = _pysqlite_build_py_params(context, argc, argv);
729     if (args) {
730         callback_context *ctx = (callback_context *)sqlite3_user_data(context);
731         assert(ctx != NULL);
732         py_retval = PyObject_CallObject(ctx->callable, args);
733         Py_DECREF(args);
734     }
735 
736     ok = 0;
737     if (py_retval) {
738         ok = _pysqlite_set_result(context, py_retval) == 0;
739         Py_DECREF(py_retval);
740     }
741     if (!ok) {
742         set_sqlite_error(context, "user-defined function raised exception");
743     }
744 
745     PyGILState_Release(threadstate);
746 }
747 
748 static void
step_callback(sqlite3_context * context,int argc,sqlite3_value ** params)749 step_callback(sqlite3_context *context, int argc, sqlite3_value **params)
750 {
751     PyGILState_STATE threadstate = PyGILState_Ensure();
752 
753     PyObject* args;
754     PyObject* function_result = NULL;
755     PyObject** aggregate_instance;
756     PyObject* stepmethod = NULL;
757 
758     aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
759 
760     if (*aggregate_instance == NULL) {
761         callback_context *ctx = (callback_context *)sqlite3_user_data(context);
762         assert(ctx != NULL);
763         *aggregate_instance = PyObject_CallNoArgs(ctx->callable);
764         if (!*aggregate_instance) {
765             set_sqlite_error(context,
766                     "user-defined aggregate's '__init__' method raised error");
767             goto error;
768         }
769     }
770 
771     stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
772     if (!stepmethod) {
773         goto error;
774     }
775 
776     args = _pysqlite_build_py_params(context, argc, params);
777     if (!args) {
778         goto error;
779     }
780 
781     function_result = PyObject_CallObject(stepmethod, args);
782     Py_DECREF(args);
783 
784     if (!function_result) {
785         set_sqlite_error(context,
786                 "user-defined aggregate's 'step' method raised error");
787     }
788 
789 error:
790     Py_XDECREF(stepmethod);
791     Py_XDECREF(function_result);
792 
793     PyGILState_Release(threadstate);
794 }
795 
796 static void
final_callback(sqlite3_context * context)797 final_callback(sqlite3_context *context)
798 {
799     PyGILState_STATE threadstate = PyGILState_Ensure();
800 
801     PyObject* function_result;
802     PyObject** aggregate_instance;
803     _Py_IDENTIFIER(finalize);
804     int ok;
805     PyObject *exception, *value, *tb;
806 
807     aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, 0);
808     if (aggregate_instance == NULL) {
809         /* No rows matched the query; the step handler was never called. */
810         goto error;
811     }
812     else if (!*aggregate_instance) {
813         /* this branch is executed if there was an exception in the aggregate's
814          * __init__ */
815 
816         goto error;
817     }
818 
819     /* Keep the exception (if any) of the last call to step() */
820     PyErr_Fetch(&exception, &value, &tb);
821 
822     function_result = _PyObject_CallMethodIdNoArgs(*aggregate_instance, &PyId_finalize);
823 
824     Py_DECREF(*aggregate_instance);
825 
826     ok = 0;
827     if (function_result) {
828         ok = _pysqlite_set_result(context, function_result) == 0;
829         Py_DECREF(function_result);
830     }
831     if (!ok) {
832         set_sqlite_error(context,
833                 "user-defined aggregate's 'finalize' method raised error");
834     }
835 
836     /* Restore the exception (if any) of the last call to step(),
837        but clear also the current exception if finalize() failed */
838     PyErr_Restore(exception, value, tb);
839 
840 error:
841     PyGILState_Release(threadstate);
842 }
843 
_pysqlite_drop_unused_cursor_references(pysqlite_Connection * self)844 static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
845 {
846     PyObject* new_list;
847     PyObject* weakref;
848     int i;
849 
850     /* we only need to do this once in a while */
851     if (self->created_cursors++ < 200) {
852         return;
853     }
854 
855     self->created_cursors = 0;
856 
857     new_list = PyList_New(0);
858     if (!new_list) {
859         return;
860     }
861 
862     for (i = 0; i < PyList_Size(self->cursors); i++) {
863         weakref = PyList_GetItem(self->cursors, i);
864         if (PyWeakref_GetObject(weakref) != Py_None) {
865             if (PyList_Append(new_list, weakref) != 0) {
866                 Py_DECREF(new_list);
867                 return;
868             }
869         }
870     }
871 
872     Py_SETREF(self->cursors, new_list);
873 }
874 
875 /* Allocate a UDF/callback context structure. In order to ensure that the state
876  * pointer always outlives the callback context, we make sure it owns a
877  * reference to the module itself. create_callback_context() is always called
878  * from connection methods, so we use the defining class to fetch the module
879  * pointer.
880  */
881 static callback_context *
create_callback_context(PyTypeObject * cls,PyObject * callable)882 create_callback_context(PyTypeObject *cls, PyObject *callable)
883 {
884     callback_context *ctx = PyMem_Malloc(sizeof(callback_context));
885     if (ctx != NULL) {
886         PyObject *module = PyType_GetModule(cls);
887         ctx->callable = Py_NewRef(callable);
888         ctx->module = Py_NewRef(module);
889         ctx->state = pysqlite_get_state(module);
890     }
891     return ctx;
892 }
893 
894 static void
free_callback_context(callback_context * ctx)895 free_callback_context(callback_context *ctx)
896 {
897     assert(ctx != NULL);
898     Py_XDECREF(ctx->callable);
899     Py_XDECREF(ctx->module);
900     PyMem_Free(ctx);
901 }
902 
903 static void
set_callback_context(callback_context ** ctx_pp,callback_context * ctx)904 set_callback_context(callback_context **ctx_pp, callback_context *ctx)
905 {
906     assert(ctx_pp != NULL);
907     callback_context *tmp = *ctx_pp;
908     *ctx_pp = ctx;
909     if (tmp != NULL) {
910         free_callback_context(tmp);
911     }
912 }
913 
914 static void
destructor_callback(void * ctx)915 destructor_callback(void *ctx)
916 {
917     if (ctx != NULL) {
918         // This function may be called without the GIL held, so we need to
919         // ensure that we destroy 'ctx' with the GIL held.
920         PyGILState_STATE gstate = PyGILState_Ensure();
921         free_callback_context((callback_context *)ctx);
922         PyGILState_Release(gstate);
923     }
924 }
925 
926 /*[clinic input]
927 _sqlite3.Connection.create_function as pysqlite_connection_create_function
928 
929     cls: defining_class
930     /
931     name: str
932     narg: int
933     func: object
934     *
935     deterministic: bool = False
936 
937 Creates a new function. Non-standard.
938 [clinic start generated code]*/
939 
940 static PyObject *
pysqlite_connection_create_function_impl(pysqlite_Connection * self,PyTypeObject * cls,const char * name,int narg,PyObject * func,int deterministic)941 pysqlite_connection_create_function_impl(pysqlite_Connection *self,
942                                          PyTypeObject *cls, const char *name,
943                                          int narg, PyObject *func,
944                                          int deterministic)
945 /*[clinic end generated code: output=8a811529287ad240 input=f0f99754bfeafd8d]*/
946 {
947     int rc;
948     int flags = SQLITE_UTF8;
949 
950     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
951         return NULL;
952     }
953 
954     if (deterministic) {
955 #if SQLITE_VERSION_NUMBER < 3008003
956         PyErr_SetString(self->NotSupportedError,
957                         "deterministic=True requires SQLite 3.8.3 or higher");
958         return NULL;
959 #else
960         if (sqlite3_libversion_number() < 3008003) {
961             PyErr_SetString(self->NotSupportedError,
962                             "deterministic=True requires SQLite 3.8.3 or higher");
963             return NULL;
964         }
965         flags |= SQLITE_DETERMINISTIC;
966 #endif
967     }
968     callback_context *ctx = create_callback_context(cls, func);
969     if (ctx == NULL) {
970         return NULL;
971     }
972     rc = sqlite3_create_function_v2(self->db, name, narg, flags, ctx,
973                                     func_callback,
974                                     NULL,
975                                     NULL,
976                                     &destructor_callback);  // will decref func
977 
978     if (rc != SQLITE_OK) {
979         /* Workaround for SQLite bug: no error code or string is available here */
980         PyErr_SetString(self->OperationalError, "Error creating function");
981         return NULL;
982     }
983     Py_RETURN_NONE;
984 }
985 
986 /*[clinic input]
987 _sqlite3.Connection.create_aggregate as pysqlite_connection_create_aggregate
988 
989     cls: defining_class
990     /
991     name: str
992     n_arg: int
993     aggregate_class: object
994 
995 Creates a new aggregate. Non-standard.
996 [clinic start generated code]*/
997 
998 static PyObject *
pysqlite_connection_create_aggregate_impl(pysqlite_Connection * self,PyTypeObject * cls,const char * name,int n_arg,PyObject * aggregate_class)999 pysqlite_connection_create_aggregate_impl(pysqlite_Connection *self,
1000                                           PyTypeObject *cls,
1001                                           const char *name, int n_arg,
1002                                           PyObject *aggregate_class)
1003 /*[clinic end generated code: output=1b02d0f0aec7ff96 input=bd527067e6c2e33f]*/
1004 {
1005     int rc;
1006 
1007     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1008         return NULL;
1009     }
1010 
1011     callback_context *ctx = create_callback_context(cls, aggregate_class);
1012     if (ctx == NULL) {
1013         return NULL;
1014     }
1015     rc = sqlite3_create_function_v2(self->db, name, n_arg, SQLITE_UTF8, ctx,
1016                                     0,
1017                                     &step_callback,
1018                                     &final_callback,
1019                                     &destructor_callback); // will decref func
1020     if (rc != SQLITE_OK) {
1021         /* Workaround for SQLite bug: no error code or string is available here */
1022         PyErr_SetString(self->OperationalError, "Error creating aggregate");
1023         return NULL;
1024     }
1025     Py_RETURN_NONE;
1026 }
1027 
1028 static int
authorizer_callback(void * ctx,int action,const char * arg1,const char * arg2,const char * dbname,const char * access_attempt_source)1029 authorizer_callback(void *ctx, int action, const char *arg1,
1030                     const char *arg2 , const char *dbname,
1031                     const char *access_attempt_source)
1032 {
1033     PyGILState_STATE gilstate = PyGILState_Ensure();
1034 
1035     PyObject *ret;
1036     int rc = SQLITE_DENY;
1037 
1038     assert(ctx != NULL);
1039     PyObject *callable = ((callback_context *)ctx)->callable;
1040     ret = PyObject_CallFunction(callable, "issss", action, arg1, arg2, dbname,
1041                                 access_attempt_source);
1042 
1043     if (ret == NULL) {
1044         print_or_clear_traceback(ctx);
1045         rc = SQLITE_DENY;
1046     }
1047     else {
1048         if (PyLong_Check(ret)) {
1049             rc = _PyLong_AsInt(ret);
1050             if (rc == -1 && PyErr_Occurred()) {
1051                 print_or_clear_traceback(ctx);
1052                 rc = SQLITE_DENY;
1053             }
1054         }
1055         else {
1056             rc = SQLITE_DENY;
1057         }
1058         Py_DECREF(ret);
1059     }
1060 
1061     PyGILState_Release(gilstate);
1062     return rc;
1063 }
1064 
1065 static int
progress_callback(void * ctx)1066 progress_callback(void *ctx)
1067 {
1068     PyGILState_STATE gilstate = PyGILState_Ensure();
1069 
1070     int rc;
1071     PyObject *ret;
1072 
1073     assert(ctx != NULL);
1074     PyObject *callable = ((callback_context *)ctx)->callable;
1075     ret = PyObject_CallNoArgs(callable);
1076     if (!ret) {
1077         /* abort query if error occurred */
1078         rc = -1;
1079     }
1080     else {
1081         rc = PyObject_IsTrue(ret);
1082         Py_DECREF(ret);
1083     }
1084     if (rc < 0) {
1085         print_or_clear_traceback(ctx);
1086     }
1087 
1088     PyGILState_Release(gilstate);
1089     return rc;
1090 }
1091 
1092 #ifdef HAVE_TRACE_V2
1093 /*
1094  * From https://sqlite.org/c3ref/trace_v2.html:
1095  * The integer return value from the callback is currently ignored, though this
1096  * may change in future releases. Callback implementations should return zero
1097  * to ensure future compatibility.
1098  */
1099 static int
trace_callback(unsigned int type,void * ctx,void * prepared_statement,void * statement_string)1100 trace_callback(unsigned int type, void *ctx, void *prepared_statement,
1101                void *statement_string)
1102 #else
1103 static void
1104 trace_callback(void *ctx, const char *statement_string)
1105 #endif
1106 {
1107 #ifdef HAVE_TRACE_V2
1108     if (type != SQLITE_TRACE_STMT) {
1109         return 0;
1110     }
1111 #endif
1112 
1113     PyGILState_STATE gilstate = PyGILState_Ensure();
1114 
1115     PyObject *py_statement = NULL;
1116     PyObject *ret = NULL;
1117     py_statement = PyUnicode_DecodeUTF8(statement_string,
1118             strlen(statement_string), "replace");
1119     assert(ctx != NULL);
1120     if (py_statement) {
1121         PyObject *callable = ((callback_context *)ctx)->callable;
1122         ret = PyObject_CallOneArg(callable, py_statement);
1123         Py_DECREF(py_statement);
1124     }
1125 
1126     if (ret) {
1127         Py_DECREF(ret);
1128     }
1129     else {
1130         print_or_clear_traceback(ctx);
1131     }
1132 
1133     PyGILState_Release(gilstate);
1134 #ifdef HAVE_TRACE_V2
1135     return 0;
1136 #endif
1137 }
1138 
1139 /*[clinic input]
1140 _sqlite3.Connection.set_authorizer as pysqlite_connection_set_authorizer
1141 
1142     cls: defining_class
1143     /
1144     authorizer_callback as callable: object
1145 
1146 Sets authorizer callback. Non-standard.
1147 [clinic start generated code]*/
1148 
1149 static PyObject *
pysqlite_connection_set_authorizer_impl(pysqlite_Connection * self,PyTypeObject * cls,PyObject * callable)1150 pysqlite_connection_set_authorizer_impl(pysqlite_Connection *self,
1151                                         PyTypeObject *cls,
1152                                         PyObject *callable)
1153 /*[clinic end generated code: output=75fa60114fc971c3 input=9f3e90d3d642c4a0]*/
1154 {
1155     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1156         return NULL;
1157     }
1158 
1159     int rc;
1160     if (callable == Py_None) {
1161         rc = sqlite3_set_authorizer(self->db, NULL, NULL);
1162         set_callback_context(&self->authorizer_ctx, NULL);
1163     }
1164     else {
1165         callback_context *ctx = create_callback_context(cls, callable);
1166         if (ctx == NULL) {
1167             return NULL;
1168         }
1169         rc = sqlite3_set_authorizer(self->db, authorizer_callback, ctx);
1170         set_callback_context(&self->authorizer_ctx, ctx);
1171     }
1172     if (rc != SQLITE_OK) {
1173         PyErr_SetString(self->OperationalError,
1174                         "Error setting authorizer callback");
1175         set_callback_context(&self->authorizer_ctx, NULL);
1176         return NULL;
1177     }
1178     Py_RETURN_NONE;
1179 }
1180 
1181 /*[clinic input]
1182 _sqlite3.Connection.set_progress_handler as pysqlite_connection_set_progress_handler
1183 
1184     cls: defining_class
1185     /
1186     progress_handler as callable: object
1187     n: int
1188 
1189 Sets progress handler callback. Non-standard.
1190 [clinic start generated code]*/
1191 
1192 static PyObject *
pysqlite_connection_set_progress_handler_impl(pysqlite_Connection * self,PyTypeObject * cls,PyObject * callable,int n)1193 pysqlite_connection_set_progress_handler_impl(pysqlite_Connection *self,
1194                                               PyTypeObject *cls,
1195                                               PyObject *callable, int n)
1196 /*[clinic end generated code: output=0739957fd8034a50 input=83e8dcbb4ce183f7]*/
1197 {
1198     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1199         return NULL;
1200     }
1201 
1202     if (callable == Py_None) {
1203         /* None clears the progress handler previously set */
1204         sqlite3_progress_handler(self->db, 0, 0, (void*)0);
1205         set_callback_context(&self->progress_ctx, NULL);
1206     }
1207     else {
1208         callback_context *ctx = create_callback_context(cls, callable);
1209         if (ctx == NULL) {
1210             return NULL;
1211         }
1212         sqlite3_progress_handler(self->db, n, progress_callback, ctx);
1213         set_callback_context(&self->progress_ctx, ctx);
1214     }
1215     Py_RETURN_NONE;
1216 }
1217 
1218 /*[clinic input]
1219 _sqlite3.Connection.set_trace_callback as pysqlite_connection_set_trace_callback
1220 
1221     cls: defining_class
1222     /
1223     trace_callback as callable: object
1224 
1225 Sets a trace callback called for each SQL statement (passed as unicode).
1226 
1227 Non-standard.
1228 [clinic start generated code]*/
1229 
1230 static PyObject *
pysqlite_connection_set_trace_callback_impl(pysqlite_Connection * self,PyTypeObject * cls,PyObject * callable)1231 pysqlite_connection_set_trace_callback_impl(pysqlite_Connection *self,
1232                                             PyTypeObject *cls,
1233                                             PyObject *callable)
1234 /*[clinic end generated code: output=d91048c03bfcee05 input=96f03acec3ec8044]*/
1235 {
1236     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1237         return NULL;
1238     }
1239 
1240     if (callable == Py_None) {
1241         /*
1242          * None clears the trace callback previously set
1243          *
1244          * Ref.
1245          * - https://sqlite.org/c3ref/c_trace.html
1246          * - https://sqlite.org/c3ref/trace_v2.html
1247          */
1248 #ifdef HAVE_TRACE_V2
1249         sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, 0, 0);
1250 #else
1251         sqlite3_trace(self->db, 0, (void*)0);
1252 #endif
1253         set_callback_context(&self->trace_ctx, NULL);
1254     }
1255     else {
1256         callback_context *ctx = create_callback_context(cls, callable);
1257         if (ctx == NULL) {
1258             return NULL;
1259         }
1260 #ifdef HAVE_TRACE_V2
1261         sqlite3_trace_v2(self->db, SQLITE_TRACE_STMT, trace_callback, ctx);
1262 #else
1263         sqlite3_trace(self->db, trace_callback, ctx);
1264 #endif
1265         set_callback_context(&self->trace_ctx, ctx);
1266     }
1267 
1268     Py_RETURN_NONE;
1269 }
1270 
1271 #ifdef PY_SQLITE_ENABLE_LOAD_EXTENSION
1272 /*[clinic input]
1273 _sqlite3.Connection.enable_load_extension as pysqlite_connection_enable_load_extension
1274 
1275     enable as onoff: bool(accept={int})
1276     /
1277 
1278 Enable dynamic loading of SQLite extension modules. Non-standard.
1279 [clinic start generated code]*/
1280 
1281 static PyObject *
pysqlite_connection_enable_load_extension_impl(pysqlite_Connection * self,int onoff)1282 pysqlite_connection_enable_load_extension_impl(pysqlite_Connection *self,
1283                                                int onoff)
1284 /*[clinic end generated code: output=9cac37190d388baf input=5c0da5b121121cbc]*/
1285 {
1286     int rc;
1287 
1288     if (PySys_Audit("sqlite3.enable_load_extension",
1289                     "OO", self, onoff ? Py_True : Py_False) < 0) {
1290         return NULL;
1291     }
1292 
1293     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1294         return NULL;
1295     }
1296 
1297     rc = sqlite3_enable_load_extension(self->db, onoff);
1298 
1299     if (rc != SQLITE_OK) {
1300         PyErr_SetString(self->OperationalError,
1301                         "Error enabling load extension");
1302         return NULL;
1303     } else {
1304         Py_RETURN_NONE;
1305     }
1306 }
1307 
1308 /*[clinic input]
1309 _sqlite3.Connection.load_extension as pysqlite_connection_load_extension
1310 
1311     name as extension_name: str
1312     /
1313 
1314 Load SQLite extension module. Non-standard.
1315 [clinic start generated code]*/
1316 
1317 static PyObject *
pysqlite_connection_load_extension_impl(pysqlite_Connection * self,const char * extension_name)1318 pysqlite_connection_load_extension_impl(pysqlite_Connection *self,
1319                                         const char *extension_name)
1320 /*[clinic end generated code: output=47eb1d7312bc97a7 input=0b711574560db9fc]*/
1321 {
1322     int rc;
1323     char* errmsg;
1324 
1325     if (PySys_Audit("sqlite3.load_extension", "Os", self, extension_name) < 0) {
1326         return NULL;
1327     }
1328 
1329     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1330         return NULL;
1331     }
1332 
1333     rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
1334     if (rc != 0) {
1335         PyErr_SetString(self->OperationalError, errmsg);
1336         return NULL;
1337     } else {
1338         Py_RETURN_NONE;
1339     }
1340 }
1341 #endif
1342 
pysqlite_check_thread(pysqlite_Connection * self)1343 int pysqlite_check_thread(pysqlite_Connection* self)
1344 {
1345     if (self->check_same_thread) {
1346         if (PyThread_get_thread_ident() != self->thread_ident) {
1347             PyErr_Format(self->ProgrammingError,
1348                         "SQLite objects created in a thread can only be used in that same thread. "
1349                         "The object was created in thread id %lu and this is thread id %lu.",
1350                         self->thread_ident, PyThread_get_thread_ident());
1351             return 0;
1352         }
1353 
1354     }
1355     return 1;
1356 }
1357 
pysqlite_connection_get_isolation_level(pysqlite_Connection * self,void * unused)1358 static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
1359 {
1360     if (!pysqlite_check_connection(self)) {
1361         return NULL;
1362     }
1363     if (self->isolation_level != NULL) {
1364         return PyUnicode_FromString(self->isolation_level);
1365     }
1366     Py_RETURN_NONE;
1367 }
1368 
pysqlite_connection_get_total_changes(pysqlite_Connection * self,void * unused)1369 static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
1370 {
1371     if (!pysqlite_check_connection(self)) {
1372         return NULL;
1373     } else {
1374         return Py_BuildValue("i", sqlite3_total_changes(self->db));
1375     }
1376 }
1377 
pysqlite_connection_get_in_transaction(pysqlite_Connection * self,void * unused)1378 static PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
1379 {
1380     if (!pysqlite_check_connection(self)) {
1381         return NULL;
1382     }
1383     if (!sqlite3_get_autocommit(self->db)) {
1384         Py_RETURN_TRUE;
1385     }
1386     Py_RETURN_FALSE;
1387 }
1388 
1389 static int
pysqlite_connection_set_isolation_level(pysqlite_Connection * self,PyObject * isolation_level,void * Py_UNUSED (ignored))1390 pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored))
1391 {
1392     if (isolation_level == NULL) {
1393         PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
1394         return -1;
1395     }
1396     if (Py_IsNone(isolation_level)) {
1397         self->isolation_level = NULL;
1398 
1399         // Execute a COMMIT to re-enable autocommit mode
1400         PyObject *res = pysqlite_connection_commit_impl(self);
1401         if (res == NULL) {
1402             return -1;
1403         }
1404         Py_DECREF(res);
1405         return 0;
1406     }
1407     if (!isolation_level_converter(isolation_level, &self->isolation_level)) {
1408         return -1;
1409     }
1410     return 0;
1411 }
1412 
1413 static PyObject *
pysqlite_connection_call(pysqlite_Connection * self,PyObject * args,PyObject * kwargs)1414 pysqlite_connection_call(pysqlite_Connection *self, PyObject *args,
1415                          PyObject *kwargs)
1416 {
1417     PyObject* sql;
1418     pysqlite_Statement* statement;
1419 
1420     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1421         return NULL;
1422     }
1423 
1424     if (!_PyArg_NoKeywords(MODULE_NAME ".Connection", kwargs))
1425         return NULL;
1426 
1427     if (!PyArg_ParseTuple(args, "U", &sql))
1428         return NULL;
1429 
1430     statement = pysqlite_statement_create(self, sql);
1431     if (statement == NULL) {
1432         return NULL;
1433     }
1434 
1435     return (PyObject*)statement;
1436 }
1437 
1438 /*[clinic input]
1439 _sqlite3.Connection.execute as pysqlite_connection_execute
1440 
1441     sql: unicode
1442     parameters: object = NULL
1443     /
1444 
1445 Executes a SQL statement. Non-standard.
1446 [clinic start generated code]*/
1447 
1448 static PyObject *
pysqlite_connection_execute_impl(pysqlite_Connection * self,PyObject * sql,PyObject * parameters)1449 pysqlite_connection_execute_impl(pysqlite_Connection *self, PyObject *sql,
1450                                  PyObject *parameters)
1451 /*[clinic end generated code: output=5be05ae01ee17ee4 input=fbd17c75c7140271]*/
1452 {
1453     _Py_IDENTIFIER(execute);
1454     PyObject* cursor = 0;
1455     PyObject* result = 0;
1456 
1457     cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
1458     if (!cursor) {
1459         goto error;
1460     }
1461 
1462     result = _PyObject_CallMethodIdObjArgs(cursor, &PyId_execute, sql, parameters, NULL);
1463     if (!result) {
1464         Py_CLEAR(cursor);
1465     }
1466 
1467 error:
1468     Py_XDECREF(result);
1469 
1470     return cursor;
1471 }
1472 
1473 /*[clinic input]
1474 _sqlite3.Connection.executemany as pysqlite_connection_executemany
1475 
1476     sql: unicode
1477     parameters: object
1478     /
1479 
1480 Repeatedly executes a SQL statement. Non-standard.
1481 [clinic start generated code]*/
1482 
1483 static PyObject *
pysqlite_connection_executemany_impl(pysqlite_Connection * self,PyObject * sql,PyObject * parameters)1484 pysqlite_connection_executemany_impl(pysqlite_Connection *self,
1485                                      PyObject *sql, PyObject *parameters)
1486 /*[clinic end generated code: output=776cd2fd20bfe71f input=4feab80659ffc82b]*/
1487 {
1488     _Py_IDENTIFIER(executemany);
1489     PyObject* cursor = 0;
1490     PyObject* result = 0;
1491 
1492     cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
1493     if (!cursor) {
1494         goto error;
1495     }
1496 
1497     result = _PyObject_CallMethodIdObjArgs(cursor, &PyId_executemany, sql,
1498                                            parameters, NULL);
1499     if (!result) {
1500         Py_CLEAR(cursor);
1501     }
1502 
1503 error:
1504     Py_XDECREF(result);
1505 
1506     return cursor;
1507 }
1508 
1509 /*[clinic input]
1510 _sqlite3.Connection.executescript as pysqlite_connection_executescript
1511 
1512     sql_script as script_obj: object
1513     /
1514 
1515 Executes multiple SQL statements at once. Non-standard.
1516 [clinic start generated code]*/
1517 
1518 static PyObject *
pysqlite_connection_executescript(pysqlite_Connection * self,PyObject * script_obj)1519 pysqlite_connection_executescript(pysqlite_Connection *self,
1520                                   PyObject *script_obj)
1521 /*[clinic end generated code: output=4c4f9d77aa0ae37d input=b27ae5c24ffb8b43]*/
1522 {
1523     _Py_IDENTIFIER(executescript);
1524     PyObject* cursor = 0;
1525     PyObject* result = 0;
1526 
1527     cursor = _PyObject_CallMethodIdNoArgs((PyObject*)self, &PyId_cursor);
1528     if (!cursor) {
1529         goto error;
1530     }
1531 
1532     result = _PyObject_CallMethodIdObjArgs(cursor, &PyId_executescript,
1533                                            script_obj, NULL);
1534     if (!result) {
1535         Py_CLEAR(cursor);
1536     }
1537 
1538 error:
1539     Py_XDECREF(result);
1540 
1541     return cursor;
1542 }
1543 
1544 /* ------------------------- COLLATION CODE ------------------------ */
1545 
1546 static int
collation_callback(void * context,int text1_length,const void * text1_data,int text2_length,const void * text2_data)1547 collation_callback(void *context, int text1_length, const void *text1_data,
1548                    int text2_length, const void *text2_data)
1549 {
1550     PyGILState_STATE gilstate = PyGILState_Ensure();
1551 
1552     PyObject* string1 = 0;
1553     PyObject* string2 = 0;
1554     PyObject* retval = NULL;
1555     long longval;
1556     int result = 0;
1557 
1558     /* This callback may be executed multiple times per sqlite3_step(). Bail if
1559      * the previous call failed */
1560     if (PyErr_Occurred()) {
1561         goto finally;
1562     }
1563 
1564     string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
1565     string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
1566 
1567     if (!string1 || !string2) {
1568         goto finally; /* failed to allocate strings */
1569     }
1570 
1571     callback_context *ctx = (callback_context *)context;
1572     assert(ctx != NULL);
1573     PyObject *args[] = { NULL, string1, string2 };  // Borrowed refs.
1574     size_t nargsf = 2 | PY_VECTORCALL_ARGUMENTS_OFFSET;
1575     retval = PyObject_Vectorcall(ctx->callable, args + 1, nargsf, NULL);
1576     if (retval == NULL) {
1577         /* execution failed */
1578         goto finally;
1579     }
1580 
1581     longval = PyLong_AsLongAndOverflow(retval, &result);
1582     if (longval == -1 && PyErr_Occurred()) {
1583         PyErr_Clear();
1584         result = 0;
1585     }
1586     else if (!result) {
1587         if (longval > 0)
1588             result = 1;
1589         else if (longval < 0)
1590             result = -1;
1591     }
1592 
1593 finally:
1594     Py_XDECREF(string1);
1595     Py_XDECREF(string2);
1596     Py_XDECREF(retval);
1597     PyGILState_Release(gilstate);
1598     return result;
1599 }
1600 
1601 /*[clinic input]
1602 _sqlite3.Connection.interrupt as pysqlite_connection_interrupt
1603 
1604 Abort any pending database operation. Non-standard.
1605 [clinic start generated code]*/
1606 
1607 static PyObject *
pysqlite_connection_interrupt_impl(pysqlite_Connection * self)1608 pysqlite_connection_interrupt_impl(pysqlite_Connection *self)
1609 /*[clinic end generated code: output=f193204bc9e70b47 input=4bd0ad083cf93aa7]*/
1610 {
1611     PyObject* retval = NULL;
1612 
1613     if (!pysqlite_check_connection(self)) {
1614         goto finally;
1615     }
1616 
1617     sqlite3_interrupt(self->db);
1618 
1619     retval = Py_NewRef(Py_None);
1620 
1621 finally:
1622     return retval;
1623 }
1624 
1625 /* Function author: Paul Kippes <kippesp@gmail.com>
1626  * Class method of Connection to call the Python function _iterdump
1627  * of the sqlite3 module.
1628  */
1629 /*[clinic input]
1630 _sqlite3.Connection.iterdump as pysqlite_connection_iterdump
1631 
1632 Returns iterator to the dump of the database in an SQL text format.
1633 
1634 Non-standard.
1635 [clinic start generated code]*/
1636 
1637 static PyObject *
pysqlite_connection_iterdump_impl(pysqlite_Connection * self)1638 pysqlite_connection_iterdump_impl(pysqlite_Connection *self)
1639 /*[clinic end generated code: output=586997aaf9808768 input=53bc907cb5eedb85]*/
1640 {
1641     _Py_IDENTIFIER(_iterdump);
1642     PyObject* retval = NULL;
1643     PyObject* module = NULL;
1644     PyObject* module_dict;
1645     PyObject* pyfn_iterdump;
1646 
1647     if (!pysqlite_check_connection(self)) {
1648         goto finally;
1649     }
1650 
1651     module = PyImport_ImportModule(MODULE_NAME ".dump");
1652     if (!module) {
1653         goto finally;
1654     }
1655 
1656     module_dict = PyModule_GetDict(module);
1657     if (!module_dict) {
1658         goto finally;
1659     }
1660 
1661     pyfn_iterdump = _PyDict_GetItemIdWithError(module_dict, &PyId__iterdump);
1662     if (!pyfn_iterdump) {
1663         if (!PyErr_Occurred()) {
1664             PyErr_SetString(self->OperationalError,
1665                             "Failed to obtain _iterdump() reference");
1666         }
1667         goto finally;
1668     }
1669 
1670     retval = PyObject_CallOneArg(pyfn_iterdump, (PyObject *)self);
1671 
1672 finally:
1673     Py_XDECREF(module);
1674     return retval;
1675 }
1676 
1677 /*[clinic input]
1678 _sqlite3.Connection.backup as pysqlite_connection_backup
1679 
1680     target: object(type='pysqlite_Connection *', subclass_of='clinic_state()->ConnectionType')
1681     *
1682     pages: int = -1
1683     progress: object = None
1684     name: str = "main"
1685     sleep: double = 0.250
1686 
1687 Makes a backup of the database. Non-standard.
1688 [clinic start generated code]*/
1689 
1690 static PyObject *
pysqlite_connection_backup_impl(pysqlite_Connection * self,pysqlite_Connection * target,int pages,PyObject * progress,const char * name,double sleep)1691 pysqlite_connection_backup_impl(pysqlite_Connection *self,
1692                                 pysqlite_Connection *target, int pages,
1693                                 PyObject *progress, const char *name,
1694                                 double sleep)
1695 /*[clinic end generated code: output=306a3e6a38c36334 input=c759627ab1ad46ff]*/
1696 {
1697     int rc;
1698     int sleep_ms = (int)(sleep * 1000.0);
1699     sqlite3 *bck_conn;
1700     sqlite3_backup *bck_handle;
1701 
1702     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1703         return NULL;
1704     }
1705 
1706     if (!pysqlite_check_connection(target)) {
1707         return NULL;
1708     }
1709 
1710     if (target == self) {
1711         PyErr_SetString(PyExc_ValueError, "target cannot be the same connection instance");
1712         return NULL;
1713     }
1714 
1715 #if SQLITE_VERSION_NUMBER < 3008008
1716     /* Since 3.8.8 this is already done, per commit
1717        https://www.sqlite.org/src/info/169b5505498c0a7e */
1718     if (!sqlite3_get_autocommit(target->db)) {
1719         PyErr_SetString(self->OperationalError, "target is in transaction");
1720         return NULL;
1721     }
1722 #endif
1723 
1724     if (progress != Py_None && !PyCallable_Check(progress)) {
1725         PyErr_SetString(PyExc_TypeError, "progress argument must be a callable");
1726         return NULL;
1727     }
1728 
1729     if (pages == 0) {
1730         pages = -1;
1731     }
1732 
1733     bck_conn = target->db;
1734 
1735     Py_BEGIN_ALLOW_THREADS
1736     bck_handle = sqlite3_backup_init(bck_conn, "main", self->db, name);
1737     Py_END_ALLOW_THREADS
1738 
1739     if (bck_handle == NULL) {
1740         _pysqlite_seterror(self->state, bck_conn);
1741         return NULL;
1742     }
1743 
1744     do {
1745         Py_BEGIN_ALLOW_THREADS
1746         rc = sqlite3_backup_step(bck_handle, pages);
1747         Py_END_ALLOW_THREADS
1748 
1749         if (progress != Py_None) {
1750             int remaining = sqlite3_backup_remaining(bck_handle);
1751             int pagecount = sqlite3_backup_pagecount(bck_handle);
1752             PyObject *res = PyObject_CallFunction(progress, "iii", rc,
1753                                                   remaining, pagecount);
1754             if (res == NULL) {
1755                 /* Callback failed: abort backup and bail. */
1756                 Py_BEGIN_ALLOW_THREADS
1757                 sqlite3_backup_finish(bck_handle);
1758                 Py_END_ALLOW_THREADS
1759                 return NULL;
1760             }
1761             Py_DECREF(res);
1762         }
1763 
1764         /* Sleep for a while if there are still further pages to copy and
1765            the engine could not make any progress */
1766         if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) {
1767             Py_BEGIN_ALLOW_THREADS
1768             sqlite3_sleep(sleep_ms);
1769             Py_END_ALLOW_THREADS
1770         }
1771     } while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);
1772 
1773     Py_BEGIN_ALLOW_THREADS
1774     rc = sqlite3_backup_finish(bck_handle);
1775     Py_END_ALLOW_THREADS
1776 
1777     if (rc != SQLITE_OK) {
1778         _pysqlite_seterror(self->state, bck_conn);
1779         return NULL;
1780     }
1781 
1782     Py_RETURN_NONE;
1783 }
1784 
1785 /*[clinic input]
1786 _sqlite3.Connection.create_collation as pysqlite_connection_create_collation
1787 
1788     cls: defining_class
1789     name: str
1790     callback as callable: object
1791     /
1792 
1793 Creates a collation function. Non-standard.
1794 [clinic start generated code]*/
1795 
1796 static PyObject *
pysqlite_connection_create_collation_impl(pysqlite_Connection * self,PyTypeObject * cls,const char * name,PyObject * callable)1797 pysqlite_connection_create_collation_impl(pysqlite_Connection *self,
1798                                           PyTypeObject *cls,
1799                                           const char *name,
1800                                           PyObject *callable)
1801 /*[clinic end generated code: output=32d339e97869c378 input=fee2c8e5708602ad]*/
1802 {
1803     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1804         return NULL;
1805     }
1806 
1807     callback_context *ctx = NULL;
1808     int rc;
1809     int flags = SQLITE_UTF8;
1810     if (callable == Py_None) {
1811         rc = sqlite3_create_collation_v2(self->db, name, flags,
1812                                          NULL, NULL, NULL);
1813     }
1814     else {
1815         if (!PyCallable_Check(callable)) {
1816             PyErr_SetString(PyExc_TypeError, "parameter must be callable");
1817             return NULL;
1818         }
1819         ctx = create_callback_context(cls, callable);
1820         if (ctx == NULL) {
1821             return NULL;
1822         }
1823         rc = sqlite3_create_collation_v2(self->db, name, flags, ctx,
1824                                          &collation_callback,
1825                                          &destructor_callback);
1826     }
1827 
1828     if (rc != SQLITE_OK) {
1829         /* Unlike other sqlite3_* functions, the destructor callback is _not_
1830          * called if sqlite3_create_collation_v2() fails, so we have to free
1831          * the context before returning.
1832          */
1833         if (callable != Py_None) {
1834             free_callback_context(ctx);
1835         }
1836         _pysqlite_seterror(self->state, self->db);
1837         return NULL;
1838     }
1839 
1840     Py_RETURN_NONE;
1841 }
1842 
1843 /*[clinic input]
1844 _sqlite3.Connection.__enter__ as pysqlite_connection_enter
1845 
1846 Called when the connection is used as a context manager.
1847 
1848 Returns itself as a convenience to the caller.
1849 [clinic start generated code]*/
1850 
1851 static PyObject *
pysqlite_connection_enter_impl(pysqlite_Connection * self)1852 pysqlite_connection_enter_impl(pysqlite_Connection *self)
1853 /*[clinic end generated code: output=457b09726d3e9dcd input=127d7a4f17e86d8f]*/
1854 {
1855     if (!pysqlite_check_connection(self)) {
1856         return NULL;
1857     }
1858     return Py_NewRef((PyObject *)self);
1859 }
1860 
1861 /*[clinic input]
1862 _sqlite3.Connection.__exit__ as pysqlite_connection_exit
1863 
1864     type as exc_type: object
1865     value as exc_value: object
1866     traceback as exc_tb: object
1867     /
1868 
1869 Called when the connection is used as a context manager.
1870 
1871 If there was any exception, a rollback takes place; otherwise we commit.
1872 [clinic start generated code]*/
1873 
1874 static PyObject *
pysqlite_connection_exit_impl(pysqlite_Connection * self,PyObject * exc_type,PyObject * exc_value,PyObject * exc_tb)1875 pysqlite_connection_exit_impl(pysqlite_Connection *self, PyObject *exc_type,
1876                               PyObject *exc_value, PyObject *exc_tb)
1877 /*[clinic end generated code: output=0705200e9321202a input=bd66f1532c9c54a7]*/
1878 {
1879     int commit = 0;
1880     PyObject* result;
1881 
1882     if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
1883         commit = 1;
1884         result = pysqlite_connection_commit_impl(self);
1885     }
1886     else {
1887         result = pysqlite_connection_rollback_impl(self);
1888     }
1889 
1890     if (result == NULL) {
1891         if (commit) {
1892             /* Commit failed; try to rollback in order to unlock the database.
1893              * If rollback also fails, chain the exceptions. */
1894             PyObject *exc, *val, *tb;
1895             PyErr_Fetch(&exc, &val, &tb);
1896             result = pysqlite_connection_rollback_impl(self);
1897             if (result == NULL) {
1898                 _PyErr_ChainExceptions(exc, val, tb);
1899             }
1900             else {
1901                 Py_DECREF(result);
1902                 PyErr_Restore(exc, val, tb);
1903             }
1904         }
1905         return NULL;
1906     }
1907     Py_DECREF(result);
1908 
1909     Py_RETURN_FALSE;
1910 }
1911 
1912 /*[clinic input]
1913 _sqlite3.Connection.setlimit as setlimit
1914 
1915     category: int
1916         The limit category to be set.
1917     limit: int
1918         The new limit. If the new limit is a negative number, the limit is
1919         unchanged.
1920     /
1921 
1922 Set connection run-time limits.
1923 
1924 Attempts to increase a limit above its hard upper bound are silently truncated
1925 to the hard upper bound. Regardless of whether or not the limit was changed,
1926 the prior value of the limit is returned.
1927 [clinic start generated code]*/
1928 
1929 static PyObject *
setlimit_impl(pysqlite_Connection * self,int category,int limit)1930 setlimit_impl(pysqlite_Connection *self, int category, int limit)
1931 /*[clinic end generated code: output=0d208213f8d68ccd input=9bd469537e195635]*/
1932 {
1933     if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
1934         return NULL;
1935     }
1936 
1937     int old_limit = sqlite3_limit(self->db, category, limit);
1938     if (old_limit < 0) {
1939         PyErr_SetString(self->ProgrammingError, "'category' is out of bounds");
1940         return NULL;
1941     }
1942     return PyLong_FromLong(old_limit);
1943 }
1944 
1945 /*[clinic input]
1946 _sqlite3.Connection.getlimit as getlimit
1947 
1948     category: int
1949         The limit category to be queried.
1950     /
1951 
1952 Get connection run-time limits.
1953 [clinic start generated code]*/
1954 
1955 static PyObject *
getlimit_impl(pysqlite_Connection * self,int category)1956 getlimit_impl(pysqlite_Connection *self, int category)
1957 /*[clinic end generated code: output=7c3f5d11f24cecb1 input=61e0849fb4fb058f]*/
1958 {
1959     return setlimit_impl(self, category, -1);
1960 }
1961 
1962 
1963 static const char connection_doc[] =
1964 PyDoc_STR("SQLite database connection object.");
1965 
1966 static PyGetSetDef connection_getset[] = {
1967     {"isolation_level",  (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
1968     {"total_changes",  (getter)pysqlite_connection_get_total_changes, (setter)0},
1969     {"in_transaction",  (getter)pysqlite_connection_get_in_transaction, (setter)0},
1970     {NULL}
1971 };
1972 
1973 static PyMethodDef connection_methods[] = {
1974     PYSQLITE_CONNECTION_BACKUP_METHODDEF
1975     PYSQLITE_CONNECTION_CLOSE_METHODDEF
1976     PYSQLITE_CONNECTION_COMMIT_METHODDEF
1977     PYSQLITE_CONNECTION_CREATE_AGGREGATE_METHODDEF
1978     PYSQLITE_CONNECTION_CREATE_COLLATION_METHODDEF
1979     PYSQLITE_CONNECTION_CREATE_FUNCTION_METHODDEF
1980     PYSQLITE_CONNECTION_CURSOR_METHODDEF
1981     PYSQLITE_CONNECTION_ENABLE_LOAD_EXTENSION_METHODDEF
1982     PYSQLITE_CONNECTION_ENTER_METHODDEF
1983     PYSQLITE_CONNECTION_EXECUTEMANY_METHODDEF
1984     PYSQLITE_CONNECTION_EXECUTESCRIPT_METHODDEF
1985     PYSQLITE_CONNECTION_EXECUTE_METHODDEF
1986     PYSQLITE_CONNECTION_EXIT_METHODDEF
1987     PYSQLITE_CONNECTION_INTERRUPT_METHODDEF
1988     PYSQLITE_CONNECTION_ITERDUMP_METHODDEF
1989     PYSQLITE_CONNECTION_LOAD_EXTENSION_METHODDEF
1990     PYSQLITE_CONNECTION_ROLLBACK_METHODDEF
1991     PYSQLITE_CONNECTION_SET_AUTHORIZER_METHODDEF
1992     PYSQLITE_CONNECTION_SET_PROGRESS_HANDLER_METHODDEF
1993     PYSQLITE_CONNECTION_SET_TRACE_CALLBACK_METHODDEF
1994     SETLIMIT_METHODDEF
1995     GETLIMIT_METHODDEF
1996     {NULL, NULL}
1997 };
1998 
1999 static struct PyMemberDef connection_members[] =
2000 {
2001     {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
2002     {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
2003     {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
2004     {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
2005     {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
2006     {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
2007     {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
2008     {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
2009     {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
2010     {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
2011     {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
2012     {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
2013     {NULL}
2014 };
2015 
2016 static PyType_Slot connection_slots[] = {
2017     {Py_tp_dealloc, connection_dealloc},
2018     {Py_tp_doc, (void *)connection_doc},
2019     {Py_tp_methods, connection_methods},
2020     {Py_tp_members, connection_members},
2021     {Py_tp_getset, connection_getset},
2022     {Py_tp_init, pysqlite_connection_init},
2023     {Py_tp_call, pysqlite_connection_call},
2024     {Py_tp_traverse, connection_traverse},
2025     {Py_tp_clear, connection_clear},
2026     {0, NULL},
2027 };
2028 
2029 static PyType_Spec connection_spec = {
2030     .name = MODULE_NAME ".Connection",
2031     .basicsize = sizeof(pysqlite_Connection),
2032     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
2033               Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
2034     .slots = connection_slots,
2035 };
2036 
2037 int
pysqlite_connection_setup_types(PyObject * module)2038 pysqlite_connection_setup_types(PyObject *module)
2039 {
2040     PyObject *type = PyType_FromModuleAndSpec(module, &connection_spec, NULL);
2041     if (type == NULL) {
2042         return -1;
2043     }
2044     pysqlite_state *state = pysqlite_get_state(module);
2045     state->ConnectionType = (PyTypeObject *)type;
2046     return 0;
2047 }
2048