Coverage for src/kwai/modules/identity/users/user_db_repository.py: 91%
35 statements
« prev ^ index » next coverage.py v7.6.10, created at 2024-01-01 00:00 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2024-01-01 00:00 +0000
1"""Module for implementing a user repository with a database."""
3from kwai.core.db.database import Database
4from kwai.core.domain.value_objects.email_address import EmailAddress
5from kwai.core.domain.value_objects.unique_id import UniqueId
6from kwai.modules.identity.users.user import UserEntity, UserIdentifier
7from kwai.modules.identity.users.user_db_query import UserDbQuery
8from kwai.modules.identity.users.user_repository import (
9 UserNotFoundException,
10 UserRepository,
11)
12from kwai.modules.identity.users.user_tables import UserRow
15class UserDbRepository(UserRepository):
16 """Database repository for the user entity."""
18 def __init__(self, database: Database):
19 self._database = database
21 async def update(self, user: UserEntity) -> None:
22 await self._database.update(
23 user.id.value, UserRow.__table_name__, UserRow.persist(user)
24 )
26 def create_query(self) -> UserDbQuery:
27 """Create a user database query."""
28 return UserDbQuery(self._database)
30 async def get_user_by_id(self, id_: UserIdentifier) -> UserEntity:
31 """Get the user with the given id.
33 UserNotFoundException is raised when the user does not exist.
34 """
35 query = self.create_query()
36 query.filter_by_id(id_)
38 row = await query.fetch_one()
39 if row:
40 return UserRow.map(row).create_entity()
42 raise UserNotFoundException()
44 async def get_user_by_uuid(self, uuid: UniqueId) -> UserEntity:
45 """Get the user with the given uuid.
47 UserNotFoundException is raised when the user does not exist.
48 """
49 query = self.create_query()
50 query.filter_by_uuid(uuid)
52 row = await query.fetch_one()
53 if row:
54 return UserRow.map(row).create_entity()
56 raise UserNotFoundException()
58 async def get_user_by_email(self, email: EmailAddress) -> UserEntity:
59 """Get the user with the given email.
61 UserNotFoundException is raised when the user does not exist.
62 """
63 query = self.create_query()
64 query.filter_by_email(email)
66 row = await query.fetch_one()
67 if row:
68 return UserRow.map(row).create_entity()
70 raise UserNotFoundException()