Skip to content

Commit bddc3d2

Browse files
committed
refactor: use lru cached engine
Use lru cached engine
1 parent 2db72d6 commit bddc3d2

1 file changed

Lines changed: 9 additions & 8 deletions

File tree

utils/core/db.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import logging
3+
from functools import lru_cache
34
from itertools import chain
45
from typing import Union, Sequence
56
from sqlalchemy.engine import Engine, URL
@@ -28,7 +29,13 @@
2829
# --- Database connection functions ---
2930

3031

31-
_engine_cache: dict[str, Engine] = {}
32+
@lru_cache
33+
def _cached_engine(url: URL) -> Engine:
34+
# URL objects hash/compare on their real fields (including password), so
35+
# caching on the URL itself is safe. str(URL) masks the password as
36+
# "***" for safe logging — passing that to create_engine() instead would
37+
# make every connection attempt authenticate with the literal "***".
38+
return create_engine(url)
3239

3340

3441
def get_engine() -> Engine:
@@ -41,13 +48,7 @@ def get_engine() -> Engine:
4148
the same process (e.g. browser vs. browser-csrf DBs) still get one
4249
engine per database instead of sharing a mismatched pool.
4350
"""
44-
url = get_connection_url()
45-
key = str(url)
46-
engine = _engine_cache.get(key)
47-
if engine is None:
48-
engine = create_engine(url)
49-
_engine_cache[key] = engine
50-
return engine
51+
return _cached_engine(get_connection_url())
5152

5253

5354
def ensure_database_exists(url: URL) -> None:

0 commit comments

Comments
 (0)