2023-03-14 01:27:22 +00:00
|
|
|
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
|
2023-03-14 01:27:22 +00:00
|
|
|
from core.sqlmodel.session import AsyncSession
|
|
|
|
|
2023-07-23 15:46:11 +00:00
|
|
|
__all__ = ("TaskRepository",)
|
2023-03-14 01:27:22 +00:00
|
|
|
|
|
|
|
|
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-03-14 01:27:22 +00:00
|
|
|
|
2023-07-23 15:46:11 +00:00
|
|
|
async def add(self, task: Task):
|
2023-03-14 01:27:22 +00:00
|
|
|
async with AsyncSession(self.engine) as session:
|
2023-07-23 15:46:11 +00:00
|
|
|
session.add(task)
|
2023-03-14 01:27:22 +00:00
|
|
|
await session.commit()
|
|
|
|
|
2023-07-23 15:46:11 +00:00
|
|
|
async def remove(self, task: Task):
|
2023-03-14 01:27:22 +00:00
|
|
|
async with AsyncSession(self.engine) as session:
|
2023-07-23 15:46:11 +00:00
|
|
|
await session.delete(task)
|
2023-03-14 01:27:22 +00:00
|
|
|
await session.commit()
|
|
|
|
|
2023-07-23 15:46:11 +00:00
|
|
|
async def update(self, task: Task) -> Task:
|
2023-03-14 01:27:22 +00:00
|
|
|
async with AsyncSession(self.engine) as session:
|
2023-07-23 15:46:11 +00:00
|
|
|
session.add(task)
|
2023-03-14 01:27:22 +00:00
|
|
|
await session.commit()
|
2023-07-23 15:46:11 +00:00
|
|
|
await session.refresh(task)
|
|
|
|
return task
|
2023-03-14 01:27:22 +00:00
|
|
|
|
2023-07-23 15:46:11 +00:00
|
|
|
async def get_by_user_id(self, user_id: int, task_type: TaskTypeEnum) -> Optional[Task]:
|
2023-03-14 01:27:22 +00:00
|
|
|
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)
|
2023-03-14 01:27:22 +00:00
|
|
|
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]]:
|
2023-03-14 01:27:22 +00:00
|
|
|
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)
|
2023-03-14 01:27:22 +00:00
|
|
|
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]:
|
2023-03-14 01:27:22 +00:00
|
|
|
async with AsyncSession(self.engine) as session:
|
2023-07-23 15:46:11 +00:00
|
|
|
query = select(Task).where(Task.type == task_type)
|
2023-03-14 01:27:22 +00:00
|
|
|
results = await session.exec(query)
|
|
|
|
return results.all()
|