Branchwell

Become a Pro / website · becomeapro.ai / supabase / migrations / 20261102000000_learning_profiles_and_activity.sql

Raw 2.6 KB on b7854f3692d64213a2fce644d0b5101d3e345b03
1-- Onboarding answers and on-site activity, used to build each user's roadmap.
2-- Nothing personal: just what they want from the site, their level and what they've watched or finished.
3
4-- ── learning_profiles ──────────────────────────────────────
5-- One row per user: their answers to the onboarding questions. Retaking the questions overwrites it.
6CREATE TABLE IF NOT EXISTS public.learning_profiles (
7 user_id uuid PRIMARY KEY REFERENCES public.users (id) ON DELETE CASCADE,
8 goals text[] NOT NULL DEFAULT '{}',
9 tracks text[] NOT NULL DEFAULT '{}',
10 level text NOT NULL CHECK (level IN ('Beginner', 'Intermediate', 'Advanced')),
11 weekly_time text NOT NULL CHECK (weekly_time IN ('light', 'steady', 'deep')),
12 format text NOT NULL CHECK (format IN ('video', 'written', 'both')),
13 created_at timestamptz NOT NULL DEFAULT now(),
14 updated_at timestamptz NOT NULL DEFAULT now()
15);
16
17ALTER TABLE public.learning_profiles ENABLE ROW LEVEL SECURITY;
18
19CREATE POLICY "learning_profiles_own"
20 ON public.learning_profiles FOR ALL
21 USING ((select auth.uid()) = user_id)
22 WITH CHECK ((select auth.uid()) = user_id);
23
24-- ── tutorial_activity ──────────────────────────────────────
25-- Which tutorials a user has opened, how often, and which they've marked done on their roadmap.
26CREATE TABLE IF NOT EXISTS public.tutorial_activity (
27 user_id uuid NOT NULL REFERENCES public.users (id) ON DELETE CASCADE,
28 tutorial_slug text NOT NULL,
29 view_count integer NOT NULL DEFAULT 0,
30 first_viewed_at timestamptz,
31 last_viewed_at timestamptz,
32 completed_at timestamptz,
33 PRIMARY KEY (user_id, tutorial_slug)
34);
35
36ALTER TABLE public.tutorial_activity ENABLE ROW LEVEL SECURITY;
37
38CREATE POLICY "tutorial_activity_own"
39 ON public.tutorial_activity FOR ALL
40 USING ((select auth.uid()) = user_id)
41 WITH CHECK ((select auth.uid()) = user_id);
42
43-- Counts a view for the signed-in user (one call per page open)
44CREATE OR REPLACE FUNCTION public.record_tutorial_view(p_slug text)
45RETURNS void
46LANGUAGE sql
47SECURITY INVOKER
48SET search_path = ''
49AS $$
50 INSERT INTO public.tutorial_activity (user_id, tutorial_slug, view_count, first_viewed_at, last_viewed_at)
51 VALUES ((select auth.uid()), p_slug, 1, now(), now())
52 ON CONFLICT (user_id, tutorial_slug)
53 DO UPDATE SET view_count = public.tutorial_activity.view_count + 1, last_viewed_at = now();
54$$;
55
56REVOKE EXECUTE ON FUNCTION public.record_tutorial_view(text) FROM public, anon;
57GRANT EXECUTE ON FUNCTION public.record_tutorial_view(text) TO authenticated;