reactions: Migrate emoji_code to store id for realm emoji.

Till now, we had been storing realm emoji's name in emoji code field
in reactions' model. This commit migrates it to store realm emoji's id.
It is a part of effort to migrate realm emojis to be referenced by their
id and not by name.
This commit is contained in:
Harshit Bansal
2017-12-15 15:54:07 +00:00
committed by Tim Abbott
parent b2cadf6817
commit 5aa8629a10
7 changed files with 112 additions and 56 deletions

View File

@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
import ujson
from collections import defaultdict
from django.conf import settings
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
from typing import Any, Dict
def realm_emoji_name_to_id(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
Reaction = apps.get_model('zerver', 'Reaction')
RealmEmoji = apps.get_model('zerver', 'RealmEmoji')
realm_emoji_by_realm_id = defaultdict(dict) # type: Dict[int, Dict[str, Any]]
for realm_emoji in RealmEmoji.objects.all():
realm_emoji_by_realm_id[realm_emoji.realm_id] = {
'id': str(realm_emoji.id),
'name': realm_emoji.name,
'deactivated': realm_emoji.deactivated,
}
for reaction in Reaction.objects.filter(reaction_type='realm_emoji'):
realm_id = reaction.user_profile.realm_id
emoji_name = reaction.emoji_name
if realm_id in realm_emoji_by_realm_id:
realm_emoji = realm_emoji_by_realm_id[realm_id].get(emoji_name)
if realm_emoji is None:
# Realm emoji used in this reaction has been deleted so this
# reaction should also be deleted. We don't need to reverse
# this step in migration reversal code.
reaction.delete()
else:
reaction.emoji_code = realm_emoji["id"]
reaction.save()
def reversal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
Reaction = apps.get_model('zerver', 'Reaction')
for reaction in Reaction.objects.filter(reaction_type='realm_emoji'):
reaction.emoji_code = reaction.emoji_name
reaction.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0144_remove_realm_create_generic_bot_by_admins_only'),
]
operations = [
migrations.RunPython(realm_emoji_name_to_id,
reverse_code=reversal),
]