Feat: add get method for student repository
This commit is contained in:
@@ -14,5 +14,20 @@ def create_tribe_table(conn) -> None:
|
||||
conn.commit()
|
||||
|
||||
|
||||
def create_student_table(conn) -> None:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS students(
|
||||
id VARCHAR(500) PRIMARY KEY UNIQUE,
|
||||
name VARCHAR,
|
||||
tribe_name VARCHAR
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def create_db(conn) -> None:
|
||||
create_tribe_table(conn)
|
||||
create_student_table(conn)
|
||||
|
69
backend/repository/student_sqlite_repository.py
Normal file
69
backend/repository/student_sqlite_repository.py
Normal file
@@ -0,0 +1,69 @@
|
||||
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,
|
||||
},
|
||||
)
|
Reference in New Issue
Block a user