Spaces:
Sleeping
Sleeping
| from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase | |
| from typing import Optional | |
| import logging | |
| from .config import get_settings | |
| logger = logging.getLogger(__name__) | |
| _client: Optional[AsyncIOMotorClient] = None | |
| _db: Optional[AsyncIOMotorDatabase] = None | |
| _connection_healthy = False | |
| async def test_connection() -> bool: | |
| """Test if the database connection is healthy""" | |
| global _connection_healthy | |
| try: | |
| client = get_client() | |
| # Try to ping the database | |
| await client.admin.command('ping') | |
| _connection_healthy = True | |
| logger.info("Database connection established successfully") | |
| return True | |
| except Exception as e: | |
| _connection_healthy = False | |
| logger.warning(f"Database connection failed: {e}") | |
| return False | |
| def get_client() -> AsyncIOMotorClient: | |
| global _client | |
| if _client is None: | |
| settings = get_settings() | |
| # Use the MongoDB URI exactly as provided, without additional parameters | |
| _client = AsyncIOMotorClient(settings.mongodb_uri) | |
| return _client | |
| def get_database() -> AsyncIOMotorDatabase: | |
| global _db | |
| if _db is None: | |
| client = get_client() | |
| settings = get_settings() | |
| _db = client[settings.database_name] | |
| return _db | |
| def get_collection(name: str): | |
| db = get_database() | |
| return db[name] | |
| def is_database_available() -> bool: | |
| """Check if database is available for operations""" | |
| return _connection_healthy | |