diff --git a/zerver/migrations/0449_scheduledmessage_zerver_unsent_scheduled_messages_indexes.py b/zerver/migrations/0449_scheduledmessage_zerver_unsent_scheduled_messages_indexes.py new file mode 100644 index 0000000000..2b85c8392d --- /dev/null +++ b/zerver/migrations/0449_scheduledmessage_zerver_unsent_scheduled_messages_indexes.py @@ -0,0 +1,28 @@ +# Generated by Django 4.2 on 2023-05-09 00:58 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("zerver", "0448_scheduledmessage_new_fields"), + ] + + operations = [ + migrations.AddIndex( + model_name="scheduledmessage", + index=models.Index( + condition=models.Q(("delivered", False), ("failed", False)), + fields=["scheduled_timestamp"], + name="zerver_unsent_scheduled_messages_by_time", + ), + ), + migrations.AddIndex( + model_name="scheduledmessage", + index=models.Index( + condition=models.Q(("delivered", False)), + fields=["sender", "delivery_type", "scheduled_timestamp"], + name="zerver_unsent_scheduled_messages_by_user", + ), + ), + ] diff --git a/zerver/models.py b/zerver/models.py index fe0bda1f52..f666e2c28e 100644 --- a/zerver/models.py +++ b/zerver/models.py @@ -4346,6 +4346,32 @@ class ScheduledMessage(models.Model): default=SEND_LATER, ) + class Meta: + indexes = [ + # We expect a large number of delivered scheduled messages + # to accumulate over time. This first index is for the + # deliver_scheduled_messages worker. + models.Index( + name="zerver_unsent_scheduled_messages_by_time", + fields=["scheduled_timestamp"], + condition=Q( + delivered=False, + failed=False, + ), + ), + # This index is for displaying scheduled messages to the + # user themself via the API; we don't filter failed + # messages since we will want to display those so that + # failures don't just disappear into a black hole. + models.Index( + name="zerver_unsent_scheduled_messages_by_user", + fields=["sender", "delivery_type", "scheduled_timestamp"], + condition=Q( + delivered=False, + ), + ), + ] + def __str__(self) -> str: display_recipient = get_display_recipient(self.recipient) return f"{display_recipient} {self.subject} {self.sender!r} {self.scheduled_timestamp}"