-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository.py
94 lines (68 loc) · 3.1 KB
/
repository.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
from sqlalchemy import select
from sqlalchemy.exc import NoResultFound
from database import TaskTable, new_session
from schemas import Task, TaskAdd
class TaskRepository:
@classmethod
async def add_data(cls, data: TaskAdd) -> Task:
async with new_session() as session:
task_dict = data.model_dump()
task = TaskTable(**task_dict)
session.add(task)
await session.flush()
await session.commit()
return Task.model_validate(task.__dict__)
@classmethod
async def get_data(cls) -> list[Task]:
async with new_session() as session:
query = select(TaskTable)
result = await session.execute(query)
task_models = result.scalars().all()
tasks_schemas = [Task.model_validate(task_model.__dict__) for task_model in task_models]
return tasks_schemas
@classmethod
async def get_task_by_id(cls, task_id: int) -> Task:
async with new_session() as session:
query = select(TaskTable).where(TaskTable.id == task_id)
result = await session.execute(query)
task_model = result.scalars().first()
if not task_model:
raise NoResultFound(f"Task with id {task_id} not found!")
return Task.model_validate(task_model.__dict__)
@classmethod
async def update_data(cls, task_id: int, data: TaskAdd) -> Task | None:
async with new_session() as session:
query = select(TaskTable).where(TaskTable.id == task_id)
result = await session.execute(query)
task_model = result.scalars().first()
if not task_model:
return None
for key, value in data.model_dump().items():
setattr(task_model, key, value)
await session.commit()
return Task.model_validate(task_model.__dict__)
@classmethod
async def patch_data(cls, task_id: int, data: dict) -> Task:
async with new_session() as session:
query = select(TaskTable).where(TaskTable.id == task_id)
result = await session.execute(query)
task_model = result.scalars().first()
if not task_model:
raise NoResultFound(f"Task with id {task_id} not found!")
for key, value in data.items():
if hasattr(task_model, key) and value is not None:
setattr(task_model, key, value)
await session.flush()
await session.commit()
return Task.model_validate(task_model.__dict__)
@classmethod
async def delete_data(cls, task_id: int) -> bool:
async with new_session() as session:
query = select(TaskTable).where(TaskTable.id == task_id)
result = await session.execute(query)
task_model = result.scalars().first()
if not task_model:
return False
await session.delete(task_model)
await session.commit()
return True