recopytex/backend/repository/student_sqlite_repository.py

70 lines
1.9 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,
},
)
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:
tribe = next(filter(lambda t: t.name == row[2], tribes))
return Student(id=row[0], name=row[1], tribe=tribe)
raise ValueError(f"The student ({id=}) does not exists")
def list(self) -> list[Student]:
cursor = self.conn.cursor()
cursor.execute(
"""
SELECT * FROM students
"""
)
rows = cursor.fetchall()
return [Student(*r) for r in rows]
def delete(self, student: Student) -> None:
self.conn.execute(
"""
DELETE FROM students WHERE name=:name
""",
{
"name": student.name,
},
)