Skip to content

Commit bec0db5

Browse files
authored
Fix: Implement Singleton pattern for DbCodeGate to prevent multiple initializations (#625)
1 parent 42ffecb commit bec0db5

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

src/codegate/db/connection.py

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,23 +32,33 @@
3232

3333

3434
class DbCodeGate:
35+
_instance = None
36+
37+
def __new__(cls, *args, **kwargs):
38+
if cls._instance is None:
39+
cls._instance = super().__new__(cls)
40+
return cls._instance
3541

3642
def __init__(self, sqlite_path: Optional[str] = None):
37-
# Initialize SQLite database engine with proper async URL
38-
if not sqlite_path:
39-
current_dir = Path(__file__).parent
40-
sqlite_path = (
41-
current_dir.parent.parent.parent / "codegate_volume" / "db" / "codegate.db"
42-
) # type: ignore
43-
self._db_path = Path(sqlite_path).absolute() # type: ignore
44-
self._db_path.parent.mkdir(parents=True, exist_ok=True)
45-
logger.debug(f"Connecting to DB from path: {self._db_path}")
46-
engine_dict = {
47-
"url": f"sqlite+aiosqlite:///{self._db_path}",
48-
"echo": False, # Set to False in production
49-
"isolation_level": "AUTOCOMMIT", # Required for SQLite
50-
}
51-
self._async_db_engine = create_async_engine(**engine_dict)
43+
if not hasattr(self, "_initialized"):
44+
# Ensure __init__ is only executed once
45+
self._initialized = True
46+
47+
# Initialize SQLite database engine with proper async URL
48+
if not sqlite_path:
49+
current_dir = Path(__file__).parent
50+
sqlite_path = (
51+
current_dir.parent.parent.parent / "codegate_volume" / "db" / "codegate.db"
52+
)
53+
self._db_path = Path(sqlite_path).absolute()
54+
self._db_path.parent.mkdir(parents=True, exist_ok=True)
55+
logger.debug(f"Connecting to DB from path: {self._db_path}")
56+
engine_dict = {
57+
"url": f"sqlite+aiosqlite:///{self._db_path}",
58+
"echo": False, # Set to False in production
59+
"isolation_level": "AUTOCOMMIT", # Required for SQLite
60+
}
61+
self._async_db_engine = create_async_engine(**engine_dict)
5262

5363
def does_db_exist(self):
5464
return self._db_path.is_file()

0 commit comments

Comments
 (0)