"""Base repository.""" from typing import Type, TypeVar, Optional, List from sqlalchemy.orm import Session from sqlalchemy import select T = TypeVar("T") class BaseRepository: """Base repository class.""" def __init__(self, model: Type[T], db: Session): self.model = model self.db = db def get_by_id(self, id: int) -> Optional[T]: """Get entity by ID.""" return self.db.query(self.model).filter(self.model.id == id).first() def get_all( self, page: int = 1, page_size: int = 10, **filters ) -> tuple[List[T], int]: """Get all entities with pagination and filters.""" query = self.db.query(self.model) # Apply filters for attr, value in filters.items(): if hasattr(self.model, attr) and value is not None: query = query.filter(getattr(self.model, attr) == value) # Get total count total = query.count() # Get paginated results entities = query.order_by(self.model.id.desc()).offset((page - 1) * page_size).limit(page_size).all() return entities, total def create(self, **kwargs) -> T: """Create new entity.""" entity = self.model(**kwargs) self.db.add(entity) self.db.commit() self.db.refresh(entity) return entity def update(self, id: int, **kwargs) -> Optional[T]: """Update entity.""" entity = self.get_by_id(id) if entity: for key, value in kwargs.items(): if hasattr(entity, key): setattr(entity, key, value) self.db.commit() self.db.refresh(entity) return entity def delete(self, id: int) -> bool: """Delete entity.""" entity = self.get_by_id(id) if entity: self.db.delete(entity) self.db.commit() return True return False def exists(self, id: int) -> bool: """Check if entity exists.""" return self.db.query(self.model).filter(self.model.id == id).first() is not None