Download src/shared/db.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 17.8 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/shared/db.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/shared/db.py
-
curl -L -o db.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/shared/db.py
17.8 kB
| """ | |
| YAZ Care Platform - Unified Database Management | |
| Consolidated database engine, sessions, and connection handling | |
| """ | |
| from collections.abc import AsyncGenerator, Generator | |
| from contextlib import asynccontextmanager, contextmanager | |
| from typing import Any | |
| import structlog | |
| from redis.asyncio import ConnectionPool, Redis | |
| from sqlalchemy import Engine, MetaData, create_engine, event, text | |
| from sqlalchemy.ext.asyncio import ( | |
| AsyncEngine, | |
| AsyncSession, | |
| async_sessionmaker, | |
| create_async_engine, | |
| ) | |
| from sqlalchemy.orm import Session, sessionmaker | |
| from sqlalchemy.pool import QueuePool, StaticPool | |
| from .models.base import Base # Import from base.py for consistency | |
| from .settings import get_settings | |
| logger = structlog.get_logger(__name__) | |
| # Global instances | |
| metadata = MetaData() | |
| # Engine and session globals | |
| _engine: Engine | None = None | |
| _async_engine: AsyncEngine | None = None | |
| _session_local: sessionmaker | None = None | |
| _async_session_local: async_sessionmaker | None = None | |
| _redis_client: Redis | None = None | |
| def get_database_url() -> str: | |
| """Get database URL from settings""" | |
| return get_settings().database.url | |
| def get_async_database_url() -> str: | |
| """Get async database URL from settings""" | |
| return get_settings().database.async_url | |
| def create_sync_engine() -> Engine: | |
| """Create synchronous database engine with optimized settings""" | |
| settings = get_settings().database | |
| engine_kwargs = { | |
| "echo": settings.echo, | |
| "pool_pre_ping": True, | |
| "pool_recycle": settings.pool_recycle, | |
| } | |
| # Configure connection pool | |
| if settings.url.startswith("sqlite"): | |
| engine_kwargs.update( | |
| { | |
| "poolclass": StaticPool, | |
| "connect_args": { | |
| "check_same_thread": False, | |
| "timeout": 30, | |
| "isolation_level": None, # Autocommit mode for better concurrency | |
| }, | |
| } | |
| ) | |
| else: | |
| engine_kwargs.update( | |
| { | |
| "poolclass": QueuePool, | |
| "pool_size": settings.pool_size, | |
| "max_overflow": settings.max_overflow, | |
| "pool_timeout": settings.pool_timeout, | |
| } | |
| ) | |
| engine = create_engine(settings.url, **engine_kwargs) | |
| # Add event listeners for healthcare-specific optimizations | |
| if settings.url.startswith("sqlite"): | |
| def set_sqlite_pragma(dbapi_connection, connection_record): | |
| """Enhanced SQLite pragmas for optimal healthcare performance""" | |
| cursor = dbapi_connection.cursor() | |
| # Performance optimizations (low-resource friendly) | |
| cursor.execute("PRAGMA journal_mode=WAL") | |
| cursor.execute("PRAGMA synchronous=NORMAL") | |
| cursor.execute("PRAGMA cache_size=5000") # 5K pages (~20MB) | |
| cursor.execute("PRAGMA temp_store=MEMORY") | |
| cursor.execute("PRAGMA mmap_size=134217728") # 128MB mmap (reduced) | |
| cursor.execute("PRAGMA page_size=4096") # Optimal page size | |
| # Data integrity for healthcare | |
| cursor.execute("PRAGMA foreign_keys=ON") | |
| cursor.execute("PRAGMA case_sensitive_like=ON") | |
| cursor.execute("PRAGMA secure_delete=ON") # HIPAA compliance | |
| # Query optimization | |
| cursor.execute("PRAGMA optimize") | |
| cursor.close() | |
| else: | |
| # PostgreSQL connection optimizations | |
| def set_postgres_settings(dbapi_connection, connection_record): | |
| """Optimize PostgreSQL connection for healthcare workloads""" | |
| with dbapi_connection.cursor() as cursor: | |
| # Connection-level optimizations | |
| cursor.execute("SET statement_timeout = '300s'") | |
| cursor.execute("SET lock_timeout = '30s'") | |
| cursor.execute("SET work_mem = '16MB'") | |
| cursor.execute("SET shared_preload_libraries = 'pg_stat_statements'") | |
| return engine | |
| def create_async_engine_instance() -> AsyncEngine: | |
| """Create asynchronous database engine""" | |
| settings = get_settings().database | |
| engine_kwargs = { | |
| "echo": settings.echo, | |
| "pool_pre_ping": True, | |
| "pool_recycle": settings.pool_recycle, | |
| } | |
| # Configure for async | |
| if not settings.url.startswith("sqlite"): | |
| engine_kwargs.update( | |
| { | |
| "pool_size": settings.pool_size, | |
| "max_overflow": settings.max_overflow, | |
| } | |
| ) | |
| return create_async_engine(get_async_database_url(), **engine_kwargs) | |
| def get_engine() -> Engine: | |
| """Get or create synchronous database engine""" | |
| global _engine | |
| if _engine is None: | |
| _engine = create_sync_engine() | |
| logger.info("Synchronous database engine created") | |
| return _engine | |
| def get_async_engine() -> AsyncEngine: | |
| """Get or create asynchronous database engine""" | |
| global _async_engine | |
| if _async_engine is None: | |
| _async_engine = create_async_engine_instance() | |
| logger.info("Asynchronous database engine created") | |
| return _async_engine | |
| def get_session_local() -> sessionmaker: | |
| """Get or create session factory""" | |
| global _session_local | |
| if _session_local is None: | |
| _session_local = sessionmaker(autocommit=False, autoflush=False, bind=get_engine()) | |
| logger.info("Session factory created") | |
| return _session_local | |
| def get_async_session_local() -> async_sessionmaker: | |
| """Get or create async session factory""" | |
| global _async_session_local | |
| if _async_session_local is None: | |
| _async_session_local = async_sessionmaker( | |
| bind=get_async_engine(), | |
| class_=AsyncSession, | |
| autocommit=False, | |
| autoflush=False, | |
| expire_on_commit=False, | |
| ) | |
| logger.info("Async session factory created") | |
| return _async_session_local | |
| # Session factories for dependency injection | |
| SessionLocal = get_session_local | |
| AsyncSessionLocal = get_async_session_local | |
| # Engine exports for backwards compatibility | |
| engine = get_engine | |
| async_engine = get_async_engine | |
| def get_db() -> Generator[Session, None, None]: | |
| """Database session dependency for FastAPI""" | |
| session = get_session_local()() | |
| try: | |
| yield session | |
| session.commit() | |
| except Exception: | |
| session.rollback() | |
| raise | |
| finally: | |
| session.close() | |
| async def get_async_db() -> AsyncGenerator[AsyncSession, None]: | |
| """Async database session dependency for FastAPI""" | |
| async_session = get_async_session_local() | |
| async with async_session() as session: | |
| try: | |
| yield session | |
| await session.commit() | |
| except Exception: | |
| await session.rollback() | |
| raise | |
| def get_db_session(): | |
| """Context manager for database sessions""" | |
| session = get_session_local()() | |
| try: | |
| yield session | |
| session.commit() | |
| except Exception: | |
| session.rollback() | |
| raise | |
| finally: | |
| session.close() | |
| async def get_async_db_session(): | |
| """Async context manager for database sessions""" | |
| async_session = get_async_session_local() | |
| async with async_session() as session: | |
| try: | |
| yield session | |
| await session.commit() | |
| except Exception: | |
| await session.rollback() | |
| raise | |
| def get_db_context(): | |
| """Alternative name for get_db_session""" | |
| return get_db_session() | |
| def get_async_db_context(): | |
| """Alternative name for get_async_db_session""" | |
| return get_async_db_session() | |
| def test_connection() -> bool: | |
| """Test database connection""" | |
| try: | |
| engine = get_engine() | |
| with engine.connect() as connection: | |
| connection.execute(text("SELECT 1")) | |
| logger.info("Database connection test successful") | |
| return True | |
| except Exception as e: | |
| logger.error("Database connection test failed", error=str(e)) | |
| return False | |
| async def test_async_connection() -> bool: | |
| """Test async database connection""" | |
| try: | |
| engine = get_async_engine() | |
| async with engine.connect() as connection: | |
| await connection.execute(text("SELECT 1")) | |
| logger.info("Async database connection test successful") | |
| return True | |
| except Exception as e: | |
| logger.error("Async database connection test failed", error=str(e)) | |
| return False | |
| async def get_redis() -> Redis: | |
| """Get Redis client for caching and session management""" | |
| global _redis_client | |
| settings = get_settings().redis | |
| if not settings.enabled: | |
| logger.warning("Redis is disabled in configuration") | |
| return None # type: ignore[name-defined, index, return-value, var-annotated] | |
| if _redis_client is None: | |
| try: | |
| # Create connection pool | |
| pool = ConnectionPool.from_url( | |
| settings.url, | |
| max_connections=settings.max_connections, | |
| socket_timeout=settings.socket_timeout, | |
| socket_connect_timeout=settings.socket_connect_timeout, | |
| retry_on_timeout=settings.retry_on_timeout, | |
| decode_responses=True, | |
| ) | |
| _redis_client = Redis(connection_pool=pool) | |
| # Test connection | |
| await _redis_client.ping() | |
| logger.info("Redis client created and connected") | |
| except Exception as e: | |
| logger.error("Failed to create Redis client", error=str(e)) | |
| _redis_client = None | |
| return _redis_client # type: ignore[name-defined, index, return-value, var-annotated] | |
| async def close_redis(): | |
| """Close Redis connection""" | |
| global _redis_client | |
| if _redis_client: | |
| await _redis_client.close() | |
| _redis_client = None | |
| logger.info("Redis client closed") | |
| async def cache_get(key: str) -> Any | None: | |
| """Get value from Redis cache with error handling""" | |
| try: | |
| redis_client = await get_redis() | |
| if not redis_client: | |
| return None | |
| value = await redis_client.get(key) | |
| if value: | |
| import json | |
| return json.loads(value) | |
| return None | |
| except Exception as e: | |
| logger.warning(f"Cache get failed for key {key}", error=str(e)) | |
| return None | |
| async def cache_set(key: str, value: Any, ttl: int = 3600) -> bool: | |
| """Set value in Redis cache with error handling""" | |
| try: | |
| redis_client = await get_redis() | |
| if not redis_client: | |
| return False | |
| import json | |
| await redis_client.setex(key, ttl, json.dumps(value, default=str)) | |
| return True | |
| except Exception as e: | |
| logger.warning(f"Cache set failed for key {key}", error=str(e)) | |
| return False | |
| async def cache_delete(key: str) -> bool: | |
| """Delete key from Redis cache""" | |
| try: | |
| redis_client = await get_redis() | |
| if not redis_client: | |
| return False | |
| await redis_client.delete(key) | |
| return True | |
| except Exception as e: | |
| logger.warning(f"Cache delete failed for key {key}", error=str(e)) | |
| return False | |
| def init_database() -> None: | |
| """Initialize database and create tables""" | |
| try: | |
| engine = get_engine() | |
| # Import all models to ensure they're registered | |
| # Schema bootstrap — SQLite (dev) only. | |
| # In production (PostgreSQL) schema is managed by Alembic migrations. | |
| # Calling create_all on PostgreSQL bypasses migration history and | |
| # risks silent schema drift. | |
| if str(engine.url).startswith("sqlite"): | |
| Base.metadata.create_all(bind=engine) | |
| logger.info("Database initialized and tables created") | |
| else: | |
| logger.info( | |
| "PostgreSQL detected — skipping create_all; " | |
| "run 'alembic upgrade head' to apply pending migrations." | |
| ) | |
| # Log connection pool status | |
| if hasattr(engine.pool, "size"): | |
| logger.info( | |
| f"Connection pool initialized - Size: {engine.pool.size()}, Checked out: {engine.pool.checkedout()}" | |
| ) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] | |
| except Exception as e: | |
| logger.error("Database initialization failed", error=str(e)) | |
| raise | |
| async def get_database_health() -> dict[str, Any]: | |
| """Get comprehensive database and cache health status""" | |
| health = {"database": False, "redis": False, "details": {}, "performance": {}} | |
| # Test database connection with timing | |
| import time | |
| try: | |
| start_time = time.time() | |
| engine = get_engine() | |
| with engine.connect() as connection: | |
| result = connection.execute(text("SELECT 1")).scalar() | |
| health["database"] = result == 1 | |
| health["details"]["database"] = "Connected" # type: ignore[name-defined, index, return-value, var-annotated] | |
| except Exception as e: | |
| health["details"]["database"] = f"Error: {str(e)}" # type: ignore[name-defined, index, return-value, var-annotated] | |
| # Test Redis connection | |
| try: | |
| redis_client = await get_redis() | |
| if redis_client: | |
| await redis_client.ping() | |
| health["redis"] = True | |
| health["details"]["redis"] = "Connected" # type: ignore[name-defined, index, return-value, var-annotated] | |
| else: | |
| health["details"]["redis"] = "Disabled or not configured" # type: ignore[name-defined, index, return-value, var-annotated] | |
| except Exception as e: | |
| health["details"]["redis"] = f"Error: {str(e)}" # type: ignore[name-defined, index, return-value, var-annotated] | |
| return health | |
| class DatabaseManager: | |
| """Healthcare-specific database management utilities""" | |
| def __init__(self): | |
| self.engine = None | |
| self.SessionLocal = None | |
| def initialize(self): | |
| """Initialize database manager""" | |
| self.engine = get_engine() | |
| self.SessionLocal = get_session_local() | |
| logger.info("Database manager initialized") | |
| def create_tables(self): | |
| """Create all database tables (SQLite/dev only; use Alembic in production)""" | |
| if not self.engine: | |
| self.initialize() | |
| if str(self.engine.url).startswith("sqlite"): # type: ignore[union-attr] | |
| Base.metadata.create_all(bind=self.engine) | |
| logger.info("Database tables created") | |
| else: | |
| logger.warning( | |
| "create_tables() called on PostgreSQL — use 'alembic upgrade head' instead." | |
| ) | |
| def check_connection(self) -> bool: | |
| """Check database connectivity""" | |
| return test_connection() | |
| async def check_redis_connection(self) -> bool: | |
| """Check Redis connectivity""" | |
| try: | |
| redis_client = await get_redis() | |
| if redis_client: | |
| await redis_client.ping() | |
| return True | |
| return False | |
| except Exception: | |
| return False | |
| def get_session(self) -> Session: | |
| """Get database session""" | |
| if not self.SessionLocal: | |
| self.initialize() | |
| return self.SessionLocal() # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] | |
| def get_active_patients_count(self) -> int: | |
| """Get count of active patients""" | |
| try: | |
| with get_db_session(): | |
| # This would need to be implemented based on your actual Patient model | |
| # For now, return 0 as placeholder | |
| return 0 | |
| except Exception as e: | |
| logger.error("Failed to get active patients count", error=str(e)) | |
| return 0 | |
| def get_pending_surgeries_count(self) -> int: | |
| """Get count of pending surgeries""" | |
| try: | |
| with get_db_session(): | |
| # This would need to be implemented based on your actual models | |
| # For now, return 0 as placeholder | |
| return 0 | |
| except Exception as e: | |
| logger.error("Failed to get pending surgeries count", error=str(e)) | |
| return 0 | |
| # Global database manager instance | |
| db_manager = DatabaseManager() | |
| # Cleanup functions | |
| async def close_database_connections(): | |
| """Close all database connections""" | |
| global _engine, _async_engine, _session_local, _async_session_local | |
| # Close Redis | |
| await close_redis() | |
| # Close async engine | |
| if _async_engine: | |
| await _async_engine.dispose() | |
| _async_engine = None | |
| # Close sync engine | |
| if _engine: | |
| _engine.dispose() | |
| _engine = None | |
| # Reset session factories | |
| _session_local = None | |
| _async_session_local = None | |
| logger.info("All database connections closed") | |
| # Initialize database on module import | |
| try: | |
| # Only initialize if not in testing - disabled for migration | |
| import os | |
| # Temporarily disabled for Alembic migration setup | |
| # if os.getenv("TESTING") != "1": | |
| # init_database() | |
| except Exception as e: | |
| logger.warning("Database initialization deferred", error=str(e)) | |
| __all__ = [ | |
| "Base", | |
| "metadata", | |
| "engine", | |
| "async_engine", | |
| "get_engine", | |
| "get_async_engine", | |
| "get_session_local", | |
| "get_async_session_local", | |
| "SessionLocal", | |
| "AsyncSessionLocal", | |
| "get_db", | |
| "get_async_db", | |
| "get_db_session", | |
| "get_async_db_session", | |
| "get_db_context", | |
| "get_async_db_context", | |
| "get_redis", | |
| "test_connection", | |
| "test_async_connection", | |
| "init_database", | |
| "get_database_health", | |
| "DatabaseManager", | |
| "db_manager", | |
| "close_database_connections", | |
| ] | |