-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathuser_data_mapper_sqla.py
More file actions
64 lines (50 loc) · 1.98 KB
/
user_data_mapper_sqla.py
File metadata and controls
64 lines (50 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from sqlalchemy import Select, select
from sqlalchemy.exc import SQLAlchemyError
from app.application.common.ports.user_command_gateway import UserCommandGateway
from app.domain.entities.user import User
from app.domain.value_objects.user_id import UserId
from app.domain.value_objects.username.username import Username
from app.infrastructure.adapters.constants import DB_QUERY_FAILED
from app.infrastructure.adapters.types import MainAsyncSession
from app.infrastructure.exceptions.gateway import DataMapperError
class SqlaUserDataMapper(UserCommandGateway):
def __init__(self, session: MainAsyncSession):
self._session = session
def add(self, user: User) -> None:
"""
:raises DataMapperError:
"""
try:
self._session.add(user)
except SQLAlchemyError as error:
raise DataMapperError(DB_QUERY_FAILED) from error
async def read_by_id(self, user_id: UserId) -> User | None:
"""
:raises DataMapperError:
"""
select_stmt: Select[tuple[User]] = select(User).where(User.id_ == user_id) # type: ignore
try:
user: User | None = (
await self._session.execute(select_stmt)
).scalar_one_or_none()
return user
except SQLAlchemyError as error:
raise DataMapperError(DB_QUERY_FAILED) from error
async def read_by_username(
self,
username: Username,
for_update: bool = False,
) -> User | None:
"""
:raises DataMapperError:
"""
select_stmt: Select[tuple[User]] = select(User).where(User.username == username) # type: ignore
if for_update:
select_stmt = select_stmt.with_for_update()
try:
user: User | None = (
await self._session.execute(select_stmt)
).scalar_one_or_none()
return user
except SQLAlchemyError as error:
raise DataMapperError(DB_QUERY_FAILED) from error