05partial_state_rooms_triggers.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright 2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. This migration adds triggers to the partial_state_events tables to enforce uniqueness
  16. Triggers cannot be expressed in .sql files, so we have to use a separate file.
  17. """
  18. from synapse.storage.engines import BaseDatabaseEngine
  19. from synapse.storage.engines.postgres import PostgresEngine
  20. from synapse.storage.engines.sqlite import Sqlite3Engine
  21. from synapse.storage.types import Cursor
  22. def run_create(cur: Cursor, database_engine: BaseDatabaseEngine, *args, **kwargs):
  23. # complain if the room_id in partial_state_events doesn't match
  24. # that in `events`. We already have a fk constraint which ensures that the event
  25. # exists in `events`, so all we have to do is raise if there is a row with a
  26. # matching stream_ordering but not a matching room_id.
  27. if isinstance(database_engine, Sqlite3Engine):
  28. cur.execute(
  29. """
  30. CREATE TRIGGER IF NOT EXISTS partial_state_events_bad_room_id
  31. BEFORE INSERT ON partial_state_events
  32. FOR EACH ROW
  33. BEGIN
  34. SELECT RAISE(ABORT, 'Incorrect room_id in partial_state_events')
  35. WHERE EXISTS (
  36. SELECT 1 FROM events
  37. WHERE events.event_id = NEW.event_id
  38. AND events.room_id != NEW.room_id
  39. );
  40. END;
  41. """
  42. )
  43. elif isinstance(database_engine, PostgresEngine):
  44. cur.execute(
  45. """
  46. CREATE OR REPLACE FUNCTION check_partial_state_events() RETURNS trigger AS $BODY$
  47. BEGIN
  48. IF EXISTS (
  49. SELECT 1 FROM events
  50. WHERE events.event_id = NEW.event_id
  51. AND events.room_id != NEW.room_id
  52. ) THEN
  53. RAISE EXCEPTION 'Incorrect room_id in partial_state_events';
  54. END IF;
  55. RETURN NEW;
  56. END;
  57. $BODY$ LANGUAGE plpgsql;
  58. """
  59. )
  60. cur.execute(
  61. """
  62. CREATE TRIGGER check_partial_state_events BEFORE INSERT OR UPDATE ON partial_state_events
  63. FOR EACH ROW
  64. EXECUTE PROCEDURE check_partial_state_events()
  65. """
  66. )
  67. else:
  68. raise NotImplementedError("Unknown database engine")