ALTER TABLE "communication_rooms" DROP COLUMN IF EXISTS "matrix_room_id"; ALTER TABLE "communication_rooms" DROP COLUMN IF EXISTS "matrix_alias"; ALTER TABLE "communication_rooms" DROP COLUMN IF EXISTS "parent_space_room_id"; CREATE TABLE IF NOT EXISTS "communication_room_members" ( "room_id" uuid NOT NULL REFERENCES "communication_rooms"("id") ON DELETE cascade, "user_id" uuid NOT NULL REFERENCES "auth_users"("id") ON DELETE cascade, "joined_at" timestamp with time zone DEFAULT now() NOT NULL, CONSTRAINT "communication_room_members_room_id_user_id_pk" PRIMARY KEY ("room_id", "user_id") ); CREATE INDEX IF NOT EXISTS "communication_room_members_user_idx" ON "communication_room_members" ("user_id"); CREATE TABLE IF NOT EXISTS "communication_messages" ( "id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, "tenant_id" bigint NOT NULL REFERENCES "tenants"("id") ON DELETE cascade, "room_id" uuid NOT NULL REFERENCES "communication_rooms"("id") ON DELETE cascade, "author_user_id" uuid NOT NULL REFERENCES "auth_users"("id"), "body" text NOT NULL, "created_at" timestamp with time zone DEFAULT now() NOT NULL ); CREATE INDEX IF NOT EXISTS "communication_messages_room_message_idx" ON "communication_messages" ("room_id", "id"); CREATE INDEX IF NOT EXISTS "communication_messages_tenant_idx" ON "communication_messages" ("tenant_id"); CREATE TABLE IF NOT EXISTS "communication_room_reads" ( "room_id" uuid NOT NULL REFERENCES "communication_rooms"("id") ON DELETE cascade, "user_id" uuid NOT NULL REFERENCES "auth_users"("id") ON DELETE cascade, "last_read_message_id" bigint, "read_at" timestamp with time zone DEFAULT now() NOT NULL, CONSTRAINT "communication_room_reads_room_id_user_id_pk" PRIMARY KEY ("room_id", "user_id") ); INSERT INTO "communication_room_members" ("room_id", "user_id") SELECT room.id, tenant_user.user_id FROM "communication_rooms" room JOIN "auth_tenant_users" tenant_user ON tenant_user.tenant_id = room.tenant_id WHERE room.type IN ('general', 'room') ON CONFLICT DO NOTHING;