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