11import sqlalchemy as sa
22from models_library .products import ProductName
33from models_library .users import UserID
4+ from notifications_library ._models import UserData
45from simcore_postgres_database .models .jinja2_templates import jinja2_templates
56from simcore_postgres_database .models .products_to_templates import products_to_templates
67from simcore_postgres_database .models .users import users
8+ from simcore_postgres_database .utils_repos import pass_or_acquire_connection
79from sqlalchemy .ext .asyncio import AsyncEngine
810
911
@@ -12,26 +14,31 @@ def __init__(self, db_engine: AsyncEngine):
1214 assert db_engine is not None # nosec
1315 self .db_engine = db_engine
1416
15- async def _get (self , query ):
16- async with self .db_engine .begin () as conn :
17+
18+ class UsersRepo (_BaseRepo ):
19+ async def get_user_data (self , user_id : UserID ) -> UserData :
20+ query = sa .select (
21+ # NOTE: careful! privacy applies here!
22+ users .c .first_name ,
23+ users .c .last_name ,
24+ users .c .email ,
25+ ).where (users .c .id == user_id )
26+ async with pass_or_acquire_connection (self .db_engine ) as conn :
1727 result = await conn .execute (query )
18- return result .first ()
28+ row = result .one_or_none ()
1929
30+ if row is None :
31+ msg = f"User not found { user_id = } "
32+ raise ValueError (msg )
2033
21- class UsersRepo (_BaseRepo ):
22- async def get_user_data (self , user_id : UserID ):
23- return await self ._get (
24- sa .select (
25- users .c .first_name ,
26- users .c .last_name ,
27- users .c .email ,
28- ).where (users .c .id == user_id )
34+ return UserData (
35+ first_name = row .first_name , last_name = row .last_name , email = row .email
2936 )
3037
3138
3239class TemplatesRepo (_BaseRepo ):
3340 async def iter_email_templates (self , product_name : ProductName ):
34- async with self .db_engine . begin ( ) as conn :
41+ async with pass_or_acquire_connection ( self .db_engine ) as conn :
3542 async for row in await conn .stream (
3643 sa .select (
3744 jinja2_templates .c .name ,
@@ -46,7 +53,7 @@ async def iter_email_templates(self, product_name: ProductName):
4653 yield row
4754
4855 async def iter_product_templates (self , product_name : ProductName ):
49- async with self .db_engine . begin ( ) as conn :
56+ async with pass_or_acquire_connection ( self .db_engine ) as conn :
5057 async for row in await conn .stream (
5158 sa .select (
5259 products_to_templates .c .product_name ,
0 commit comments