From dee457e30d6a56cc11a577d99d3cb5893c536b41 Mon Sep 17 00:00:00 2001 From: Matt Hutton Date: Sun, 23 Feb 2025 11:30:15 +1300 Subject: [PATCH] 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 (https://github.com/python/cpython/issues/105539). --- things/database.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/things/database.py b/things/database.py index 5bbd7da..406b28c 100755 --- a/things/database.py +++ b/things/database.py @@ -8,6 +8,7 @@ import plistlib import re import sqlite3 +import weakref from textwrap import dedent from typing import Optional, Union @@ -186,6 +187,8 @@ 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 + # Close the underlying SQLite connection when this Database object is garbage collected + weakref.finalize(self, sqlite3.Connection.close, self.connection) # Test for migrated database in Things 3.15.16+ # --------------------------------