didier/database/crud/users.py

48 lines
1.1 KiB
Python
Raw Normal View History

2022-06-30 21:17:48 +02:00
from typing import Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
2022-07-11 22:23:38 +02:00
from database.models import Bank, NightlyData, User
__all__ = [
"get_or_add",
]
2022-06-30 21:17:48 +02:00
async def get_or_add(session: AsyncSession, user_id: int, *, options: Optional[list] = None) -> User:
2022-06-30 21:17:48 +02:00
"""Get a user's profile
If it doesn't exist yet, create it (along with all linked datastructures)
2022-06-30 21:17:48 +02:00
"""
if options is None:
options = []
statement = select(User).where(User.user_id == user_id).options(*options)
2022-06-30 21:17:48 +02:00
user: Optional[User] = (await session.execute(statement)).scalar_one_or_none()
# User exists
if user is not None:
return user
# Create new user
user = User(user_id=user_id)
session.add(user)
await session.commit()
# Add bank & nightly info
bank = Bank(user_id=user_id)
nightly_data = NightlyData(user_id=user_id)
user.bank = bank
user.nightly_data = nightly_data
session.add(bank)
session.add(nightly_data)
session.add(user)
await session.commit()
await session.refresh(user)
2022-06-30 21:17:48 +02:00
return user