Branchwell

AI Resource Pro / website / scripts / add-is-archived-column.sql

1-- Add is_archived column to user_roadmaps table
2ALTER TABLE public.user_roadmaps
3ADD COLUMN IF NOT EXISTS is_archived BOOLEAN DEFAULT false;
4
5-- Find users with multiple active roadmaps and archive all but the most recent one
6DO $$
7DECLARE
8 user_with_dupes RECORD;
9 roadmap_to_keep RECORD;
10BEGIN
11 -- Log beginning of cleanup process
12 RAISE NOTICE 'Beginning cleanup of duplicate roadmaps...';
13
14 -- Get list of users who have multiple roadmaps
15 FOR user_with_dupes IN
16 SELECT user_id, COUNT(*) as roadmap_count
17 FROM public.user_roadmaps
18 WHERE is_archived = false OR is_archived IS NULL
19 GROUP BY user_id
20 HAVING COUNT(*) > 1
21 LOOP
22 RAISE NOTICE 'Processing user % with % roadmaps', user_with_dupes.user_id, user_with_dupes.roadmap_count;
23
24 -- Find most recent roadmap to keep active
25 SELECT id, created_at
26 INTO roadmap_to_keep
27 FROM public.user_roadmaps
28 WHERE user_id = user_with_dupes.user_id AND (is_archived = false OR is_archived IS NULL)
29 ORDER BY created_at DESC
30 LIMIT 1;
31
32 RAISE NOTICE 'Keeping roadmap % (created at %) active', roadmap_to_keep.id, roadmap_to_keep.created_at;
33
34 -- Archive all other roadmaps for this user
35 UPDATE public.user_roadmaps
36 SET is_archived = true
37 WHERE user_id = user_with_dupes.user_id
38 AND id != roadmap_to_keep.id
39 AND (is_archived = false OR is_archived IS NULL);
40
41 RAISE NOTICE 'Archived older roadmaps for user %', user_with_dupes.user_id;
42 END LOOP;
43
44 RAISE NOTICE 'Duplicate roadmap cleanup complete';
45END $$;
46
47-- Create a partial unique index that only allows one active roadmap per user
48DROP INDEX IF EXISTS idx_user_roadmaps_one_active_per_user;
49CREATE UNIQUE INDEX idx_user_roadmaps_one_active_per_user
50ON public.user_roadmaps (user_id)
51WHERE is_archived = false;
52
53-- Output a message to confirm the migration was successful
54DO $$
55BEGIN
56 RAISE NOTICE 'Migration complete: Added is_archived column, cleaned up duplicate roadmaps, and created partial unique index on user_roadmaps table';
57END $$;