76 lines
3.0 KiB
Python
76 lines
3.0 KiB
Python
from abc import ABC, abstractmethod
|
|
from typing import Tuple
|
|
|
|
from sqlalchemy import select, update
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import tbl_account
|
|
from common.enums import ErrorType
|
|
from common.logger import LOG
|
|
from common.utils.gtime import GTime
|
|
|
|
|
|
# CRUD 는 인터페이스(I*) 와 구현(*) 으로 분리한다.
|
|
# - service 는 인터페이스 타입에 의존하고 Depends 로 구현을 주입받는다 (테스트/교체 용이).
|
|
# - 모든 메서드는 (session, ...) 을 받는다. session 은 람다 호출 시 매니저가 넘겨준다.
|
|
class IUserCRUD(ABC):
|
|
@abstractmethod
|
|
async def get_account_by_id(self, cdb: AsyncSession, user_id: str) -> Tuple[ErrorType, tbl_account]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def is_account(self, cdb: AsyncSession, user_id: str) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def add_account(self, cdb: AsyncSession, account: tbl_account) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def update_last_login(self, cdb: AsyncSession, user_uid: int) -> ErrorType:
|
|
pass
|
|
|
|
|
|
class UserCRUD(IUserCRUD):
|
|
async def get_account_by_id(self, cdb: AsyncSession, user_id: str) -> Tuple[ErrorType, tbl_account]:
|
|
try:
|
|
query = select(tbl_account).where(tbl_account.id == user_id).limit(1)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_account_by_id(ID:{user_id}) failed.")
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
if len(row_list) != 1:
|
|
return ErrorType.DB_INVALID_KEY, None
|
|
return ErrorType.SUCCESS, row_list[0]
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
async def is_account(self, cdb: AsyncSession, user_id: str) -> ErrorType:
|
|
try:
|
|
query = select(tbl_account).where(tbl_account.id == user_id).limit(1)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type
|
|
if row_list:
|
|
return ErrorType.DB_ALREADY_SAME_KEY
|
|
return ErrorType.SUCCESS
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def add_account(self, cdb: AsyncSession, account: tbl_account) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, account)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def update_last_login(self, cdb: AsyncSession, user_uid: int) -> ErrorType:
|
|
try:
|
|
query = update(tbl_account).where(tbl_account.uid == user_uid).values(last_login_at=GTime.UTC())
|
|
return await DB_SESSION_MNG.add(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|