diff --git a/sqlit/domains/shell/app/main.py b/sqlit/domains/shell/app/main.py index 2f85d91b..241d14b9 100644 --- a/sqlit/domains/shell/app/main.py +++ b/sqlit/domains/shell/app/main.py @@ -1231,6 +1231,29 @@ def on_unmount(self) -> None: close_worker = getattr(self, "_close_process_worker_client", None) if callable(close_worker): close_worker() + self._close_connections_on_exit() + + def _close_connections_on_exit(self) -> None: + """Close open database connections synchronously before the process exits. + + Leaving them to the interpreter's atexit handlers makes some drivers + (e.g. snowflake-connector-python) emit a FutureWarning about connections + not being explicitly closed. + """ + session = getattr(self, "_session", None) + self._session = None + if session is not None: + try: + session.close() + except Exception: + pass + executor = getattr(self, "_transaction_executor", None) + self._transaction_executor = None + if executor is not None: + try: + executor.close() + except Exception: + pass def _startup_stamp(self, name: str) -> None: if not self._startup_profile: diff --git a/tests/ui/test_close_connections_on_exit.py b/tests/ui/test_close_connections_on_exit.py new file mode 100644 index 00000000..62f35f8d --- /dev/null +++ b/tests/ui/test_close_connections_on_exit.py @@ -0,0 +1,38 @@ +"""Open database connections are closed explicitly when the app exits.""" + +from __future__ import annotations + +import pytest + +from sqlit.domains.shell.app.main import SSMSTUI + +from .mocks import MockConnectionStore, MockSettingsStore, build_test_services + + +class _Closable: + def __init__(self) -> None: + self.close_calls = 0 + + def close(self) -> None: + self.close_calls += 1 + + +@pytest.mark.asyncio +async def test_exit_closes_session_and_transaction_executor() -> None: + services = build_test_services( + connection_store=MockConnectionStore(), + settings_store=MockSettingsStore({}), + ) + app = SSMSTUI(services=services) + session = _Closable() + executor = _Closable() + + async with app.run_test() as pilot: + app._session = session + app._transaction_executor = executor + await pilot.pause() + + assert session.close_calls == 1 + assert executor.close_calls == 1 + assert app._session is None + assert app._transaction_executor is None