-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDATABASE_MIGRATION.sql
More file actions
59 lines (51 loc) · 2.32 KB
/
DATABASE_MIGRATION.sql
File metadata and controls
59 lines (51 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
-- DATABASE MIGRATION FOR NOTIFICATION SYSTEM
-- Run this in your Supabase SQL Editor
-- 1. Create the FCM tokens table
CREATE TABLE IF NOT EXISTS public.user_fcm_tokens (
id UUID PRIMARY KEY DEFAULT extensions.uuid_generate_v4(),
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
token TEXT NOT NULL,
device_info TEXT,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now(),
UNIQUE(user_id, token)
);
-- 2. Create the Notifications log table (referenced as user_notifications in backup)
CREATE TABLE IF NOT EXISTS public.user_notifications (
id UUID PRIMARY KEY DEFAULT extensions.uuid_generate_v4(),
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
milestone_id UUID REFERENCES public.milestones(id) ON DELETE SET NULL,
title TEXT NOT NULL,
message TEXT NOT NULL,
type TEXT CHECK (type = ANY (ARRAY['reminder', 'achievement', 'verse', 'prayer', 'reflection', 'system', 'test'])),
read BOOLEAN DEFAULT false,
action_url TEXT,
metadata JSONB,
scheduled_for TIMESTAMPTZ,
sent_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT now()
);
-- 3. Enable RLS
ALTER TABLE public.user_fcm_tokens ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_notifications ENABLE ROW LEVEL SECURITY;
-- 4. RLS Policies
CREATE POLICY "Users can manage their own tokens" ON public.user_fcm_tokens
FOR ALL USING (auth.uid() = user_id);
CREATE POLICY "Users can view their own notifications" ON public.user_notifications
FOR SELECT USING (auth.uid() = user_id);
CREATE POLICY "Users can update their own notification read status" ON public.user_notifications
FOR UPDATE USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id);
-- 5. Updated At Trigger for tokens
CREATE TRIGGER update_fcm_tokens_updated_at
BEFORE UPDATE ON public.user_fcm_tokens
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
-- 6. Cron Job Setup (requires pg_cron extension enabled in Supabase)
-- SELECT cron.schedule(
-- 'daily-verse-notifications',
-- '0 8 * * *', -- 8:00 AM daily
-- $$ SELECT net.http_post(
-- url := 'https://YOUR_PROJECT_REF.supabase.co/functions/v1/schedule-daily-notifications',
-- headers := '{"Content-Type": "application/json", "Authorization": "Bearer YOUR_SERVICE_ROLE_KEY"}'::jsonb
-- ) $$
-- );