MibooGram/core/services/task/repositories.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

51 lines
1.9 KiB
Python
Raw Normal View History

from typing import List, Optional
from sqlmodel import select
from core.base_service import BaseService
2023-03-25 03:17:38 +00:00
from core.dependence.database import Database
2023-07-23 15:46:11 +00:00
from core.services.task.models import Task, TaskTypeEnum
from core.sqlmodel.session import AsyncSession
2023-07-23 15:46:11 +00:00
__all__ = ("TaskRepository",)
2023-07-23 15:46:11 +00:00
class TaskRepository(BaseService.Component):
2023-03-25 03:17:38 +00:00
def __init__(self, database: Database):
self.engine = database.engine
2023-07-23 15:46:11 +00:00
async def add(self, task: Task):
async with AsyncSession(self.engine) as session:
2023-07-23 15:46:11 +00:00
session.add(task)
await session.commit()
2023-07-23 15:46:11 +00:00
async def remove(self, task: Task):
async with AsyncSession(self.engine) as session:
2023-07-23 15:46:11 +00:00
await session.delete(task)
await session.commit()
2023-07-23 15:46:11 +00:00
async def update(self, task: Task) -> Task:
async with AsyncSession(self.engine) as session:
2023-07-23 15:46:11 +00:00
session.add(task)
await session.commit()
2023-07-23 15:46:11 +00:00
await session.refresh(task)
return task
2023-07-23 15:46:11 +00:00
async def get_by_user_id(self, user_id: int, task_type: TaskTypeEnum) -> Optional[Task]:
async with AsyncSession(self.engine) as session:
2023-07-23 15:46:11 +00:00
statement = select(Task).where(Task.user_id == user_id).where(Task.type == task_type)
results = await session.exec(statement)
return results.first()
2023-07-23 15:46:11 +00:00
async def get_by_chat_id(self, chat_id: int, task_type: TaskTypeEnum) -> Optional[List[Task]]:
async with AsyncSession(self.engine) as session:
2023-07-23 15:46:11 +00:00
statement = select(Task).where(Task.chat_id == chat_id).where(Task.type == task_type)
results = await session.exec(statement)
return results.all()
2023-07-23 15:46:11 +00:00
async def get_all(self, task_type: TaskTypeEnum) -> List[Task]:
async with AsyncSession(self.engine) as session:
2023-07-23 15:46:11 +00:00
query = select(Task).where(Task.type == task_type)
results = await session.exec(query)
return results.all()