Spaces:
Runtime error
Runtime error
Download shared/database/connection.py from greenman123/2323: direct link, hf CLI and curl.
- Browser
- Download file 3.25 kB
-
https://huggingface.co/spaces/greenman123/2323/resolve/main/shared/database/connection.py
- Command line
-
hf download hf://spaces/greenman123/2323/shared/database/connection.py
-
curl -L -o connection.py https://huggingface.co/spaces/greenman123/2323/resolve/main/shared/database/connection.py
3.25 kB
| """Database connection management.""" | |
| import os | |
| from typing import Optional | |
| from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker | |
| from sqlalchemy.orm import declarative_base | |
| Base = declarative_base() | |
| class DatabaseConnection: | |
| """Manages database connections with connection pooling.""" | |
| def __init__(self, database_url: str): | |
| self.database_url = database_url | |
| self.engine = None | |
| self.session_factory = None | |
| async def connect(self): | |
| """Initialize database engine and session factory.""" | |
| # Convert database URL for async | |
| if self.database_url.startswith("postgresql://"): | |
| async_url = self.database_url.replace("postgresql://", "postgresql+asyncpg://") | |
| elif self.database_url.startswith("sqlite:///"): | |
| async_url = self.database_url.replace("sqlite:///", "sqlite+aiosqlite:///") | |
| else: | |
| async_url = self.database_url | |
| self.engine = create_async_engine( | |
| async_url, | |
| echo=False, | |
| pool_pre_ping=True, | |
| pool_size=10, | |
| max_overflow=20, | |
| ) | |
| self.session_factory = async_sessionmaker( | |
| self.engine, | |
| class_=AsyncSession, | |
| expire_on_commit=False, | |
| ) | |
| async def disconnect(self): | |
| """Close database connections.""" | |
| if self.engine: | |
| await self.engine.dispose() | |
| async def get_session(self) -> AsyncSession: | |
| """Get a database session.""" | |
| if not self.session_factory: | |
| raise RuntimeError("Database not connected") | |
| return self.session_factory() | |
| async def health_check(self) -> bool: | |
| """Check if database is accessible.""" | |
| try: | |
| session = await self.get_session() | |
| try: | |
| await session.execute("SELECT 1") | |
| return True | |
| finally: | |
| await session.close() | |
| except Exception: | |
| return False | |
| def get_db_connection() -> DatabaseConnection: | |
| """ | |
| Create database connection from environment variables. | |
| Returns: | |
| DatabaseConnection instance | |
| """ | |
| # Check for direct database URL (e.g., from Neon, Supabase, etc.) | |
| neon_url = os.getenv("NEON_DATABASE_URL") | |
| if neon_url: | |
| return DatabaseConnection(neon_url) | |
| db_type = os.getenv("DATABASE_TYPE", "sqlite") | |
| if db_type == "postgresql": | |
| host = os.getenv("POSTGRES_HOST", "localhost") | |
| port = os.getenv("POSTGRES_PORT", "5432") | |
| db = os.getenv("POSTGRES_DB", "chimera") | |
| user = os.getenv("POSTGRES_USER", "chimera") | |
| password = os.getenv("DB_PASSWORD", "") | |
| # Build URL with SSL if it's a cloud database | |
| if "neon.tech" in host or "supabase" in host or "aws" in host: | |
| database_url = f"postgresql://{user}:{password}@{host}:{port}/{db}?sslmode=require" | |
| else: | |
| database_url = f"postgresql://{user}:{password}@{host}:{port}/{db}" | |
| else: | |
| # SQLite for development | |
| database_url = "sqlite:///./chimera.db" | |
| return DatabaseConnection(database_url) | |