Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

migrations: Add backfill to move personal DMs to DM groups.

Alex Vandivera68ac6434a0f
diff --git a/zerver/migrations/0790_backfill_update_recipient_type_of_personal_messages_to_dm_group.py b/zerver/migrations/0790_backfill_update_recipient_type_of_personal_messages_to_dm_group.py
new file mode 100644
index 00000000000..9f14921e0b4
--- /dev/null
+++ b/zerver/migrations/0790_backfill_update_recipient_type_of_personal_messages_to_dm_group.py
@@ -0,0 +1,171 @@
+# Generated by Django 5.2.4 on 2025-08-17 00:11
+
+import hashlib
+from typing import Any
+
+from django.db import connection, migrations, transaction
+from django.db.backends.base.schema import BaseDatabaseSchemaEditor
+from django.db.migrations.state import StateApps
+from psycopg2.sql import SQL, Identifier
+
+BATCH_SIZE = 500
+PERSONAL_RECIPIENT = 1
+DIRECT_MESSAGE_GROUP_RECIPIENT = 3
+
+TABLES = [
+ ("zerver_message", "sender_id"),
+ ("zerver_archivedmessage", "sender_id"),
+ ("zerver_scheduledmessage", "sender_id"),
+ ("zerver_draft", "user_profile_id"),
+]
+
+
+def get_direct_message_group_hash(id_list: list[int]) -> str:
+ """
+ Takes a list of user IDs and returns a hash for the group consisting of
+ these users. This is used to create a unique identifier for direct message groups.
+
+ This function is copied from zerver/model/recipients.py to avoid import issues.
+ """
+ sorted_ids = sorted(id_list)
+ hash_key = ",".join(str(x) for x in sorted_ids)
+ return hashlib.sha1(hash_key.encode()).hexdigest()
+
+
+def get_or_create_direct_message_group(apps: StateApps, id_list: list[int]) -> Any:
+ """
+ Takes a list of user IDs and returns the DirectMessageGroup object for
+ the group consisting of these users. If the DirectMessageGroup object
+ does not yet exist, it will be transparently created.
+
+ This function is copied from zerver/model/recipients.py to avoid import issues.
+ """
+ DirectMessageGroup = apps.get_model("zerver", "DirectMessageGroup")
+ Recipient = apps.get_model("zerver", "Recipient")
+
+ direct_message_group_hash = get_direct_message_group_hash(id_list)
+ with transaction.atomic(savepoint=False):
+ direct_message_group, created = DirectMessageGroup.objects.get_or_create(
+ huddle_hash=direct_message_group_hash,
+ group_size=len(id_list),
+ )
+ if not created:
+ return direct_message_group
+
+ recipient = Recipient.objects.create(
+ type_id=direct_message_group.id, type=DIRECT_MESSAGE_GROUP_RECIPIENT
+ )
+ direct_message_group.recipient = recipient
+ direct_message_group.save(update_fields=["recipient"])
+ with connection.cursor() as cursor:
+ cursor.execute(
+ """
+ INSERT INTO zerver_subscription
+ (recipient_id, user_profile_id, is_user_active,
+ active, is_muted, color, pin_to_top,
+ desktop_notifications, audible_notifications,
+ push_notifications, email_notifications,
+ wildcard_mentions_notify)
+ SELECT %s, id, is_active,
+ true, false, '#c2c2c2', false,
+ NULL, NULL, NULL, NULL, NULL
+ FROM zerver_userprofile
+ WHERE id IN %s
+ """,
+ [recipient.id, tuple(id_list)],
+ )
+ return direct_message_group
+
+
+def backfill_update_recipient_type_of_personal_messages_to_dm_group(
+ apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
+) -> None:
+ print()
+
+ with connection.cursor() as cursor:
+ # Only include personal recipients that have rows in at least
+ # one of the four tables we need to convert.
+ cursor.execute(
+ "CREATE TEMP TABLE personal_recipients_to_process AS "
+ "SELECT r.id, type_id FROM zerver_recipient r "
+ "JOIN zerver_userprofile u ON u.id = r.type_id "
+ "WHERE r.type = %s AND ("
+ " EXISTS (SELECT 1 FROM zerver_message WHERE recipient_id = r.id)"
+ " OR EXISTS (SELECT 1 FROM zerver_archivedmessage WHERE recipient_id = r.id)"
+ " OR EXISTS (SELECT 1 FROM zerver_scheduledmessage WHERE recipient_id = r.id)"
+ " OR EXISTS (SELECT 1 FROM zerver_draft WHERE recipient_id = r.id)"
+ ") ORDER BY u.realm_id, r.id",
+ [PERSONAL_RECIPIENT],
+ )
+ cursor.execute(
+ "CREATE INDEX personal_recipients_to_process_id ON personal_recipients_to_process (id)"
+ )
+ cursor.execute("SELECT COUNT(*) FROM personal_recipients_to_process")
+ (total,) = cursor.fetchone()
+ print(f"Processing {total} personal recipients...")
+
+ processed = 0
+ while True:
+ cursor.execute(
+ "SELECT id, type_id FROM personal_recipients_to_process LIMIT %s",
+ [BATCH_SIZE],
+ )
+ batch = cursor.fetchall()
+ if not batch:
+ break
+
+ for personal_rec_id, receiving_user_id in batch:
+ # Collect distinct senders per table for this recipient.
+ sender_tables: dict[int, list[tuple[str, str]]] = {}
+ for table, col in TABLES:
+ cursor.execute(
+ SQL("SELECT DISTINCT {} FROM {} WHERE recipient_id = %s").format(
+ Identifier(col), Identifier(table)
+ ),
+ [personal_rec_id],
+ )
+ for (sender_id,) in cursor.fetchall():
+ sender_tables.setdefault(sender_id, []).append((table, col))
+
+ # For each sender, create the DMG and update rows atomically.
+ for sender_id, tables_to_update in sender_tables.items():
+ if sender_id == receiving_user_id:
+ id_list = [sender_id]
+ else:
+ id_list = [sender_id, receiving_user_id]
+
+ with transaction.atomic():
+ dmg = get_or_create_direct_message_group(apps, id_list)
+ for table, col in tables_to_update:
+ cursor.execute(
+ SQL(
+ "UPDATE {} SET recipient_id = %s"
+ " WHERE {} = %s AND recipient_id = %s"
+ ).format(Identifier(table), Identifier(col)),
+ [dmg.recipient_id, sender_id, personal_rec_id],
+ )
+
+ cursor.execute(
+ "DELETE FROM personal_recipients_to_process WHERE id = ANY(%s)",
+ [[row[0] for row in batch]],
+ )
+ processed += len(batch)
+ print(f" Processed {processed}/{total} personal recipients.")
+
+ print("Migration completed.")
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("zerver", "0789_add_external_auth_fields_to_preregistrationuser"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ backfill_update_recipient_type_of_personal_messages_to_dm_group,
+ reverse_code=migrations.RunPython.noop,
+ elidable=True,
+ ),
+ ]