90 lines
2.2 KiB
Python
90 lines
2.2 KiB
Python
from backend.model.tribe import Tribe
|
|
from backend.repository.abstract_repository import AbstractRepository
|
|
|
|
|
|
class TribeRepositoryError(Exception):
|
|
pass
|
|
|
|
|
|
class TribeSQLiteRepository(AbstractRepository):
|
|
def __init__(self, conn) -> None:
|
|
self.conn = conn
|
|
|
|
def add(self, tribe: Tribe) -> None:
|
|
tribes = self.list()
|
|
if tribe.name in map(lambda x: x.name, tribes):
|
|
raise TribeRepositoryError(
|
|
f"The tribe {tribe.name} already exists. Can't add it"
|
|
)
|
|
|
|
self.conn.execute(
|
|
"""
|
|
INSERT INTO tribes(name, level) VALUES (?, ?)
|
|
""",
|
|
(
|
|
tribe.name,
|
|
tribe.level,
|
|
),
|
|
)
|
|
|
|
def update(self, name: str, tribe: Tribe) -> None:
|
|
tribes = self.list()
|
|
|
|
if name not in map(lambda x: x.name, tribes):
|
|
raise TribeRepositoryError(
|
|
f"The tribe {name} doesn't exists. Can't update it"
|
|
)
|
|
|
|
self.conn.execute(
|
|
"""
|
|
UPDATE tribes SET name=:newname, level=:newlevel WHERE name=:name
|
|
""",
|
|
{
|
|
"newname": tribe.name,
|
|
"newlevel": tribe.level,
|
|
"name": name,
|
|
},
|
|
)
|
|
|
|
def get(self, name: str) -> Tribe:
|
|
cursor = self.conn.cursor()
|
|
cursor.execute(
|
|
"""
|
|
SELECT * FROM tribes WHERE name=?
|
|
""",
|
|
(name,),
|
|
)
|
|
|
|
row = cursor.fetchone()
|
|
if row:
|
|
return Tribe(*row)
|
|
|
|
raise TribeRepositoryError(f"The tribe {name} does not exists")
|
|
|
|
def list(self) -> list[Tribe]:
|
|
cursor = self.conn.cursor()
|
|
cursor.execute(
|
|
"""
|
|
SELECT * FROM tribes
|
|
"""
|
|
)
|
|
|
|
rows = cursor.fetchall()
|
|
return [Tribe(*r) for r in rows]
|
|
|
|
def delete(self, name: str) -> None:
|
|
tribes = self.list()
|
|
if name not in map(lambda x: x.name, tribes):
|
|
raise TribeRepositoryError(
|
|
f"The tribe {name} doesn't exists. Can't delete it."
|
|
)
|
|
|
|
self.conn.execute(
|
|
"""
|
|
DELETE FROM tribes WHERE name=:name
|
|
""",
|
|
{
|
|
"name": name,
|
|
},
|
|
)
|