Skip to content

Commit a1c6ac8

Browse files
authored
fix: automatic pool cleanup at shutdown (#25)
Automatically close any open pools at shutdown
1 parent 28cfc8c commit a1c6ac8

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

sqlspec/base.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# ruff: noqa: PLR6301
2+
import atexit
3+
import contextlib
24
import re
35
from abc import ABC, abstractmethod
46
from collections.abc import Awaitable
@@ -19,6 +21,7 @@
1921
from sqlspec.exceptions import NotFoundError
2022
from sqlspec.statement import SQLStatement
2123
from sqlspec.typing import ModelDTOT, StatementParameterType
24+
from sqlspec.utils.sync_tools import maybe_async_
2225

2326
if TYPE_CHECKING:
2427
from contextlib import AbstractAsyncContextManager, AbstractContextManager
@@ -202,6 +205,15 @@ class SQLSpec:
202205

203206
def __init__(self) -> None:
204207
self._configs: dict[Any, DatabaseConfigProtocol[Any, Any, Any]] = {}
208+
# Register the cleanup handler to run at program exit
209+
atexit.register(self._cleanup_pools)
210+
211+
def _cleanup_pools(self) -> None:
212+
"""Clean up all open database pools at program exit."""
213+
for config in self._configs.values():
214+
if config.support_connection_pooling and config.pool_instance is not None:
215+
with contextlib.suppress(Exception):
216+
maybe_async_(config.close_pool)()
205217

206218
@overload
207219
def add_config(self, config: "SyncConfigT") -> "type[SyncConfigT]": ...

0 commit comments

Comments
 (0)