from datetime import datetime from uuid import UUID from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from ..db.models import Chat, ChatMember, User async def create_atomic( db: AsyncSession, title: str, member_ids: list[UUID] ) -> Chat: async with db.begin(): found = ( (await db.execute(select(User.id).where(User.id.in_(member_ids)))) .scalars() .all() ) if len(set(found)) != len(set(member_ids)): raise ValueError("member_not_found") chat = Chat(title=title) db.add(chat) await db.flush() for uid in member_ids: db.add(ChatMember(chat_id=chat.id, user_id=uid)) await db.refresh(chat) return chat async def get_if_member( db: AsyncSession, chat_id: UUID, user_id: UUID ) -> Chat | None: stmt = ( select(Chat) .join(ChatMember, ChatMember.chat_id == Chat.id) .where(Chat.id == chat_id, ChatMember.user_id == user_id) ) return (await db.execute(stmt)).scalar_one_or_none() async def list_member_ids(db: AsyncSession, chat_id: UUID) -> list[UUID]: stmt = select(ChatMember.user_id).where(ChatMember.chat_id == chat_id) return list((await db.execute(stmt)).scalars().all()) async def list_for_user( db: AsyncSession, user_id: UUID, limit: int, cursor: tuple[datetime, UUID] | None, ) -> tuple[list[Chat], tuple[datetime, UUID] | None]: stmt = ( select(Chat) .join(ChatMember, ChatMember.chat_id == Chat.id) .where(ChatMember.user_id == user_id) .order_by(Chat.created_at.asc(), Chat.id.asc()) .limit(limit + 1) ) if cursor is not None: c_created, c_id = cursor stmt = stmt.where( (Chat.created_at > c_created) | ((Chat.created_at == c_created) & (Chat.id > c_id)) ) rows = list((await db.execute(stmt)).scalars().all()) next_cursor = None if len(rows) > limit: rows = rows[:limit] last = rows[-1] next_cursor = (last.created_at, last.id) return rows, next_cursor