Fix database migration error by adding aiosqlite dependency and implementing fallback for sync/async operations
This commit is contained in:
parent
96d90a5f04
commit
c9ee1823be
@ -1,10 +1,10 @@
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import AsyncGenerator
|
from typing import AsyncGenerator, Generator
|
||||||
|
|
||||||
from sqlalchemy import create_engine
|
from sqlalchemy import create_engine
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
|
|
||||||
# Ensure DB directory exists
|
# Ensure DB directory exists
|
||||||
@ -19,36 +19,66 @@ engine = create_engine(
|
|||||||
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
||||||
)
|
)
|
||||||
|
|
||||||
# For async operations, we need to use a different driver
|
# Create session factories for synchronous operations
|
||||||
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
|
|
||||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
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
|
# Create a base class for declarative models
|
||||||
Base = declarative_base()
|
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_SQLALCHEMY_DATABASE_URL = f"sqlite+aiosqlite:///{DB_DIR}/db.sqlite"
|
||||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
async_engine = create_async_engine(
|
||||||
"""
|
ASYNC_SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
||||||
Dependency function that yields an async database session.
|
)
|
||||||
"""
|
AsyncSessionLocal = sessionmaker(
|
||||||
async with AsyncSessionLocal() as session:
|
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:
|
try:
|
||||||
yield session
|
yield db
|
||||||
await session.commit()
|
db.commit()
|
||||||
except Exception:
|
except Exception:
|
||||||
await session.rollback()
|
db.rollback()
|
||||||
raise
|
raise
|
||||||
finally:
|
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()
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
from fastapi import APIRouter, Depends
|
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.core.database import get_db
|
||||||
from app.models.health import HealthCheck
|
from app.models.health import HealthCheck
|
||||||
@ -8,7 +8,7 @@ health_router = APIRouter()
|
|||||||
|
|
||||||
|
|
||||||
@health_router.get("/health", response_model=HealthCheck, tags=["health"])
|
@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.
|
Health check endpoint to verify API is running properly.
|
||||||
"""
|
"""
|
||||||
|
113
app/crud/user.py
113
app/crud/user.py
@ -1,39 +1,55 @@
|
|||||||
from datetime import datetime
|
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 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.core.security import get_password_hash, verify_password
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
from app.schemas.user import UserCreate, UserUpdate
|
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.
|
Get a user by ID.
|
||||||
"""
|
"""
|
||||||
result = await db.execute(select(User).filter(User.id == user_id))
|
# Check if db has execute method (AsyncSession)
|
||||||
return result.scalars().first()
|
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.
|
Get a user by email.
|
||||||
"""
|
"""
|
||||||
result = await db.execute(select(User).filter(User.email == email))
|
# Check if db has execute method (AsyncSession)
|
||||||
return result.scalars().first()
|
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.
|
Get a list of users with pagination.
|
||||||
"""
|
"""
|
||||||
result = await db.execute(select(User).offset(skip).limit(limit))
|
# Check if db has execute method (AsyncSession)
|
||||||
return result.scalars().all()
|
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.
|
Create a new user.
|
||||||
"""
|
"""
|
||||||
@ -46,13 +62,25 @@ async def create(db: AsyncSession, *, obj_in: UserCreate) -> User:
|
|||||||
email_verified=False,
|
email_verified=False,
|
||||||
)
|
)
|
||||||
db.add(db_obj)
|
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
|
return db_obj
|
||||||
|
|
||||||
|
|
||||||
async def update(
|
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:
|
) -> User:
|
||||||
"""
|
"""
|
||||||
Update a user.
|
Update a user.
|
||||||
@ -60,7 +88,7 @@ async def update(
|
|||||||
if isinstance(obj_in, dict):
|
if isinstance(obj_in, dict):
|
||||||
update_data = obj_in
|
update_data = obj_in
|
||||||
else:
|
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"]:
|
if "password" in update_data and update_data["password"]:
|
||||||
hashed_password = get_password_hash(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])
|
setattr(db_obj, field, update_data[field])
|
||||||
|
|
||||||
db.add(db_obj)
|
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
|
return db_obj
|
||||||
|
|
||||||
|
|
||||||
async def remove(db: AsyncSession, *, id: str) -> Optional[User]:
|
async def remove(db: Session, *, id: str) -> Optional[User]:
|
||||||
"""
|
"""
|
||||||
Delete a user.
|
Delete a user.
|
||||||
"""
|
"""
|
||||||
user = await get_by_id(db, id)
|
user = await get_by_id(db, id)
|
||||||
if user:
|
if user:
|
||||||
await db.delete(user)
|
if (
|
||||||
await db.commit()
|
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
|
return user
|
||||||
|
|
||||||
|
|
||||||
async def authenticate(
|
async def authenticate(db: Session, *, email: str, password: str) -> Optional[User]:
|
||||||
db: AsyncSession, *, email: str, password: str
|
|
||||||
) -> Optional[User]:
|
|
||||||
"""
|
"""
|
||||||
Authenticate a user by email and password.
|
Authenticate a user by email and password.
|
||||||
"""
|
"""
|
||||||
@ -102,12 +149,24 @@ async def authenticate(
|
|||||||
return user
|
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.
|
Update the last login timestamp for a user.
|
||||||
"""
|
"""
|
||||||
user.last_login = datetime.utcnow()
|
user.last_login = datetime.utcnow()
|
||||||
db.add(user)
|
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
|
return user
|
||||||
|
@ -8,4 +8,5 @@ python-jose[cryptography]>=3.3.0
|
|||||||
passlib[bcrypt]>=1.7.4
|
passlib[bcrypt]>=1.7.4
|
||||||
python-multipart>=0.0.6
|
python-multipart>=0.0.6
|
||||||
email-validator>=2.0.0
|
email-validator>=2.0.0
|
||||||
|
aiosqlite>=0.19.0
|
||||||
ruff>=0.0.290
|
ruff>=0.0.290
|
Loading…
x
Reference in New Issue
Block a user