From a9dc771ffba9f69b12d1a23adb707f241cf2fb6f Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 11 Apr 2026 11:58:10 +0200 Subject: [PATCH] feat(chat): add messages and channel_read_state tables --- .../20260411_create_chat_tables.sql | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 supabase/migrations/20260411_create_chat_tables.sql diff --git a/supabase/migrations/20260411_create_chat_tables.sql b/supabase/migrations/20260411_create_chat_tables.sql new file mode 100644 index 0000000..63eee12 --- /dev/null +++ b/supabase/migrations/20260411_create_chat_tables.sql @@ -0,0 +1,47 @@ +-- supabase/migrations/20260411_create_chat_tables.sql + +-- Messages table +CREATE TABLE IF NOT EXISTS messages ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + channel_id uuid NOT NULL REFERENCES tablos(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES auth.users(id), + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz, + deleted_at timestamptz +); + +CREATE INDEX IF NOT EXISTS idx_messages_channel_created ON messages(channel_id, created_at DESC); + +-- Read state table +CREATE TABLE IF NOT EXISTS channel_read_state ( + user_id uuid NOT NULL REFERENCES auth.users(id), + channel_id uuid NOT NULL REFERENCES tablos(id) ON DELETE CASCADE, + last_read_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, channel_id) +); + +-- RLS policies +ALTER TABLE messages ENABLE ROW LEVEL SECURITY; +ALTER TABLE channel_read_state ENABLE ROW LEVEL SECURITY; + +-- Messages: users can read messages in channels they are members of +CREATE POLICY "Users can read messages in their tablos" + ON messages FOR SELECT + USING ( + EXISTS ( + SELECT 1 FROM tablo_access + WHERE tablo_access.tablo_id = messages.channel_id + AND tablo_access.user_id = auth.uid() + AND tablo_access.is_active = true + ) + ); + +-- Messages: service role inserts (from chat worker) bypass RLS +-- No INSERT policy needed — the chat worker uses the service role key + +-- Read state: users can read/write their own read state +CREATE POLICY "Users can manage their own read state" + ON channel_read_state FOR ALL + USING (user_id = auth.uid()) + WITH CHECK (user_id = auth.uid());