diff --git a/src/backend/chat/migrations/0002_fix_source_type_in_messages.py b/src/backend/chat/migrations/0002_fix_source_type_in_messages.py new file mode 100644 index 0000000..4524790 --- /dev/null +++ b/src/backend/chat/migrations/0002_fix_source_type_in_messages.py @@ -0,0 +1,54 @@ +# Generated by Django 5.2.3 on 2025-09-15 11:47 +from django.db import migrations + + +def forwards_func(apps, schema_editor): + """Use raw SQL to replace "source_type" with "sourceType" in the messages field.""" + with schema_editor.connection.cursor() as cursor: + cursor.execute(""" + UPDATE chat_chatconversation + SET messages = REPLACE(messages::text, '"source_type"', '"sourceType"')::jsonb + WHERE messages::text LIKE '%"source_type"%' + """) + with schema_editor.connection.cursor() as cursor: + cursor.execute(""" + UPDATE chat_chatconversation + SET ui_messages = REPLACE(ui_messages::text, '"source_type"', '"sourceType"')::jsonb + WHERE ui_messages::text LIKE '%"source_type"%' + """) + + +def reverse_func(apps, schema_editor): + """Use raw SQL to replace "sourceType" with "source_type" in the messages field.""" + with schema_editor.connection.cursor() as cursor: + cursor.execute(""" + UPDATE chat_chatconversation + SET messages = REPLACE(messages::text, '"sourceType"', '"source_type"')::jsonb + WHERE messages::text LIKE '%"sourceType"%' + """) + with schema_editor.connection.cursor() as cursor: + cursor.execute(""" + UPDATE chat_chatconversation + SET ui_messages = REPLACE(ui_messages::text, '"sourceType"', '"source_type"')::jsonb + WHERE ui_messages::text LIKE '%"sourceType"%' + """) + + +class Migration(migrations.Migration): + """ + Rename source_type to sourceType in messages field of ChatConversation model. + + Warning: This migration is not fail-safe, if the messages field contains + other occurrences of "source_type" or "sourceType" in other contexts, they will + also be replaced. Also, if the messages field is very large, this migration + may take a long time to run. + => OK because we are only in development phase. + """ + + dependencies = [ + ("chat", "0001_initial"), + ] + + operations = [ + migrations.RunPython(forwards_func, reverse_func), + ]