From b747ea285f9a1f1077007c8fd0700c9dea2a148b Mon Sep 17 00:00:00 2001 From: Alex Vandiver Date: Wed, 21 Feb 2024 03:37:54 +0000 Subject: [PATCH] topic: Fix history order for topic moves. 5c96f942060e mistakenly appended, rather than prepended, the edit to the history. This caused AssertionErrors when attempting to view the history of moved messages, which check that the `last_edit_time` matches the timestamp of the first edit in the list. Fix the ordering, and update the `edit_history` for messages that were affected. We limit to only messages edited since the commit was merged, since that helps bound the affected messages somewhat. --- zerver/lib/topic.py | 8 ++--- zerver/migrations/0497_resort_edit_history.py | 35 +++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 zerver/migrations/0497_resort_edit_history.py diff --git a/zerver/lib/topic.py b/zerver/lib/topic.py index 3a61adba86..577d2db3fe 100644 --- a/zerver/lib/topic.py +++ b/zerver/lib/topic.py @@ -194,6 +194,10 @@ def update_messages_for_topic_edit( # )::text "edit_history": Cast( Func( + Cast( + Value(orjson.dumps([edit_history_event]).decode()), + JSONField(), + ), Cast( Func( F("edit_history"), @@ -202,10 +206,6 @@ def update_messages_for_topic_edit( ), JSONField(), ), - Cast( - Value(orjson.dumps([edit_history_event]).decode()), - JSONField(), - ), function="", arg_joiner=" || ", ), diff --git a/zerver/migrations/0497_resort_edit_history.py b/zerver/migrations/0497_resort_edit_history.py new file mode 100644 index 0000000000..36ca1caa7a --- /dev/null +++ b/zerver/migrations/0497_resort_edit_history.py @@ -0,0 +1,35 @@ +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ("zerver", "0496_alter_scheduledmessage_read_by_sender"), + ] + + operations = [ + migrations.RunSQL( + # Update with properly-sorted history for messages changed + # after 5c96f942060e was merged. + """ + WITH sorted_history AS ( + SELECT zerver_message.id AS rowid, + JSONB_AGG(value ORDER BY (value->>'timestamp')::NUMERIC desc) AS updated_history + FROM zerver_message + CROSS JOIN JSONB_ARRAY_ELEMENTS(zerver_message.edit_history::jsonb) + WHERE zerver_message.edit_history IS NOT NULL + AND zerver_message.last_edit_time > '2024-02-14' + AND JSONB_ARRAY_LENGTH(zerver_message.edit_history::jsonb) > 1 + GROUP BY zerver_message.id + ORDER BY zerver_message.id + ) + UPDATE zerver_message + SET edit_history = sorted_history.updated_history::text + FROM sorted_history + WHERE zerver_message.id = sorted_history.rowid + AND zerver_message.edit_history::jsonb != sorted_history.updated_history + """, + reverse_sql="", + elidable=True, + ) + ]