recopytex/backend/repository/student_sqlite_repository.py

106 lines
2.8 KiB
Python
Raw Permalink Normal View History

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(
"""
2022-12-30 09:34:20 +00:00
SELECT id FROM students WHERE id=:id
""",
{"id": student.id},
).fetchone()
2022-12-30 09:34:20 +00:00
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,
},
)
2022-12-27 07:41:59 +00:00
def _rebuild_student(self, row: tuple, tribes: list[Tribe]) -> Student:
print(row)
print([t.name for t in tribes])
2022-12-27 07:41:59 +00:00
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 list_id(self):
cursor = self.conn.cursor()
cursor.execute(
"""
SELECT id FROM students
"""
)
rows = cursor.fetchall()
return [r[0] for r in rows]
def delete(self, id: str) -> None:
students_id = self.list_id()
if id not in students_id:
raise StudentRepositoryError(
f"The student {id} doesn't exists. Can't delete it."
)
self.conn.execute(
"""
2022-12-27 07:41:59 +00:00
DELETE FROM students WHERE id=:id
""",
{
"id": id,
},
)