242a2047eae0_update_chat_table.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """Update chat table
  2. Revision ID: 242a2047eae0
  3. Revises: 6a39f3d8e55c
  4. Create Date: 2024-10-09 21:02:35.241684
  5. """
  6. from alembic import op
  7. import sqlalchemy as sa
  8. from sqlalchemy.sql import table, select, update
  9. import json
  10. revision = "242a2047eae0"
  11. down_revision = "6a39f3d8e55c"
  12. branch_labels = None
  13. depends_on = None
  14. def upgrade():
  15. # Step 1: Rename current 'chat' column to 'old_chat'
  16. op.alter_column("chat", "chat", new_column_name="old_chat", existing_type=sa.Text)
  17. # Step 2: Add new 'chat' column of type JSON
  18. op.add_column("chat", sa.Column("chat", sa.JSON(), nullable=True))
  19. # Step 3: Migrate data from 'old_chat' to 'chat'
  20. chat_table = table(
  21. "chat",
  22. sa.Column("id", sa.String, primary_key=True),
  23. sa.Column("old_chat", sa.Text),
  24. sa.Column("chat", sa.JSON()),
  25. )
  26. # - Selecting all data from the table
  27. connection = op.get_bind()
  28. results = connection.execute(select(chat_table.c.id, chat_table.c.old_chat))
  29. for row in results:
  30. try:
  31. # Convert text JSON to actual JSON object, assuming the text is in JSON format
  32. json_data = json.loads(row.old_chat)
  33. except json.JSONDecodeError:
  34. json_data = None # Handle cases where the text cannot be converted to JSON
  35. connection.execute(
  36. sa.update(chat_table)
  37. .where(chat_table.c.id == row.id)
  38. .values(chat=json_data)
  39. )
  40. # Step 4: Drop 'old_chat' column
  41. op.drop_column("chat", "old_chat")
  42. def downgrade():
  43. # Step 1: Add 'old_chat' column back as Text
  44. op.add_column("chat", sa.Column("old_chat", sa.Text(), nullable=True))
  45. # Step 2: Convert 'chat' JSON data back to text and store in 'old_chat'
  46. chat_table = table(
  47. "chat",
  48. sa.Column("id", sa.String, primary_key=True),
  49. sa.Column("chat", sa.JSON()),
  50. sa.Column("old_chat", sa.Text()),
  51. )
  52. connection = op.get_bind()
  53. results = connection.execute(select(chat_table.c.id, chat_table.c.chat))
  54. for row in results:
  55. text_data = json.dumps(row.chat) if row.chat is not None else None
  56. connection.execute(
  57. sa.update(chat_table)
  58. .where(chat_table.c.id == row.id)
  59. .values(old_chat=text_data)
  60. )
  61. # Step 3: Remove the new 'chat' JSON column
  62. op.drop_column("chat", "chat")
  63. # Step 4: Rename 'old_chat' back to 'chat'
  64. op.alter_column("chat", "old_chat", new_column_name="chat", existing_type=sa.Text)