Skip to content

Commit 210a746

Browse files
committed
Close DB connection when Database is garbage collected
Register a weakref.finalize callback to close the underlying DB connection when the Database instance is garbage collected. This address a ResourceWarning which was introduced in Python 3.13 (python/cpython#105539).
1 parent a83d418 commit 210a746

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

things/database.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import sqlite3
1111
from textwrap import dedent
1212
from typing import Optional, Union
13+
import weakref
1314

1415

1516
# --------------------------------------------------
@@ -186,6 +187,7 @@ def __init__(self, filepath=None, print_sql=False):
186187
# See: https://sqlite.org/uri.html#recognized_query_parameters
187188
uri = f"file:{self.filepath}?mode=ro"
188189
self.connection = sqlite3.connect(uri, uri=True) # pylint: disable=E1101
190+
self._finalizer = weakref.finalize(self, self._close_connection)
189191

190192
# Test for migrated database in Things 3.15.16+
191193
# --------------------------------
@@ -510,6 +512,10 @@ def execute_query(self, sql_query, parameters=(), row_factory=None):
510512

511513
return cursor.fetchall()
512514

515+
def _close_connection(self):
516+
"""Close the database connection."""
517+
self.connection.close()
518+
513519

514520
# Helper functions
515521

0 commit comments

Comments
 (0)