Skip to content

Commit 1a1bfc2

Browse files
gh-105539: Emit ResourceWarning if sqlite3 database is not closed explicitly (#108015)
1 parent 8661751 commit 1a1bfc2

File tree

5 files changed

+30
-0
lines changed

5 files changed

+30
-0
lines changed

Doc/library/sqlite3.rst

+6
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,12 @@ Connection objects
630630
* :ref:`sqlite3-connection-shortcuts`
631631
* :ref:`sqlite3-connection-context-manager`
632632

633+
634+
.. versionchanged:: 3.13
635+
636+
A :exc:`ResourceWarning` is emitted if :meth:`close` is not called before
637+
a :class:`!Connection` object is deleted.
638+
633639
An SQLite database connection has the following attributes and methods:
634640

635641
.. method:: cursor(factory=Cursor)

Doc/whatsnew/3.13.rst

+7
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,13 @@ pathlib
158158
:meth:`~pathlib.Path.is_dir`.
159159
(Contributed by Barney Gale in :gh:`77609` and :gh:`105793`.)
160160

161+
sqlite3
162+
-------
163+
164+
* A :exc:`ResourceWarning` is now emitted if a :class:`sqlite3.Connection`
165+
object is not :meth:`closed <sqlite3.Connection.close>` explicitly.
166+
(Contributed by Erlend E. Aasland in :gh:`105539`.)
167+
161168
tkinter
162169
-------
163170

Lib/test/test_sqlite3/test_dbapi.py

+6
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,12 @@ def test_connect_positional_arguments(self):
583583
cx.close()
584584
self.assertEqual(cm.filename, __file__)
585585

586+
def test_connection_resource_warning(self):
587+
with self.assertWarns(ResourceWarning):
588+
cx = sqlite.connect(":memory:")
589+
del cx
590+
gc_collect()
591+
586592

587593
class UninitialisedConnectionTests(unittest.TestCase):
588594
def setUp(self):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:mod:`sqlite3` now emits an :exc:`ResourceWarning` if a
2+
:class:`sqlite3.Connection` object is not :meth:`closed
3+
<sqlite3.connection.close>` explicitly. Patch by Erlend E. Aasland.

Modules/_sqlite/connection.c

+8
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,14 @@ connection_finalize(PyObject *self)
493493
}
494494

495495
/* Clean up if user has not called .close() explicitly. */
496+
if (con->db) {
497+
if (PyErr_ResourceWarning(self, 1, "unclosed database in %R", self)) {
498+
/* Spurious errors can appear at shutdown */
499+
if (PyErr_ExceptionMatches(PyExc_Warning)) {
500+
PyErr_WriteUnraisable(self);
501+
}
502+
}
503+
}
496504
if (connection_close(con) < 0) {
497505
if (teardown) {
498506
PyErr_Clear();

0 commit comments

Comments
 (0)