diff --git a/things/database.py b/things/database.py index 5bbd7da..e5fcce4 100755 --- a/things/database.py +++ b/things/database.py @@ -10,6 +10,7 @@ import sqlite3 from textwrap import dedent from typing import Optional, Union +import weakref # -------------------------------------------------- @@ -186,6 +187,7 @@ def __init__(self, filepath=None, print_sql=False): # See: https://sqlite.org/uri.html#recognized_query_parameters uri = f"file:{self.filepath}?mode=ro" self.connection = sqlite3.connect(uri, uri=True) # pylint: disable=E1101 + self._finalizer = weakref.finalize(self, self._close_connection) # Test for migrated database in Things 3.15.16+ # -------------------------------- @@ -510,6 +512,10 @@ def execute_query(self, sql_query, parameters=(), row_factory=None): return cursor.fetchall() + def _close_connection(self): + """Close the database connection.""" + self.connection.close() + # Helper functions