recopytex/backend/repository/student_sqlite_repository.py

73 lines
2.0 KiB
Python
Raw Normal View History

from backend.model.student import Student
from backend.model.tribe import Tribe
from backend.repository.abstract_repository import AbstractRepository
class StudentSQLiteRepository(AbstractRepository):
def __init__(self, conn) -> None:
self.conn = conn
def add(self, student: Student) -> None:
self.conn.execute(
"""
INSERT INTO students(id, name, tribe_name) VALUES (?, ?, ?)
""",
(
student.id,
student.name,
student.tribe.name,
),
)
def update(self, name: str, student: Student) -> None:
self.conn.execute(
"""
UPDATE students SET name=:newname, tribe_name=:newtribe WHERE id=:id
""",
{
"newname": student.name,
"newtribe": student.tribe.name,
"id": student.id,
},
)
2022-12-27 07:41:59 +00:00
def _rebuild_student(self, row: tuple, tribes: list[Tribe]) -> Student:
tribe = next(filter(lambda t: t.name == row[2], tribes))
return Student(id=row[0], name=row[1], tribe=tribe)
def get(self, id: str, tribes: list[Tribe]) -> Student:
cursor = self.conn.cursor()
cursor.execute(
"""
SELECT id, name, tribe_name FROM students WHERE id=?
""",
(id,),
)
row = cursor.fetchone()
if row:
2022-12-27 07:41:59 +00:00
return self._rebuild_student(row, tribes)
raise ValueError(f"The student ({id=}) does not exists")
2022-12-27 07:41:59 +00:00
def list(self, tribes: list[Tribe]) -> list[Student]:
cursor = self.conn.cursor()
cursor.execute(
"""
SELECT * FROM students
"""
)
rows = cursor.fetchall()
2022-12-27 07:41:59 +00:00
return [self._rebuild_student(r, tribes) for r in rows]
def delete(self, student: Student) -> None:
self.conn.execute(
"""
2022-12-27 07:41:59 +00:00
DELETE FROM students WHERE id=:id
""",
{
2022-12-27 07:41:59 +00:00
"id": student.id,
},
)