From c9ee1823beb911c0b89c05e8194f8ba07ea8cc57 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Thu, 5 Jun 2025 11:35:00 +0000 Subject: [PATCH] Fix database migration error by adding aiosqlite dependency and implementing fallback for sync/async operations --- app/core/database.py | 80 ++++++++++++++++++++---------- app/core/health.py | 4 +- app/crud/user.py | 113 ++++++++++++++++++++++++++++++++----------- requirements.txt | 1 + 4 files changed, 144 insertions(+), 54 deletions(-) diff --git a/app/core/database.py b/app/core/database.py index 9d73503..d6eb336 100644 --- a/app/core/database.py +++ b/app/core/database.py @@ -1,10 +1,10 @@ from pathlib import Path -from typing import AsyncGenerator +from typing import AsyncGenerator, Generator from sqlalchemy import create_engine from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker +from sqlalchemy.orm import Session, sessionmaker # Ensure DB directory exists @@ -19,36 +19,66 @@ engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} ) -# For async operations, we need to use a different driver -ASYNC_SQLALCHEMY_DATABASE_URL = f"sqlite+aiosqlite:///{DB_DIR}/db.sqlite" -async_engine = create_async_engine( - ASYNC_SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) - -# Create session factories +# Create session factories for synchronous operations SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) -AsyncSessionLocal = sessionmaker( - autocommit=False, - autoflush=False, - bind=async_engine, - class_=AsyncSession, -) # Create a base class for declarative models Base = declarative_base() +# For async operations, we need to use a different driver +try: + import aiosqlite # noqa: F401 - needed for sqlalchemy dialect registration -# Dependency function for getting a database session -async def get_db() -> AsyncGenerator[AsyncSession, None]: - """ - Dependency function that yields an async database session. - """ - async with AsyncSessionLocal() as session: + ASYNC_SQLALCHEMY_DATABASE_URL = f"sqlite+aiosqlite:///{DB_DIR}/db.sqlite" + async_engine = create_async_engine( + ASYNC_SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} + ) + AsyncSessionLocal = sessionmaker( + autocommit=False, + autoflush=False, + bind=async_engine, + class_=AsyncSession, + ) + + # Dependency function for getting an async database session + async def get_db() -> AsyncGenerator[AsyncSession, None]: + """ + Dependency function that yields an async database session. + """ + async with AsyncSessionLocal() as session: + try: + yield session + await session.commit() + except Exception: + await session.rollback() + raise + finally: + await session.close() +except ImportError: + # Fallback to synchronous operations if aiosqlite is not available + async_engine = None + AsyncSessionLocal = None + + # Fallback synchronous dependency + def get_db_sync() -> Generator[Session, None, None]: + """ + Synchronous dependency function for getting a database session. + For use when aiosqlite is not available. + """ + db = SessionLocal() try: - yield session - await session.commit() + yield db + db.commit() except Exception: - await session.rollback() + db.rollback() raise finally: - await session.close() + db.close() + + # Wrapper for backward compatibility + async def get_db() -> Generator[Session, None, None]: + """ + Compatibility wrapper that provides a synchronous session + when aiosqlite is not available. + """ + yield from get_db_sync() diff --git a/app/core/health.py b/app/core/health.py index 7ac7acb..5fcca7c 100644 --- a/app/core/health.py +++ b/app/core/health.py @@ -1,5 +1,5 @@ from fastapi import APIRouter, Depends -from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import Session from app.core.database import get_db from app.models.health import HealthCheck @@ -8,7 +8,7 @@ health_router = APIRouter() @health_router.get("/health", response_model=HealthCheck, tags=["health"]) -async def health(db: AsyncSession = Depends(get_db)): +async def health(db: Session = Depends(get_db)): """ Health check endpoint to verify API is running properly. """ diff --git a/app/crud/user.py b/app/crud/user.py index 9d04153..8ee2f2a 100644 --- a/app/crud/user.py +++ b/app/crud/user.py @@ -1,39 +1,55 @@ from datetime import datetime -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, List, Optional, Union, TYPE_CHECKING from sqlalchemy import select -from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import Session from app.core.security import get_password_hash, verify_password from app.models.user import User from app.schemas.user import UserCreate, UserUpdate +# For type hints +if TYPE_CHECKING: + pass -async def get_by_id(db: AsyncSession, user_id: str) -> Optional[User]: + +async def get_by_id(db: Session, user_id: str) -> Optional[User]: """ Get a user by ID. """ - result = await db.execute(select(User).filter(User.id == user_id)) - return result.scalars().first() + # Check if db has execute method (AsyncSession) + if hasattr(db, "execute"): + result = await db.execute(select(User).filter(User.id == user_id)) + return result.scalars().first() + # Synchronous operation + return db.query(User).filter(User.id == user_id).first() -async def get_by_email(db: AsyncSession, email: str) -> Optional[User]: +async def get_by_email(db: Session, email: str) -> Optional[User]: """ Get a user by email. """ - result = await db.execute(select(User).filter(User.email == email)) - return result.scalars().first() + # Check if db has execute method (AsyncSession) + if hasattr(db, "execute"): + result = await db.execute(select(User).filter(User.email == email)) + return result.scalars().first() + # Synchronous operation + return db.query(User).filter(User.email == email).first() -async def get_users(db: AsyncSession, skip: int = 0, limit: int = 100) -> List[User]: +async def get_users(db: Session, skip: int = 0, limit: int = 100) -> List[User]: """ Get a list of users with pagination. """ - result = await db.execute(select(User).offset(skip).limit(limit)) - return result.scalars().all() + # Check if db has execute method (AsyncSession) + if hasattr(db, "execute"): + result = await db.execute(select(User).offset(skip).limit(limit)) + return result.scalars().all() + # Synchronous operation + return db.query(User).offset(skip).limit(limit).all() -async def create(db: AsyncSession, *, obj_in: UserCreate) -> User: +async def create(db: Session, *, obj_in: UserCreate) -> User: """ Create a new user. """ @@ -46,13 +62,25 @@ async def create(db: AsyncSession, *, obj_in: UserCreate) -> User: email_verified=False, ) db.add(db_obj) - await db.commit() - await db.refresh(db_obj) + + # Check if db has commit method that's a coroutine + if ( + hasattr(db, "commit") + and callable(db.commit) + and hasattr(db.commit, "__await__") + ): + await db.commit() + await db.refresh(db_obj) + else: + # Synchronous operation + db.commit() + db.refresh(db_obj) + return db_obj async def update( - db: AsyncSession, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]] + db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]] ) -> User: """ Update a user. @@ -60,7 +88,7 @@ async def update( if isinstance(obj_in, dict): update_data = obj_in else: - update_data = obj_in.dict(exclude_unset=True) + update_data = obj_in.model_dump(exclude_unset=True) if "password" in update_data and update_data["password"]: hashed_password = get_password_hash(update_data["password"]) @@ -72,25 +100,44 @@ async def update( setattr(db_obj, field, update_data[field]) db.add(db_obj) - await db.commit() - await db.refresh(db_obj) + + # Check if db has commit method that's a coroutine + if ( + hasattr(db, "commit") + and callable(db.commit) + and hasattr(db.commit, "__await__") + ): + await db.commit() + await db.refresh(db_obj) + else: + # Synchronous operation + db.commit() + db.refresh(db_obj) + return db_obj -async def remove(db: AsyncSession, *, id: str) -> Optional[User]: +async def remove(db: Session, *, id: str) -> Optional[User]: """ Delete a user. """ user = await get_by_id(db, id) if user: - await db.delete(user) - await db.commit() + if ( + hasattr(db, "delete") + and callable(db.delete) + and hasattr(db.delete, "__await__") + ): + await db.delete(user) + await db.commit() + else: + # Synchronous operation + db.delete(user) + db.commit() return user -async def authenticate( - db: AsyncSession, *, email: str, password: str -) -> Optional[User]: +async def authenticate(db: Session, *, email: str, password: str) -> Optional[User]: """ Authenticate a user by email and password. """ @@ -102,12 +149,24 @@ async def authenticate( return user -async def update_last_login(db: AsyncSession, *, user: User) -> User: +async def update_last_login(db: Session, *, user: User) -> User: """ Update the last login timestamp for a user. """ user.last_login = datetime.utcnow() db.add(user) - await db.commit() - await db.refresh(user) + + # Check if db has commit method that's a coroutine + if ( + hasattr(db, "commit") + and callable(db.commit) + and hasattr(db.commit, "__await__") + ): + await db.commit() + await db.refresh(user) + else: + # Synchronous operation + db.commit() + db.refresh(user) + return user diff --git a/requirements.txt b/requirements.txt index 4b67f64..0ed699c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,4 +8,5 @@ python-jose[cryptography]>=3.3.0 passlib[bcrypt]>=1.7.4 python-multipart>=0.0.6 email-validator>=2.0.0 +aiosqlite>=0.19.0 ruff>=0.0.290 \ No newline at end of file