From eb368c9c9278038db14e628cce85b6904bd11af8 Mon Sep 17 00:00:00 2001 From: Steve Howell Date: Sat, 29 Feb 2020 14:34:00 +0000 Subject: [PATCH] performance: Optimize max_message_id calculation. We calculate `max_message_id` for the mobile client. Our query now no longer joins to the Message table and just grabs one value instead of fat objects. --- zerver/lib/events.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/zerver/lib/events.py b/zerver/lib/events.py index 51bff11a95..945b3499f1 100644 --- a/zerver/lib/events.py +++ b/zerver/lib/events.py @@ -53,7 +53,7 @@ from zerver.lib.user_groups import user_groups_in_realm_serialized from zerver.lib.user_status import get_user_info_dict from zerver.tornado.event_queue import request_event_queue, get_user_events from zerver.models import ( - Client, Message, Realm, UserProfile, + Client, Message, Realm, UserProfile, UserMessage, get_user_profile_by_id, realm_filters_for_realm, custom_profile_fields_for_realm, get_realm_domains, get_default_stream_groups, CustomProfileField, Stream @@ -112,9 +112,12 @@ def fetch_initial_state_data(user_profile: UserProfile, # The client should use get_messages() to fetch messages # starting with the max_message_id. They will get messages # newer than that ID via get_events() - messages = Message.objects.filter(usermessage__user_profile=user_profile).order_by('-id')[:1] - if messages: - state['max_message_id'] = messages[0].id + user_messages = UserMessage.objects \ + .filter(user_profile=user_profile) \ + .order_by('-message_id') \ + .values('message_id')[:1] + if user_messages: + state['max_message_id'] = user_messages[0]['message_id'] else: state['max_message_id'] = -1