Backend Tests: - Add pytest configuration with async support (conftest.py) - Add model tests: User, Conversation, Message, TokenUsage, Session, UserMemory - Add configuration tests: Settings validation and environment variables - Add API tests: Health endpoint and future endpoint stubs - Add database tests: Connection, transactions, query execution Phase 1 Foundation: - FastAPI application structure with main.py - SQLAlchemy async models for all entities - Alembic migrations setup - Configuration management via Pydantic Settings - Logging system (English only) - Docker multi-stage builds for backend - Docker Compose orchestration (PostgreSQL, Redis, backend) - Frontend React + TypeScript structure - Dark & Gold theme CSS implementation - Environment configuration examples All code and comments in English as per requirements. Tests cover model relationships, cascade deletes, and constraints. Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
65 lines
1.5 KiB
Python
65 lines
1.5 KiB
Python
"""
|
|
Database connection and session management using SQLAlchemy with async support.
|
|
"""
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
|
from sqlalchemy.orm import declarative_base
|
|
from app.config import settings
|
|
|
|
# Create async engine
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=settings.DEBUG,
|
|
pool_pre_ping=True,
|
|
pool_size=10,
|
|
max_overflow=20,
|
|
)
|
|
|
|
# Create async session factory
|
|
AsyncSessionLocal = async_sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
autocommit=False,
|
|
autoflush=False,
|
|
)
|
|
|
|
# Base class for declarative models
|
|
Base = declarative_base()
|
|
|
|
|
|
async def get_db() -> AsyncSession:
|
|
"""
|
|
Dependency for FastAPI endpoints to get database session.
|
|
|
|
Usage:
|
|
@app.get("/users")
|
|
async def get_users(db: AsyncSession = Depends(get_db)):
|
|
...
|
|
"""
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|
|
|
|
|
|
async def init_db():
|
|
"""
|
|
Initialize database - create all tables.
|
|
Should be called on application startup.
|
|
"""
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
|
|
|
|
async def close_db():
|
|
"""
|
|
Close database connections.
|
|
Should be called on application shutdown.
|
|
"""
|
|
await engine.dispose()
|