Files
zulip/zerver/migrations/0037_disallow_null_string_id.py
Anders Kaseorg 7a34e9a3fd 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>
(cherry picked from commit df001db1a9)
2023-04-05 16:07:58 -07:00

41 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"])
continue
except IntegrityError:
pass
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),
),
]