2017-11-16 00:44:00 +01:00
|
|
|
from django.db import migrations, models
|
2023-03-04 01:40:40 +01:00
|
|
|
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
|
2016-10-27 03:05:21 +02:00
|
|
|
from django.db.migrations.state import StateApps
|
2017-11-16 00:44:00 +01:00
|
|
|
from django.db.utils import IntegrityError
|
2016-10-27 03:05:21 +02:00
|
|
|
|
2020-01-14 21:59:46 +01:00
|
|
|
|
2022-05-27 23:33:51 +02:00
|
|
|
def set_string_id_using_domain(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
|
2021-02-12 08:20:45 +01:00
|
|
|
Realm = apps.get_model("zerver", "Realm")
|
2016-10-27 03:05:21 +02:00
|
|
|
for realm in Realm.objects.all():
|
|
|
|
if not realm.string_id:
|
2021-02-12 08:20:45 +01:00
|
|
|
prefix = realm.domain.split(".")[0]
|
2016-10-27 03:05:21 +02:00
|
|
|
try:
|
|
|
|
realm.string_id = prefix
|
|
|
|
realm.save(update_fields=["string_id"])
|
|
|
|
continue
|
|
|
|
except IntegrityError:
|
|
|
|
pass
|
|
|
|
for i in range(1, 100):
|
|
|
|
try:
|
|
|
|
realm.string_id = prefix + str(i)
|
|
|
|
realm.save(update_fields=["string_id"])
|
2023-01-18 05:56:37 +01:00
|
|
|
break
|
2016-10-27 03:05:21 +02:00
|
|
|
except IntegrityError:
|
|
|
|
pass
|
2023-01-18 05:56:37 +01:00
|
|
|
else:
|
|
|
|
raise RuntimeError(f"Unable to find a good string_id for realm {realm}")
|
2016-10-27 03:05:21 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2016-10-27 03:05:21 +02:00
|
|
|
class Migration(migrations.Migration):
|
|
|
|
dependencies = [
|
2021-02-12 08:20:45 +01:00
|
|
|
("zerver", "0036_rename_subdomain_to_string_id"),
|
2016-10-27 03:05:21 +02:00
|
|
|
]
|
|
|
|
|
|
|
|
operations = [
|
2020-04-29 08:43:25 +02:00
|
|
|
migrations.RunPython(set_string_id_using_domain, elidable=True),
|
2016-10-27 03:05:21 +02:00
|
|
|
migrations.AlterField(
|
2021-02-12 08:20:45 +01:00
|
|
|
model_name="realm",
|
|
|
|
name="string_id",
|
2016-10-27 03:05:21 +02:00
|
|
|
field=models.CharField(unique=True, max_length=40),
|
|
|
|
),
|
|
|
|
]
|