DB Implementations UPdated
Browse filesFiles changed (2)
- chat_manager.py+83-11
- chat_routes.py+18-8
65 unmodified lines666768697071721 unmodified line7475767778798081828384858687888993 unmodified lines1831841851861871881891901911921931941 unmodified line19619719819920020120220320486 unmodified lines291292293294295296297298299300301302303304305306307308309310311312313181 unmodified lines49549649749865 unmodified linesfinally:session.close()def add_message(self, chat_id: int, content: str, sender: str) -> Dict[str, Any]:"""Add a message to a chat.1 unmodified linechat_id: ID of the chat to add the message tocontent: Message contentsender: Message sender ('user' or 'bot')Returns:Dictionary containing message information"""session = self.Session()try:# Check if chat existschat = session.query(Chat).filter(Chat.chat_id == chat_id).first()if not chat:raise ValueError(f"Chat with ID {chat_id} not found")# Create a new messagemessage = Message(93 unmodified linesfinally:session.close()def get_chat(self, chat_id: int) -> Dict[str, Any]:"""Get a chat by ID with all its messages.Args:chat_id: ID of the chat to retrieveReturns:Dictionary containing chat information and messages1 unmodified linesession = self.Session()try:# Get the chatchat = session.query(Chat).filter(Chat.chat_id == chat_id).first()if not chat:raise ValueError(f"Chat with ID {chat_id} not found")# Get the chat messages ordered by timestampmessages = session.query(Message).filter(86 unmodified linesfinally:session.close()def delete_chat(self, chat_id: int) -> bool:"""Delete a chat and all its messages.Args:chat_id: ID of the chat to deleteReturns:True if deletion was successful, False otherwise"""session = self.Session()try:# Delete all messages in the chatsession.query(Message).filter(Message.chat_id == chat_id).delete()# Delete the chatresult = session.query(Chat).filter(Chat.chat_id == chat_id).delete()session.commit()return result > 0181 unmodified linesreturn titleexcept Exception as e:logger.error(f"Error generating title: {str(e)}")return "New Chat"65 unmodified lines666768697071721 unmodified line74757677787980818283848586878889909192939493 unmodified lines1881891901911921931941951961971981992001 unmodified line20220320420520620720820921021121221321421521686 unmodified lines303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339181 unmodified lines52152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957065 unmodified linesfinally:session.close()def add_message(self, chat_id: int, content: str, sender: str, user_id: Optional[int] = None) -> Dict[str, Any]:"""Add a message to a chat.1 unmodified linechat_id: ID of the chat to add the message tocontent: Message contentsender: Message sender ('user' or 'bot')user_id: Optional user ID to verify ownershipReturns:Dictionary containing message information"""session = self.Session()try:# Check if chat exists and belongs to the user if user_id is providedquery = session.query(Chat).filter(Chat.chat_id == chat_id)if user_id is not None:query = query.filter((Chat.user_id == user_id) | (Chat.user_id.is_(None)))chat = query.first()if not chat:raise ValueError(f"Chat with ID {chat_id} not found or access denied")# Create a new messagemessage = Message(93 unmodified linesfinally:session.close()def get_chat(self, chat_id: int, user_id: Optional[int] = None) -> Dict[str, Any]:"""Get a chat by ID with all its messages.Args:chat_id: ID of the chat to retrieveuser_id: Optional user ID to verify ownershipReturns:Dictionary containing chat information and messages1 unmodified linesession = self.Session()try:# Get the chatquery = session.query(Chat).filter(Chat.chat_id == chat_id)# If user_id is provided, ensure the chat belongs to this userif user_id is not None:query = query.filter(Chat.user_id == user_id)chat = query.first()if not chat:raise ValueError(f"Chat with ID {chat_id} not found or access denied")# Get the chat messages ordered by timestampmessages = session.query(Message).filter(86 unmodified linesfinally:session.close()def delete_chat(self, chat_id: int, user_id: Optional[int] = None) -> bool:"""Delete a chat and all its messages.Args:chat_id: ID of the chat to deleteuser_id: Optional user ID to verify ownershipReturns:True if deletion was successful, False otherwise"""session = self.Session()try:# Check if chat exists and belongs to the user if user_id is providedif user_id is not None:chat = session.query(Chat).filter(Chat.chat_id == chat_id,Chat.user_id == user_id).first()if not chat:return False # Chat not found or doesn't belong to the user# Delete all messages in the chatsession.query(Message).filter(Message.chat_id == chat_id).delete()# Delete the chat (with user_id filter if provided)query = session.query(Chat).filter(Chat.chat_id == chat_id)if user_id is not None:query = query.filter(Chat.user_id == user_id)result = query.delete()session.commit()return result > 0181 unmodified linesreturn titleexcept Exception as e:logger.error(f"Error generating title: {str(e)}")return "New Chat"def delete_empty_chats(self, user_id: Optional[int] = None, is_admin: bool = False) -> int:"""Delete empty chats (chats with no messages) for a user.Args:user_id: ID of the user whose empty chats should be deletedis_admin: Whether this is an admin userReturns:Number of chats deleted"""session = self.Session()try:# Get all chats for the userquery = session.query(Chat)if user_id is not None:query = query.filter(Chat.user_id == user_id)elif not is_admin:return 0 # Don't delete anything if not a user or admin# For each chat, check if it has any messageschats_to_delete = []for chat in query.all():message_count = session.query(Message).filter(Message.chat_id == chat.chat_id).count()if message_count == 0:chats_to_delete.append(chat.chat_id)# Delete the empty chatsif chats_to_delete:deleted = session.query(Chat).filter(Chat.chat_id.in_(chats_to_delete)).delete(synchronize_session=False)session.commit()return deletedreturn 0except SQLAlchemyError as e:session.rollback()logger.error(f"Error deleting empty chats: {str(e)}")return 0finally:session.close()
64 unmodified lines656667686970717273742 unmodified lines7778798081828384858616 unmodified lines10310410510610710810911011111211311442 unmodified lines15715815916064 unmodified linesraise HTTPException(status_code=500, detail=f"Failed to create chat: {str(e)}")@router.post("/{chat_id}/messages", response_model=MessageResponse)async def add_message(chat_id: int, message: MessageCreate):"""Add a message to a chat"""try:result = chat_manager.add_message(chat_id, message.content, message.sender)return resultexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e))2 unmodified linesraise HTTPException(status_code=500, detail=f"Failed to add message: {str(e)}")@router.get("/{chat_id}", response_model=ChatDetailResponse)async def get_chat(chat_id: int):"""Get a chat by ID with all messages"""try:chat = chat_manager.get_chat(chat_id)return chatexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e))16 unmodified linesraise HTTPException(status_code=500, detail=f"Failed to retrieve chats: {str(e)}")@router.delete("/{chat_id}")async def delete_chat(chat_id: int):"""Delete a chat and all its messages"""try:success = chat_manager.delete_chat(chat_id)if not success:raise HTTPException(status_code=404, detail=f"Chat with ID {chat_id} not found")return {"message": f"Chat {chat_id} deleted successfully"}except HTTPException:raise42 unmodified linesraise HTTPException(status_code=404, detail=str(e))except Exception as e:logger.error(f"Error updating chat: {str(e)}")raise HTTPException(status_code=500, detail=f"Failed to update chat: {str(e)}")64 unmodified lines656667686970717273742 unmodified lines7778798081828384858616 unmodified lines10310410510610710810911011111211311442 unmodified lines15715815916016116216316416516616716816917064 unmodified linesraise HTTPException(status_code=500, detail=f"Failed to create chat: {str(e)}")@router.post("/{chat_id}/messages", response_model=MessageResponse)async def add_message(chat_id: int, message: MessageCreate, user_id: Optional[int] = None):"""Add a message to a chat"""try:result = chat_manager.add_message(chat_id, message.content, message.sender, user_id)return resultexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e))2 unmodified linesraise HTTPException(status_code=500, detail=f"Failed to add message: {str(e)}")@router.get("/{chat_id}", response_model=ChatDetailResponse)async def get_chat(chat_id: int, user_id: Optional[int] = None):"""Get a chat by ID with all messages"""try:chat = chat_manager.get_chat(chat_id, user_id)return chatexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e))16 unmodified linesraise HTTPException(status_code=500, detail=f"Failed to retrieve chats: {str(e)}")@router.delete("/{chat_id}")async def delete_chat(chat_id: int, user_id: Optional[int] = None):"""Delete a chat and all its messages"""try:success = chat_manager.delete_chat(chat_id, user_id)if not success:raise HTTPException(status_code=404, detail=f"Chat with ID {chat_id} not found or access denied")return {"message": f"Chat {chat_id} deleted successfully"}except HTTPException:raise42 unmodified linesraise HTTPException(status_code=404, detail=str(e))except Exception as e:logger.error(f"Error updating chat: {str(e)}")raise HTTPException(status_code=500, detail=f"Failed to update chat: {str(e)}")@router.post("/cleanup-empty", response_model=dict)async def cleanup_empty_chats(request: ChatCreate):"""Delete empty chats for a user"""try:deleted_count = chat_manager.delete_empty_chats(request.user_id, request.is_admin)return {"message": f"Deleted {deleted_count} empty chats"}except Exception as e:logger.error(f"Error cleaning up empty chats: {str(e)}")raise HTTPException(status_code=500, detail=f"Failed to clean up empty chats: {str(e)}")
chat_manager.py+83-11
chat_routes.py+18-8