Skip to content

Commit

Permalink
close db connections
Browse files Browse the repository at this point in the history
  • Loading branch information
callebtc committed Jul 7, 2024
1 parent 915c2d1 commit bb1168b
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions cashu/core/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from loguru import logger
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
from sqlalchemy.pool import NullPool, QueuePool
from sqlalchemy.pool import NullPool

from cashu.core.settings import settings

Expand Down Expand Up @@ -162,10 +162,6 @@ def _parse_timestamp(value, _):
kwargs = {}
if not settings.db_connection_pool:
kwargs["poolclass"] = NullPool
else:
kwargs["poolclass"] = QueuePool
kwargs["pool_size"] = 10
kwargs["max_overflow"] = 20

self.engine = create_async_engine(database_uri, **kwargs)

Expand Down Expand Up @@ -216,10 +212,12 @@ async def connect(
lock_timeout: Optional[float] = None,
):
connection: Optional[AsyncConnection] = None
inherited = True

if self._connection is None:
await self.initialize_connection()
assert self._connection is not None, "Connection not initialized"
inherited = False

# if connection is in transaction, create a new connection
if self._connection.in_transaction():
Expand Down Expand Up @@ -269,6 +267,11 @@ def _is_lock_exception(e):
await _handle_lock_retry(retry_delay, timeout, start_time)
else:
raise e
finally:
if not inherited:
logger.trace("Closing connection")
await connection.close()
self._connection = None
raise Exception(
f"failed to acquire database lock on {lock_table} after {timeout}s and {trial} trials ({random_int})"
)
Expand Down

0 comments on commit bb1168b

Please sign in to comment.