From 79e859427aab9b11d5b3f6dca507f72dd7231185 Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Fri, 25 Nov 2022 19:46:30 -0800 Subject: [PATCH] =?UTF-8?q?migrations:=20Fix=20Python-looped=20SQL=20in=20?= =?UTF-8?q?0376;=20don=E2=80=99t=20crash=20if=20no=20user=20found.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Anders Kaseorg --- ...almemoji_author_and_reupload_realmemoji.py | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/zerver/migrations/0376_set_realmemoji_author_and_reupload_realmemoji.py b/zerver/migrations/0376_set_realmemoji_author_and_reupload_realmemoji.py index c3961242e5..751e501f04 100644 --- a/zerver/migrations/0376_set_realmemoji_author_and_reupload_realmemoji.py +++ b/zerver/migrations/0376_set_realmemoji_author_and_reupload_realmemoji.py @@ -1,6 +1,7 @@ from django.db import migrations from django.db.backends.postgresql.schema import BaseDatabaseSchemaEditor from django.db.migrations.state import StateApps +from django.db.models import OuterRef, Subquery def set_emoji_author(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None: @@ -13,20 +14,15 @@ def set_emoji_author(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) - UserProfile = apps.get_model("zerver", "UserProfile") ROLE_REALM_OWNER = 100 - realm_emoji_to_update = [] - for realm_emoji in RealmEmoji.objects.all(): - if realm_emoji.author_id is None: - user_profile = ( - UserProfile.objects.filter( - realm_id=realm_emoji.realm_id, is_active=True, role=ROLE_REALM_OWNER - ) - .order_by("id") - .first() + RealmEmoji.objects.filter(author=None).update( + author=Subquery( + UserProfile.objects.filter( + realm=OuterRef("realm"), is_active=True, role=ROLE_REALM_OWNER ) - realm_emoji.author_id = user_profile.id - realm_emoji_to_update.append(realm_emoji) - - RealmEmoji.objects.bulk_update(realm_emoji_to_update, ["author_id"]) + .order_by("id")[:1] + .values("pk") + ) + ) # Previously, this also pushed `reupload_realm_emoji` events onto # the `deferred_work` queue; however,