02_drop_user_id_constraint_user_filters.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from synapse.storage.database import LoggingTransaction
  2. from synapse.storage.engines import BaseDatabaseEngine, PostgresEngine
  3. def run_create(cur: LoggingTransaction, database_engine: BaseDatabaseEngine) -> None:
  4. """
  5. Update to drop the NOT NULL constraint on column user_id so that we can cease to
  6. write to it without inserts to other columns triggering the constraint
  7. """
  8. if isinstance(database_engine, PostgresEngine):
  9. drop_sql = """
  10. ALTER TABLE user_filters ALTER COLUMN user_id DROP NOT NULL
  11. """
  12. cur.execute(drop_sql)
  13. else:
  14. # irritatingly in SQLite we need to rewrite the table to drop the constraint.
  15. cur.execute("DROP TABLE IF EXISTS temp_user_filters")
  16. create_sql = """
  17. CREATE TABLE temp_user_filters (
  18. full_user_id text NOT NULL,
  19. user_id text,
  20. filter_id bigint NOT NULL,
  21. filter_json bytea NOT NULL
  22. )
  23. """
  24. cur.execute(create_sql)
  25. index_sql = """
  26. CREATE UNIQUE INDEX IF NOT EXISTS user_filters_full_user_id_unique ON
  27. temp_user_filters (full_user_id, filter_id)
  28. """
  29. cur.execute(index_sql)
  30. copy_sql = """
  31. INSERT INTO temp_user_filters (
  32. user_id,
  33. filter_id,
  34. filter_json,
  35. full_user_id)
  36. SELECT user_id, filter_id, filter_json, full_user_id FROM user_filters
  37. """
  38. cur.execute(copy_sql)
  39. drop_sql = """
  40. DROP TABLE user_filters
  41. """
  42. cur.execute(drop_sql)
  43. rename_sql = """
  44. ALTER TABLE temp_user_filters RENAME to user_filters
  45. """
  46. cur.execute(rename_sql)