59 lines
1.5 KiB
Python
59 lines
1.5 KiB
Python
"""Async database configuration and initialization."""
|
|
|
|
import logging
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from app.config import settings
|
|
from app.memory.models import Base
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Global engine and session factory
|
|
engine = None
|
|
async_session_factory = None
|
|
|
|
|
|
async def init_db() -> None:
|
|
"""Initialize the database engine and create all tables."""
|
|
global engine, async_session_factory
|
|
|
|
try:
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=settings.DEBUG,
|
|
future=True,
|
|
)
|
|
|
|
async_session_factory = sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
)
|
|
|
|
# Create all tables
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
|
|
logger.info("Database initialized successfully")
|
|
except Exception as e:
|
|
logger.error(f"Failed to initialize database: {e}")
|
|
raise
|
|
|
|
|
|
async def get_session() -> AsyncSession:
|
|
"""Get an async database session."""
|
|
if async_session_factory is None:
|
|
raise RuntimeError("Database not initialized. Call init_db() first.")
|
|
|
|
async with async_session_factory() as session:
|
|
yield session
|
|
|
|
|
|
async def close_db() -> None:
|
|
"""Close the database connection."""
|
|
global engine
|
|
if engine:
|
|
await engine.dispose()
|
|
logger.info("Database connection closed")
|