from sqlalchemy import select
from .repobase import RepoBase

__all__ = ['CRUDRepo']



class CRUDRepo(RepoBase):
    
    async def get_all(self, entity_class, **kwargs):
        stmt = select(entity_class).filter_by(**kwargs)
        result = await self._s.execute(stmt)
        return result.scalars().all()
    
    
    async def get_first(self, entity_class, **kwargs):
        stmt = select(entity_class).filter_by(**kwargs)
        result = await self._s.execute(stmt)
        return result.scalars().first()
    
    
    async def create_if_none(self, ormobj, **kwargs):
        stmt = select(ormobj.__class__).filter_by(**kwargs)
        result = await self._s.execute(stmt)
        obj = result.scalars().first()
        if not obj:
            obj = ormobj
            self._s.add(obj)
        return obj
    
    
    async def create(self, *args):
        for arg in args:
            await self._s.merge(arg)
    
    
    async def update(self, *args):
        for arg in args:
            await self._s.merge(arg)
    
    
    async def upsert(self, *args):
        for arg in args:
            await self._s.merge(arg)
    
    
    async def delete(self, *args):
        for arg in args:
            self._s.delete(arg)
