Spaces:
Runtime error
Runtime error
File size: 3,251 Bytes
55b6d21 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | """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)
|