""" YAZ Care Platform - Database Manager PostgreSQL production database with multi-tenant support and HIPAA compliance """ import os import asyncio import structlog from typing import Dict, Any, Optional, List from datetime import datetime from pathlib import Path try: import sqlalchemy as sa from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker from sqlalchemy.orm import declarative_base, sessionmaker from sqlalchemy.sql import text from alembic import command from alembic.config import Config ASYNC_DB_AVAILABLE = True except ImportError: ASYNC_DB_AVAILABLE = False # asyncpg is optional - only needed for PostgreSQL try: import asyncpg ASYNCPG_AVAILABLE = True except ImportError: ASYNCPG_AVAILABLE = False logger = structlog.get_logger(__name__) class DatabaseManager: """ Production database manager with multi-tenant support Features: Connection pooling, RLS, HIPAA compliance, automated migrations """ def __init__(self): db_url = os.getenv("DATABASE_URL", "sqlite:///./data/databases/yaz_care.db") # Convert sqlite:// to sqlite+aiosqlite:// for async support if db_url.startswith("sqlite://"): self.database_url = db_url.replace("sqlite://", "sqlite+aiosqlite://") else: self.database_url = db_url self.is_postgresql = self.database_url.startswith("postgresql") self.engine = None self.async_session_maker = None self.tenant_isolation = os.getenv("TENANT_ISOLATION_ENABLED", "false").lower() == "true" self.rls_enabled = os.getenv("RLS_ENABLED", "false").lower() == "true" async def initialize(self): """Initialize database connection and setup""" if not ASYNC_DB_AVAILABLE: logger.warning("Async database dependencies not available") return False try: # Import optimization settings from core.database.query_optimizer import get_optimal_pool_settings # Get environment-specific pool settings env = os.getenv("ENVIRONMENT", "development") pool_settings = get_optimal_pool_settings(env) # Create async engine with optimized production settings engine_kwargs = { "pool_size": int(os.getenv("DB_POOL_SIZE", str(pool_settings["pool_size"]))), "max_overflow": int( os.getenv("DB_MAX_OVERFLOW", str(pool_settings["max_overflow"])) ), "pool_timeout": int( os.getenv("DB_POOL_TIMEOUT", str(pool_settings["pool_timeout"])) ), "pool_recycle": int( os.getenv("DB_POOL_RECYCLE", str(pool_settings["pool_recycle"])) ), "echo": os.getenv("DEBUG", "false").lower() == "true", } # Add pool_pre_ping for PostgreSQL (not supported by SQLite) if self.is_postgresql and pool_settings.get("pool_pre_ping"): engine_kwargs["pool_pre_ping"] = True self.engine = create_async_engine(self.database_url, **engine_kwargs) # Register engine for pool telemetry (Prometheus db_pool_* metrics) try: from monitoring.prometheus_metrics import register_db_engine # asyncpg engine exposes pool via sync_engine _sync_engine = getattr(self.engine, "sync_engine", self.engine) register_db_engine(_sync_engine, name="primary") except Exception: pass # Non-fatal: metrics simply won't show pool stats # Create session maker self.async_session_maker = async_sessionmaker( self.engine, class_=AsyncSession, expire_on_commit=False ) # Test connection await self.health_check() logger.info("✅ Database initialized successfully") return True except Exception as e: logger.error(f"❌ Database initialization failed: {e}") return False async def health_check(self) -> Dict[str, Any]: """Comprehensive database health check""" if not self.engine: return {"status": "error", "message": "Database not initialized"} try: async with self.engine.connect() as conn: # Basic connectivity await conn.execute(text("SELECT 1")) # Check PostgreSQL specific features if self.is_postgresql: # Check RLS support rls_result = await conn.execute( text( "SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public'" ) ) table_count = rls_result.scalar() # Check for tenant isolation table if self.tenant_isolation: tenant_check = await conn.execute( text( "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'tenants')" ) ) tenant_table_exists = tenant_check.scalar() else: tenant_table_exists = None return { "status": "healthy", "database_type": "postgresql", "table_count": table_count, "rls_enabled": self.rls_enabled, "tenant_isolation": self.tenant_isolation, "tenant_table_exists": tenant_table_exists, "timestamp": datetime.now().isoformat(), } else: return { "status": "healthy", "database_type": "sqlite", "timestamp": datetime.now().isoformat(), } except Exception as e: return {"status": "error", "message": str(e), "timestamp": datetime.now().isoformat()} async def setup_multi_tenant_schema(self): """Setup multi-tenant schema with Row Level Security""" if not self.is_postgresql or not self.tenant_isolation: logger.info("Multi-tenant setup skipped (not PostgreSQL or disabled)") return True try: async with self.engine.connect() as conn: # type: ignore[union-attr] # Create tenants table await conn.execute( text( """ CREATE TABLE IF NOT EXISTS tenants ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name VARCHAR(255) NOT NULL UNIQUE, subdomain VARCHAR(100) UNIQUE, settings JSONB DEFAULT '{}', created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), active BOOLEAN DEFAULT TRUE ) """ ) ) # Create tenant context function await conn.execute( text( """ CREATE OR REPLACE FUNCTION get_current_tenant_id() RETURNS UUID AS $$ BEGIN RETURN current_setting('app.tenant_id', true)::UUID; EXCEPTION WHEN others THEN RETURN NULL; END; $$ LANGUAGE plpgsql STABLE; """ ) ) # Create audit log table for HIPAA compliance await conn.execute( text( """ CREATE TABLE IF NOT EXISTS audit_logs ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id UUID REFERENCES tenants(id), user_id UUID, action VARCHAR(100) NOT NULL, resource_type VARCHAR(100), resource_id VARCHAR(255), old_values JSONB, new_values JSONB, ip_address INET, user_agent TEXT, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ) """ ) ) await conn.commit() logger.info("✅ Multi-tenant schema setup complete") return True except Exception as e: logger.error(f"❌ Multi-tenant schema setup failed: {e}") return False async def create_default_tenant(self): """Create default tenant for initial setup""" if not self.tenant_isolation: return True try: async with self.async_session_maker() as session: # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] # Check if default tenant exists result = await session.execute( text("SELECT id FROM tenants WHERE name = 'Default Healthcare Organization'") ) if not result.scalar(): # Create default tenant await session.execute( text( """ INSERT INTO tenants (name, subdomain, settings) VALUES ( 'Default Healthcare Organization', 'default', '{"features": ["all"], "max_users": 1000}' ) """ ) ) await session.commit() logger.info("✅ Default tenant created") return True except Exception as e: logger.error(f"❌ Default tenant creation failed: {e}") return False async def run_migrations(self) -> Dict[str, Any]: """Run database migrations""" try: # Setup Alembic configuration alembic_cfg = Config("alembic.ini") # Run migrations command.upgrade(alembic_cfg, "head") return { "status": "success", "message": "Migrations completed successfully", "timestamp": datetime.now().isoformat(), } except Exception as e: logger.error(f"Migration failed: {e}") return {"status": "error", "message": str(e), "timestamp": datetime.now().isoformat()} async def backup_database(self) -> Dict[str, Any]: """Create database backup""" if not self.is_postgresql: return {"status": "skipped", "message": "Backup only supported for PostgreSQL"} try: # Extract connection details import urllib.parse as urlparse parsed = urlparse.urlparse(self.database_url) backup_path = ( Path("./backups") / f"yazcare_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.sql" ) backup_path.parent.mkdir(exist_ok=True) # Use pg_dump for backup import subprocess cmd = [ "pg_dump", "-h", parsed.hostname, "-p", str(parsed.port), "-U", parsed.username, "-d", parsed.path[1:], # Remove leading slash "-f", str(backup_path), "--verbose", ] env = os.environ.copy() env["PGPASSWORD"] = parsed.password # type: ignore[arg-type, assignment] result = subprocess.run(cmd, env=env, capture_output=True, text=True) # type: ignore[arg-type, assignment] if result.returncode == 0: return { "status": "success", "backup_path": str(backup_path), "size_mb": backup_path.stat().st_size / (1024 * 1024), "timestamp": datetime.now().isoformat(), } else: return { "status": "error", "message": result.stderr, "timestamp": datetime.now().isoformat(), } except Exception as e: logger.error(f"Backup failed: {e}") return {"status": "error", "message": str(e), "timestamp": datetime.now().isoformat()} async def close(self): """Close database connections""" if self.engine: await self.engine.dispose() logger.info("Database connections closed") # Global database manager instance db_manager = DatabaseManager() # Convenience functions - FastAPI dependency injection compatible async def get_db_session(): """ Get database session as async generator for FastAPI Depends(). Usage: session: AsyncSession = Depends(get_db_session) Note: Do NOT use @asynccontextmanager decorator - FastAPI handles the context management automatically for async generators. """ if not db_manager.async_session_maker: await db_manager.initialize() async with db_manager.async_session_maker() as session: # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] yield session async def init_database(): """Initialize database system""" success = await db_manager.initialize() if success and db_manager.is_postgresql: await db_manager.setup_multi_tenant_schema() await db_manager.create_default_tenant() return success # Export main components __all__ = ["DatabaseManager", "db_manager", "get_db_session", "init_database"]