message: Pass args to select_related call for Message objects.

This commit adds code to pass all the required arguments to
select_related call for Message objects such that only the
required related fields are fetched from the database.

Previously, we did not pass any arguments to select_related,
so all the directly and indirectly related fields were fetched
when many of them were actually not being used and made the
query unnecessarily complex.
This commit is contained in:
Sahil Batra 2023-08-01 19:42:18 +05:30 committed by Tim Abbott
parent 35559ae324
commit 36f8aba7db
2 changed files with 5 additions and 3 deletions

View File

@ -596,7 +596,7 @@ class MessageDict:
# of going to the DB here should be overshadowed by the cost of rendering # of going to the DB here should be overshadowed by the cost of rendering
# and updating the row. # and updating the row.
# TODO: see #1379 to eliminate Markdown dependencies # TODO: see #1379 to eliminate Markdown dependencies
message = Message.objects.select_related().get(id=message_id) message = Message.objects.select_related("sender", "sender__realm").get(id=message_id)
assert message is not None # Hint for mypy. assert message is not None # Hint for mypy.
# It's unfortunate that we need to have side effects on the message # It's unfortunate that we need to have side effects on the message
@ -776,7 +776,7 @@ def access_message(
pass lock_message when inside a @transaction.atomic block. pass lock_message when inside a @transaction.atomic block.
""" """
try: try:
base_query = Message.objects.select_related() base_query = Message.objects.select_related(*Message.DEFAULT_SELECT_RELATED)
if lock_message: if lock_message:
# We want to lock only the `Message` row, and not the related fields # We want to lock only the `Message` row, and not the related fields
# because the `Message` row only has a possibility of races. # because the `Message` row only has a possibility of races.
@ -808,7 +808,7 @@ def access_web_public_message(
raise MissingAuthenticationError raise MissingAuthenticationError
try: try:
message = Message.objects.select_related().get(id=message_id) message = Message.objects.select_related(*Message.DEFAULT_SELECT_RELATED).get(id=message_id)
except Message.DoesNotExist: except Message.DoesNotExist:
raise MissingAuthenticationError raise MissingAuthenticationError

View File

@ -3015,6 +3015,8 @@ class Message(AbstractMessage):
search_tsvector = SearchVectorField(null=True) search_tsvector = SearchVectorField(null=True)
DEFAULT_SELECT_RELATED = ["sender", "sender__realm", "realm", "recipient", "sending_client"]
def topic_name(self) -> str: def topic_name(self) -> str:
""" """
Please start using this helper to facilitate an Please start using this helper to facilitate an