Coverage for kwai/modules/identity/users/user_account_db_repository.py: 100%
32 statements
« prev ^ index » next coverage.py v7.3.0, created at 2023-09-05 17:55 +0000
« prev ^ index » next coverage.py v7.3.0, created at 2023-09-05 17:55 +0000
1"""Module that implements a user account repository for a database."""
2from kwai.core.db.database import Database
3from kwai.core.domain.entity import Entity
4from kwai.core.domain.value_objects.email_address import EmailAddress
5from kwai.modules.identity.users.user import UserIdentifier
6from kwai.modules.identity.users.user_account import (
7 UserAccountEntity,
8 UserAccountIdentifier,
9)
10from kwai.modules.identity.users.user_account_repository import (
11 UserAccountNotFoundException,
12 UserAccountRepository,
13)
14from kwai.modules.identity.users.user_tables import (
15 UserAccountRow,
16 UserAccountsTable,
17)
20class UserAccountDbRepository(UserAccountRepository):
21 """User account repository for a database."""
23 def __init__(self, database: Database):
24 self._database = database
26 async def get_user_by_email(self, email: EmailAddress) -> UserAccountEntity:
27 query = (
28 self._database.create_query_factory()
29 .select()
30 .from_(UserAccountsTable.table_name)
31 .columns(*UserAccountsTable.aliases())
32 .and_where(UserAccountsTable.field("email").eq(str(email)))
33 )
34 row = await self._database.fetch_one(query)
35 if row:
36 return UserAccountsTable(row).create_entity()
38 raise UserAccountNotFoundException()
40 async def exists_with_email(self, email: EmailAddress) -> bool:
41 try:
42 await self.get_user_by_email(email)
43 except UserAccountNotFoundException:
44 return False
46 return True
48 async def create(self, user_account: UserAccountEntity) -> UserAccountEntity:
49 new_id = await self._database.insert(
50 UserAccountsTable.table_name, UserAccountRow.persist(user_account)
51 )
52 await self._database.commit()
53 return Entity.replace(
54 user_account,
55 id_=UserAccountIdentifier(new_id),
56 user=Entity.replace(user_account.user, id_=UserIdentifier(new_id)),
57 )
59 async def update(self, user_account: UserAccountEntity):
60 await self._database.update(
61 user_account.id.value,
62 UserAccountsTable.table_name,
63 UserAccountRow.persist(user_account),
64 )
65 await self._database.commit()
67 async def delete(self, user_account):
68 await self._database.delete(user_account.id.value, UserAccountsTable.table_name)
69 await self._database.commit()