diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index 80ad026..b8e8d4b 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -336,6 +336,10 @@ class Database: self._registered_functions: set = set() self.use_counts_table = use_counts_table + def close(self): + "Close the SQLite connection, and the underlying database file" + self.conn.close() + @contextlib.contextmanager def tracer(self, tracer: Callable = None): """ diff --git a/tests/test_constructor.py b/tests/test_constructor.py index d8c8d72..8743911 100644 --- a/tests/test_constructor.py +++ b/tests/test_constructor.py @@ -1,4 +1,6 @@ from sqlite_utils import Database +from sqlite_utils.utils import sqlite3 +import pytest def test_recursive_triggers(): @@ -25,3 +27,15 @@ def test_sqlite_version(): as_string = ".".join(map(str, version)) actual = next(db.query("select sqlite_version() as v"))["v"] assert actual == as_string + + +@pytest.mark.parametrize("memory", [True, False]) +def test_database_close(tmpdir, memory): + if memory: + db = Database(memory=True) + else: + db = Database(str(tmpdir / "test.db")) + assert db.execute("select 1 + 1").fetchone()[0] == 2 + db.close() + with pytest.raises(sqlite3.ProgrammingError): + db.execute("select 1 + 1")