Initial commit
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
"""SQLite implementation of UserRepository."""
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
import aiosqlite
|
||||
|
||||
from app.entities.user import User
|
||||
from app.repositories.user_repository import UserRepository
|
||||
from app.utils.errors import NotFoundError
|
||||
|
||||
|
||||
class SQLiteUserRepository(UserRepository):
|
||||
def __init__(self, connection: aiosqlite.Connection) -> None:
|
||||
self._conn = connection
|
||||
|
||||
@staticmethod
|
||||
def _row_to_entity(row: aiosqlite.Row) -> User:
|
||||
return User(
|
||||
id=UUID(row["id"]),
|
||||
personal_data_uuid=UUID(row["personal_data_uuid"]),
|
||||
email=row["email"],
|
||||
hashed_password=row["hashed_password"],
|
||||
created_at=datetime.fromisoformat(row["created_at"]),
|
||||
)
|
||||
|
||||
async def create(self, item: User) -> User:
|
||||
now = datetime.now()
|
||||
item.created_at = item.created_at or now
|
||||
await self._conn.execute(
|
||||
"""
|
||||
INSERT INTO "user" (id, personal_data_uuid, email, hashed_password, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
str(item.id),
|
||||
str(item.personal_data_uuid),
|
||||
item.email,
|
||||
item.hashed_password,
|
||||
item.created_at.isoformat(),
|
||||
),
|
||||
)
|
||||
await self._conn.commit()
|
||||
return item
|
||||
|
||||
async def get_by_id(self, id: UUID) -> User | None:
|
||||
cursor = await self._conn.execute('SELECT * FROM "user" WHERE id = ?', (str(id),))
|
||||
row = await cursor.fetchone()
|
||||
return self._row_to_entity(row) if row else None
|
||||
|
||||
async def get_by_email(self, email: str) -> User | None:
|
||||
cursor = await self._conn.execute('SELECT * FROM "user" WHERE email = ?', (email,))
|
||||
row = await cursor.fetchone()
|
||||
return self._row_to_entity(row) if row else None
|
||||
|
||||
async def update(self, id: UUID, item: User) -> User:
|
||||
cursor = await self._conn.execute(
|
||||
'UPDATE "user" SET email = ?, hashed_password = ? WHERE id = ?',
|
||||
(item.email, item.hashed_password, str(id)),
|
||||
)
|
||||
await self._conn.commit()
|
||||
if cursor.rowcount == 0:
|
||||
raise NotFoundError(f"User {id} not found")
|
||||
refreshed = await self.get_by_id(id)
|
||||
assert refreshed is not None
|
||||
return refreshed
|
||||
|
||||
async def delete(self, id: UUID) -> None:
|
||||
cursor = await self._conn.execute('DELETE FROM "user" WHERE id = ?', (str(id),))
|
||||
await self._conn.commit()
|
||||
if cursor.rowcount == 0:
|
||||
raise NotFoundError(f"User {id} not found")
|
||||
|
||||
async def list(self, **filters: object) -> list[User]:
|
||||
cursor = await self._conn.execute('SELECT * FROM "user"')
|
||||
rows = await cursor.fetchall()
|
||||
return [self._row_to_entity(r) for r in rows]
|
||||
Reference in New Issue
Block a user