from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import OperationalError from config import MYSQL_CONFIG from fastapi import HTTPException import os import base64 SQLALCHEMY_DATABASE_URL = MYSQL_CONFIG.DB_URI_SQL_ALCHEMY # Get the base64 encoded certificate from the environment variable ca_cert_base64 = os.getenv("CA_CERT_BASE64") # Decode the base64 content if ca_cert_base64: ca_cert_content = base64.b64decode(ca_cert_base64).decode("utf-8") # Write the decoded content to a temporary .pem file with open("/tmp/ca.pem", "w") as f: f.write(ca_cert_content) ca_cert_path = "/tmp/ca.pem" else: raise ValueError("CA_CERT_BASE64 environment variable is not set") # Use the decoded CA certificate in the SQLAlchemy engine engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={ "ssl": { "sslmode": "REQUIRED", "ca": ca_cert_path, # Path to the temporary CA certificate # Add other SSL options as needed } }, ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) def get_db(): db = SessionLocal() try: yield db except OperationalError as e: # Log the error and raise HTTPException for FastAPI print(f"An error occurred in get database sql alchemy.: {e}") raise HTTPException(status_code=400, detail="Database connection error") # Check if it's an authentication-related error except Exception as e: # Check if it's an authentication-related error if "401" in str(e): raise HTTPException(status_code=401, detail="Authentication failed") else: # For any other type of exception, raise a generic 400 error print(f"An error occurred: {e}") raise HTTPException(status_code=400, detail="An unexpected error occurred")