migration_5.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # Migration to add room settings table
  2. from datetime import datetime
  3. def migration(conn):
  4. with conn.cursor() as cursor:
  5. cursor.execute(
  6. """
  7. CREATE TABLE IF NOT EXISTS room_settings (
  8. room_id TEXT NOT NULL,
  9. setting TEXT NOT NULL,
  10. value TEXT NOT NULL,
  11. PRIMARY KEY (room_id, setting)
  12. )
  13. """
  14. )
  15. cursor.execute("SELECT * FROM system_messages")
  16. system_messages = cursor.fetchall()
  17. # Get latest system message for each room
  18. cursor.execute(
  19. """
  20. SELECT system_messages.room_id, system_messages.message_id, system_messages.user_id, system_messages.body, system_messages.timestamp
  21. FROM system_messages
  22. INNER JOIN (
  23. SELECT room_id, MAX(timestamp) AS timestamp FROM system_messages GROUP BY room_id
  24. ) AS latest_system_message ON system_messages.room_id = latest_system_message.room_id AND system_messages.timestamp = latest_system_message.timestamp
  25. """
  26. )
  27. system_messages = cursor.fetchall()
  28. for message in system_messages:
  29. cursor.execute(
  30. "INSERT INTO room_settings (room_id, setting, value) VALUES (?, ?, ?)",
  31. (message[0], "system_message", message[1])
  32. )
  33. cursor.execute("DROP TABLE system_messages")
  34. cursor.execute(
  35. "INSERT INTO migrations (id, timestamp) VALUES (5, ?)",
  36. (datetime.now(),)
  37. )
  38. conn.commit()