Files
zulip/zerver/migrations/0037_disallow_null_string_id.py
Anders Kaseorg df001db1a9 black: Reformat with Black 23.
Black 23 enforces some slightly more specific rules about empty line
counts and redundant parenthesis removal, but the result is still
compatible with Black 22.

(This does not actually upgrade our Python environment to Black 23
yet.)

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2023-02-02 10:40:13 -08:00

42 lines
1.4 KiB
Python

from django.db import migrations, models
from django.db.backends.postgresql.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps
from django.db.utils import IntegrityError
def set_string_id_using_domain(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
Realm = apps.get_model("zerver", "Realm")
for realm in Realm.objects.all():
if not realm.string_id:
prefix = realm.domain.split(".")[0]
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"])
break
except IntegrityError:
pass
else:
raise RuntimeError(f"Unable to find a good string_id for realm {realm}")
class Migration(migrations.Migration):
dependencies = [
("zerver", "0036_rename_subdomain_to_string_id"),
]
operations = [
migrations.RunPython(set_string_id_using_domain, elidable=True),
migrations.AlterField(
model_name="realm",
name="string_id",
field=models.CharField(unique=True, max_length=40),
),
]