diff --git a/zerver/lib/actions.py b/zerver/lib/actions.py index b4a10a4d30..17cd716b52 100644 --- a/zerver/lib/actions.py +++ b/zerver/lib/actions.py @@ -2300,6 +2300,12 @@ def bulk_add_subscriptions(streams: Iterable[Stream], # Log Subscription Activities in RealmAuditLog event_time = timezone_now() event_last_message_id = Message.objects.aggregate(Max('id'))['id__max'] + if event_last_message_id is None: + # During initial realm creation, there might be 0 messages in + # the database; in that case, the `aggregate` query returns + # None. Since we want an int for "beginning of time", use -1. + event_last_message_id = -1 + all_subscription_logs = [] # type: (List[RealmAuditLog]) for (sub, stream) in subs_to_add: all_subscription_logs.append(RealmAuditLog(realm=sub.user_profile.realm, diff --git a/zerver/migrations/0139_fill_last_message_id_in_subscription_logs.py b/zerver/migrations/0139_fill_last_message_id_in_subscription_logs.py new file mode 100644 index 0000000000..0fae9f9933 --- /dev/null +++ b/zerver/migrations/0139_fill_last_message_id_in_subscription_logs.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models +from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor +from django.db.migrations.state import StateApps + +def backfill_last_message_id(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: + event_type = ['subscription_created', 'subscription_deactivated', 'subscription_activated'] + RealmAuditLog = apps.get_model('zerver', 'RealmAuditLog') + subscription_logs = RealmAuditLog.objects.filter( + event_last_message_id__isnull=True, event_type__in=event_type) + subscription_logs.update(event_last_message_id=-1) + +class Migration(migrations.Migration): + + dependencies = [ + ('zerver', '0138_userprofile_realm_name_in_notifications'), + ] + + operations = [ + migrations.RunPython(backfill_last_message_id, + reverse_code=migrations.RunPython.noop), + ]