feat: revue de code, doc CODE_REVIEW, forfaits 2026, traduction LLM, providers avec modèle
Made-with: Cursor
This commit is contained in:
@@ -1,135 +1,174 @@
|
||||
"""
|
||||
Database connection and session management
|
||||
Supports both PostgreSQL (production) and SQLite (development/testing)
|
||||
Async SQLAlchemy 2.0 implementation
|
||||
"""
|
||||
|
||||
import os
|
||||
import logging
|
||||
from typing import Generator, Optional
|
||||
from typing import AsyncGenerator, Optional
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from sqlalchemy import text, create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
create_async_engine,
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
AsyncEngine,
|
||||
)
|
||||
from sqlalchemy.pool import QueuePool, StaticPool
|
||||
from contextlib import contextmanager
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from sqlalchemy.pool import QueuePool, StaticPool
|
||||
from database.utils import convert_to_async_url
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Database URL from environment
|
||||
# PostgreSQL: postgresql://user:password@host:port/database
|
||||
# SQLite: sqlite:///./data/translate.db
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", "")
|
||||
|
||||
# Determine if we're using SQLite or PostgreSQL
|
||||
_is_sqlite = DATABASE_URL.startswith("sqlite") if DATABASE_URL else True
|
||||
_is_postgres = DATABASE_URL.startswith("postgres") if DATABASE_URL else False
|
||||
|
||||
# Create engine based on database type
|
||||
if DATABASE_URL and not _is_sqlite:
|
||||
# PostgreSQL configuration
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
|
||||
if DATABASE_URL and _is_postgres:
|
||||
async_database_url = convert_to_async_url(DATABASE_URL)
|
||||
engine: AsyncEngine = create_async_engine(
|
||||
async_database_url,
|
||||
poolclass=QueuePool,
|
||||
pool_size=5,
|
||||
max_overflow=10,
|
||||
pool_timeout=30,
|
||||
pool_recycle=1800, # Recycle connections after 30 minutes
|
||||
pool_pre_ping=True, # Check connection health before use
|
||||
pool_recycle=1800,
|
||||
pool_pre_ping=True,
|
||||
echo=os.getenv("DATABASE_ECHO", "false").lower() == "true",
|
||||
)
|
||||
logger.info("✅ Database configured with PostgreSQL")
|
||||
logger.info("✅ Database configured with PostgreSQL (async)")
|
||||
else:
|
||||
# SQLite configuration (for development/testing or when no DATABASE_URL)
|
||||
sqlite_path = os.getenv("SQLITE_PATH", "data/translate.db")
|
||||
os.makedirs(os.path.dirname(sqlite_path), exist_ok=True)
|
||||
|
||||
sqlite_url = f"sqlite:///./{sqlite_path}"
|
||||
engine = create_engine(
|
||||
sqlite_url,
|
||||
os.makedirs(
|
||||
os.path.dirname(sqlite_path) if os.path.dirname(sqlite_path) else ".",
|
||||
exist_ok=True,
|
||||
)
|
||||
|
||||
async_database_url = f"sqlite+aiosqlite:///./{sqlite_path}"
|
||||
engine: AsyncEngine = create_async_engine(
|
||||
async_database_url,
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
echo=os.getenv("DATABASE_ECHO", "false").lower() == "true",
|
||||
)
|
||||
|
||||
# Enable foreign keys for SQLite
|
||||
@event.listens_for(engine, "connect")
|
||||
def set_sqlite_pragma(dbapi_connection, connection_record):
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close()
|
||||
|
||||
if not DATABASE_URL:
|
||||
logger.warning("⚠️ DATABASE_URL not set, using SQLite for development")
|
||||
else:
|
||||
logger.info(f"✅ Database configured with SQLite: {sqlite_path}")
|
||||
|
||||
# Session factory
|
||||
SessionLocal = sessionmaker(
|
||||
if not DATABASE_URL:
|
||||
logger.warning("⚠️ DATABASE_URL not set, using SQLite for development (async)")
|
||||
else:
|
||||
logger.info(f"✅ Database configured with SQLite: {sqlite_path} (async)")
|
||||
|
||||
# Sync engine and session for repositories (auth, translation log).
|
||||
# Kept for backward compatibility until all callers use async; see story 1-1.
|
||||
# Prefer get_db() / AsyncSessionLocal for new code.
|
||||
if DATABASE_URL and _is_postgres:
|
||||
sync_engine = create_engine(
|
||||
DATABASE_URL,
|
||||
poolclass=QueuePool,
|
||||
pool_size=5,
|
||||
max_overflow=10,
|
||||
pool_pre_ping=True,
|
||||
echo=os.getenv("DATABASE_ECHO", "false").lower() == "true",
|
||||
)
|
||||
else:
|
||||
_sqlite_path = os.getenv("SQLITE_PATH", "data/translate.db")
|
||||
_sync_sqlite_url = f"sqlite:///./{_sqlite_path}"
|
||||
sync_engine = create_engine(
|
||||
_sync_sqlite_url,
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
|
||||
SyncSessionLocal = sessionmaker(bind=sync_engine, autocommit=False, autoflush=False, expire_on_commit=False)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_sync_session():
|
||||
"""Sync session context manager for use with sync repositories (auth_service, translation log)."""
|
||||
session = SyncSessionLocal()
|
||||
try:
|
||||
yield session
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
AsyncSessionLocal = async_sessionmaker(
|
||||
bind=engine,
|
||||
class_=AsyncSession,
|
||||
autocommit=False,
|
||||
autoflush=False,
|
||||
bind=engine,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
"""
|
||||
Dependency for FastAPI to get database session.
|
||||
Usage: db: Session = Depends(get_db)
|
||||
Async dependency for FastAPI to get database session.
|
||||
Usage: db: AsyncSession = Depends(get_db)
|
||||
"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_db_session() -> Generator[Session, None, None]:
|
||||
@asynccontextmanager
|
||||
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
"""
|
||||
Context manager for database session.
|
||||
Usage: with get_db_session() as db: ...
|
||||
Async context manager for database session.
|
||||
Usage: async with get_db_session() as db: ...
|
||||
"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
db.commit()
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
|
||||
|
||||
# Alias for backward compatibility
|
||||
get_sync_session = get_db_session
|
||||
get_async_session = get_db_session
|
||||
|
||||
|
||||
def init_db():
|
||||
async def init_db():
|
||||
"""
|
||||
Initialize database tables.
|
||||
Initialize database tables asynchronously.
|
||||
Call this on application startup.
|
||||
"""
|
||||
from database.models import Base
|
||||
Base.metadata.create_all(bind=engine)
|
||||
logger.info("✅ Database tables initialized")
|
||||
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
logger.info("✅ Database tables initialized (async)")
|
||||
|
||||
|
||||
def check_db_connection() -> bool:
|
||||
async def check_db_connection() -> bool:
|
||||
"""
|
||||
Check if database connection is healthy.
|
||||
Returns True if connection works, False otherwise.
|
||||
"""
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
async with engine.connect() as conn:
|
||||
await conn.execute(text("SELECT 1"))
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Database connection check failed: {e}")
|
||||
return False
|
||||
|
||||
|
||||
# Connection pool stats (for monitoring)
|
||||
def get_pool_stats() -> dict:
|
||||
"""Get database connection pool statistics"""
|
||||
if hasattr(engine.pool, 'status'):
|
||||
if hasattr(engine.pool, "status"):
|
||||
return {
|
||||
"pool_size": engine.pool.size(),
|
||||
"checked_in": engine.pool.checkedin(),
|
||||
@@ -137,3 +176,8 @@ def get_pool_stats() -> dict:
|
||||
"overflow": engine.pool.overflow(),
|
||||
}
|
||||
return {"status": "pool stats not available"}
|
||||
|
||||
|
||||
def get_engine() -> AsyncEngine:
|
||||
"""Get the async engine instance"""
|
||||
return engine
|
||||
|
||||
Reference in New Issue
Block a user