from backend.model.student import Student from backend.model.tribe import Tribe from backend.repository.abstract_repository import AbstractRepository class StudentRepositoryError(Exception): pass 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, student: Student) -> None: search_student = self.conn.execute( """ SELECT id FROM students WHERE id=:id """, {"id": student.id}, ).fetchone() if search_student is None: raise StudentRepositoryError(f"The student ({student.id=}) does not exists") self.conn.execute( """ UPDATE students SET name=:newname, tribe_name=:newtribe WHERE id=:id """, { "newname": student.name, "newtribe": student.tribe.name, "id": student.id, }, ) def _rebuild_student(self, row: tuple, tribes: list[Tribe]) -> Student: print(row) print([t.name for t in tribes]) 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: return self._rebuild_student(row, tribes) raise ValueError(f"The student ({id=}) does not exists") def list(self, tribes: list[Tribe]) -> list[Student]: cursor = self.conn.cursor() cursor.execute( """ SELECT * FROM students """ ) rows = cursor.fetchall() return [self._rebuild_student(r, tribes) for r in rows] def delete(self, student: Student) -> None: self.conn.execute( """ DELETE FROM students WHERE id=:id """, { "id": student.id, }, )