2022-09-08 01:08:37 +00:00
|
|
|
from typing import List, Optional, cast
|
2022-08-06 06:36:44 +00:00
|
|
|
|
|
|
|
from sqlalchemy import select
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
2022-09-08 01:08:37 +00:00
|
|
|
from core.base.mysql import MySQL
|
2022-08-06 06:36:44 +00:00
|
|
|
from .models import Sign
|
|
|
|
|
|
|
|
|
|
|
|
class SignRepository:
|
|
|
|
def __init__(self, mysql: MySQL):
|
|
|
|
self.mysql = mysql
|
|
|
|
|
|
|
|
async def add(self, sign: Sign):
|
|
|
|
async with self.mysql.Session() as session:
|
|
|
|
session = cast(AsyncSession, session)
|
|
|
|
session.add(sign)
|
|
|
|
await session.commit()
|
|
|
|
|
2022-08-06 07:21:18 +00:00
|
|
|
async def remove(self, sign: Sign):
|
|
|
|
async with self.mysql.Session() as session:
|
|
|
|
session = cast(AsyncSession, session)
|
|
|
|
await session.delete(sign)
|
|
|
|
await session.commit()
|
|
|
|
|
2022-08-06 06:36:44 +00:00
|
|
|
async def update(self, sign: Sign):
|
|
|
|
async with self.mysql.Session() as session:
|
|
|
|
session = cast(AsyncSession, session)
|
|
|
|
session.add(sign)
|
|
|
|
await session.commit()
|
|
|
|
await session.refresh(sign)
|
|
|
|
|
|
|
|
async def get_by_user_id(self, user_id: int) -> Optional[Sign]:
|
|
|
|
async with self.mysql.Session() as session:
|
|
|
|
session = cast(AsyncSession, session)
|
|
|
|
statement = select(Sign).where(Sign.user_id == user_id)
|
|
|
|
results = await session.exec(statement)
|
2022-08-06 07:21:18 +00:00
|
|
|
return sign[0] if (sign := results.first()) else None
|
2022-08-06 06:36:44 +00:00
|
|
|
|
2022-10-12 12:11:54 +00:00
|
|
|
async def get_by_chat_id(self, chat_id: int) -> Optional[List[Sign]]:
|
|
|
|
async with self.mysql.Session() as session:
|
|
|
|
session = cast(AsyncSession, session)
|
|
|
|
statement = select(Sign).where(Sign.chat_id == chat_id)
|
|
|
|
results = await session.exec(statement)
|
|
|
|
signs = results.all()
|
|
|
|
return [sign[0] for sign in signs]
|
|
|
|
|
2022-08-06 06:36:44 +00:00
|
|
|
async def get_all(self) -> List[Sign]:
|
|
|
|
async with self.mysql.Session() as session:
|
|
|
|
query = select(Sign)
|
|
|
|
results = await session.exec(query)
|
|
|
|
signs = results.all()
|
|
|
|
return [sign[0] for sign in signs]
|