-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathschema.sql
More file actions
2145 lines (1913 loc) · 82.4 KB
/
schema.sql
File metadata and controls
2145 lines (1913 loc) · 82.4 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- ============================================================================
-- C4C Campus Database Schema
-- AI Development Accelerator for Animal Liberation
-- ============================================================================
-- Run this schema in Supabase SQL Editor
-- Generated: November 2025
-- ============================================================================
-- ============================================================================
-- ⚠️ DESTRUCTIVE OPERATIONS - READ CAREFULLY ⚠️
-- ============================================================================
-- This schema file contains DROP TABLE statements that will DELETE ALL DATA.
--
-- USE CASES:
-- ✓ Fresh database setup (development/testing)
-- ✓ Resetting local development environment
-- ✗ Production databases (use migration scripts instead)
--
-- BEFORE RUNNING:
-- 1. Backup your database: pg_dump or Supabase dashboard backup
-- 2. Verify you're not connected to production
-- 3. Understand that ALL DATA will be permanently deleted
--
-- ALTERNATIVES:
-- - For production: Use migration scripts in migrations/ directory
-- - For adding columns: See migrations/add_cohort_id_columns.sql
-- - For Supabase: Use Supabase CLI migrations (supabase db push)
-- ============================================================================
-- ============================================================================
-- TABLE DEPENDENCY HIERARCHY:
-- ============================================================================
--
-- auth.users (Supabase managed)
-- ├── applications
-- ├── profiles
-- ├── auth_logs
-- └── courses
-- ├── modules
-- │ └── lessons
-- │ ├── lesson_discussions (→ cohorts)
-- │ ├── lesson_progress (→ cohorts)
-- │ ├── quizzes
-- │ │ ├── quiz_questions
-- │ │ └── quiz_attempts (→ cohorts)
-- │ └── assignments
-- │ ├── assignment_rubrics
-- │ └── assignment_submissions
-- ├── cohorts
-- │ ├── cohort_enrollments
-- │ ├── cohort_schedules
-- │ └── enrollments (→ courses)
-- ├── course_forums (→ cohorts)
-- │ └── forum_replies
-- ├── ai_conversations
-- │ └── ai_messages
-- ├── certificates (→ certificate_templates)
-- └── payments
-- blog_posts (standalone, FK to auth.users)
--
-- ============================================================================
-- ============================================================================
-- DROP TABLE STATEMENTS (Reverse dependency order)
-- ============================================================================
-- Drop order: children → parents to respect foreign key constraints
-- CASCADE ensures dependent objects are also dropped
-- Level 7 - Deepest dependencies (drop first)
DROP TABLE IF EXISTS forum_replies CASCADE;
DROP TABLE IF EXISTS messages CASCADE;
DROP TABLE IF EXISTS notifications CASCADE;
DROP TABLE IF EXISTS announcements CASCADE;
-- Level 6 - Second-level children
DROP TABLE IF EXISTS lesson_discussions CASCADE;
DROP TABLE IF EXISTS course_forums CASCADE;
DROP TABLE IF EXISTS quiz_questions CASCADE;
DROP TABLE IF EXISTS quiz_attempts CASCADE;
DROP TABLE IF EXISTS assignment_rubrics CASCADE;
DROP TABLE IF EXISTS assignment_submissions CASCADE;
DROP TABLE IF EXISTS ai_messages CASCADE;
DROP TABLE IF EXISTS ai_usage_logs CASCADE;
-- Level 5 - First-level children
DROP TABLE IF EXISTS lesson_progress CASCADE;
DROP TABLE IF EXISTS enrollments CASCADE;
DROP TABLE IF EXISTS quizzes CASCADE;
DROP TABLE IF EXISTS assignments CASCADE;
DROP TABLE IF EXISTS ai_conversations CASCADE;
DROP TABLE IF EXISTS media_library CASCADE;
DROP TABLE IF EXISTS analytics_events CASCADE;
DROP TABLE IF EXISTS blog_posts CASCADE;
-- Level 4 - Module/cohort dependencies
DROP TABLE IF EXISTS lessons CASCADE;
DROP TABLE IF EXISTS cohort_enrollments CASCADE;
DROP TABLE IF EXISTS cohort_schedules CASCADE;
DROP TABLE IF EXISTS certificates CASCADE;
DROP TABLE IF EXISTS payments CASCADE;
DROP TABLE IF EXISTS subscriptions CASCADE;
DROP TABLE IF EXISTS message_threads CASCADE;
-- Level 3 - Parent tables
DROP TABLE IF EXISTS modules CASCADE;
DROP TABLE IF EXISTS cohorts CASCADE;
DROP TABLE IF EXISTS certificate_templates CASCADE;
-- Level 2 - Root tables
DROP TABLE IF EXISTS courses CASCADE;
DROP TABLE IF EXISTS applications CASCADE;
DROP TABLE IF EXISTS profiles CASCADE;
DROP TABLE IF EXISTS auth_logs CASCADE;
-- ============================================================================
-- Enable required extensions
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pg_trgm";
-- Create sequences
CREATE SEQUENCE IF NOT EXISTS public.certificate_number_seq START 1;
-- ============================================================================
-- HELPER FUNCTIONS
-- ============================================================================
-- Function to check if user is admin
CREATE OR REPLACE FUNCTION public.is_admin(user_uuid UUID)
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS (
SELECT 1 FROM public.applications
WHERE user_id = user_uuid AND role = 'admin'
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- Function to check if user is teacher
CREATE OR REPLACE FUNCTION public.is_teacher(user_uuid UUID)
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS (
SELECT 1 FROM public.applications
WHERE user_id = user_uuid AND role IN ('teacher', 'admin')
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- Function to auto-update updated_at timestamp
CREATE OR REPLACE FUNCTION public.update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Function to check if current user is admin (no parameter version)
CREATE OR REPLACE FUNCTION public.is_admin()
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS (
SELECT 1 FROM public.profiles
WHERE profiles.id = auth.uid()
AND profiles.role = 'admin'
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- Function to check if current user is teacher (no parameter version)
CREATE OR REPLACE FUNCTION public.is_teacher()
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS (
SELECT 1 FROM public.profiles
WHERE profiles.id = auth.uid()
AND profiles.role IN ('teacher', 'admin')
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- Function to get user role
CREATE OR REPLACE FUNCTION public.get_user_role(check_user_id UUID)
RETURNS TEXT AS $$
DECLARE
user_role TEXT;
BEGIN
SELECT role INTO user_role
FROM public.applications
WHERE user_id = check_user_id;
RETURN COALESCE(user_role, 'student');
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- Function to check if course is completed
CREATE OR REPLACE FUNCTION public.is_course_completed(check_user_id UUID, check_course_id BIGINT)
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS(
SELECT 1 FROM public.enrollments
WHERE user_id = check_user_id
AND course_id = check_course_id
AND status = 'completed'
);
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Function to get course completion date
CREATE OR REPLACE FUNCTION public.get_course_completion_date(check_user_id UUID, check_course_id BIGINT)
RETURNS TEXT AS $$
BEGIN
RETURN (SELECT completed_at::text FROM public.enrollments
WHERE user_id = check_user_id
AND course_id = check_course_id);
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Function to generate certificate number
CREATE OR REPLACE FUNCTION public.generate_certificate_number()
RETURNS TEXT AS $$
BEGIN
RETURN 'CERT-' || TO_CHAR(NOW(), 'YYYY') || '-' || LPAD(nextval('public.certificate_number_seq')::text, 6, '0');
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Function to generate verification code
CREATE OR REPLACE FUNCTION public.generate_verification_code()
RETURNS TEXT AS $$
BEGIN
RETURN encode(gen_random_bytes(16), 'hex');
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Function to approve application
CREATE OR REPLACE FUNCTION public.approve_application(application_id UUID)
RETURNS VOID AS $$
BEGIN
UPDATE public.applications
SET
status = 'approved',
reviewed_at = NOW()
WHERE id = application_id;
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Function to reject application
CREATE OR REPLACE FUNCTION public.reject_application(application_id UUID)
RETURNS VOID AS $$
BEGIN
UPDATE public.applications
SET
status = 'rejected',
reviewed_at = NOW()
WHERE id = application_id;
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Function to waitlist application
CREATE OR REPLACE FUNCTION public.waitlist_application(application_id UUID)
RETURNS VOID AS $$
BEGIN
UPDATE public.applications
SET
status = 'waitlisted',
reviewed_at = NOW()
WHERE id = application_id;
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Function to check if user can submit to an assignment
-- Returns TRUE if submission is allowed, FALSE otherwise
--
-- This is a pure check function (returns boolean, not exceptions).
-- API handlers should use this to gate submissions, then provide user-friendly
-- error messages based on which rule failed.
--
-- Rules checked (in order):
-- 1. Assignment must exist and be published
-- 2. If past due_date and allow_late_submissions=false, deny
-- 3. First submission is always allowed (if above pass)
-- 4. Resubmission requires allow_resubmission=true
-- 5. Cannot exceed max_submissions limit
--
CREATE OR REPLACE FUNCTION public.can_user_submit(
assignment_id_param UUID,
user_id_param UUID
)
RETURNS BOOLEAN AS $$
DECLARE
v_assignment RECORD;
v_submission_count INTEGER;
BEGIN
-- Get assignment details
SELECT
is_published,
due_date,
allow_late_submissions,
allow_resubmission,
max_submissions
INTO v_assignment
FROM public.assignments
WHERE id = assignment_id_param;
-- Assignment must exist and be published
IF NOT FOUND OR NOT v_assignment.is_published THEN
RETURN FALSE;
END IF;
-- Check due date if not allowing late submissions
IF v_assignment.due_date IS NOT NULL
AND v_assignment.due_date < NOW()
AND NOT v_assignment.allow_late_submissions THEN
RETURN FALSE;
END IF;
-- Count existing submissions
SELECT COUNT(*) INTO v_submission_count
FROM public.assignment_submissions
WHERE assignment_id = assignment_id_param
AND user_id = user_id_param;
-- If no submissions yet, allow
IF v_submission_count = 0 THEN
RETURN TRUE;
END IF;
-- If resubmission not allowed, deny
IF NOT COALESCE(v_assignment.allow_resubmission, FALSE) THEN
RETURN FALSE;
END IF;
-- Check max submissions limit
IF v_assignment.max_submissions IS NOT NULL
AND v_submission_count >= v_assignment.max_submissions THEN
RETURN FALSE;
END IF;
RETURN TRUE;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- Function to get assignment statistics
-- Returns aggregate statistics for all submissions to an assignment
--
-- This function returns a single row with submission statistics.
-- If the assignment has no submissions, all counts will be 0 and average_score will be NULL.
--
-- Return columns:
-- total_submissions - Total number of submissions
-- graded_submissions - Submissions with status='graded'
-- average_score - Mean score across graded submissions (NULL if none graded)
-- late_submissions - Submissions with is_late=true
-- on_time_submissions - Submissions with is_late=false or NULL
--
CREATE OR REPLACE FUNCTION public.get_assignment_stats(assignment_id_param UUID)
RETURNS TABLE(
total_submissions BIGINT,
graded_submissions BIGINT,
average_score NUMERIC,
late_submissions BIGINT,
on_time_submissions BIGINT
) AS $$
BEGIN
RETURN QUERY
SELECT
COUNT(*)::BIGINT as total_submissions,
COUNT(*) FILTER (WHERE status = 'graded')::BIGINT as graded_submissions,
ROUND(AVG(score)::NUMERIC, 2) as average_score,
COUNT(*) FILTER (WHERE is_late = TRUE)::BIGINT as late_submissions,
COUNT(*) FILTER (WHERE is_late = FALSE OR is_late IS NULL)::BIGINT as on_time_submissions
FROM public.assignment_submissions
WHERE assignment_id = assignment_id_param;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- Trigger function to log application approval
CREATE OR REPLACE FUNCTION public.log_application_approval()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.status = 'approved' AND (OLD.status IS NULL OR OLD.status != 'approved') THEN
RAISE NOTICE 'Application approved for user %. Email: %.', NEW.name, NEW.email;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Trigger function to handle new user creation
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public.profiles (id, email, full_name, role)
VALUES (
NEW.id,
NEW.email,
COALESCE(NEW.raw_user_meta_data->>'full_name', NEW.email),
COALESCE(NEW.raw_user_meta_data->>'role', 'student')
)
ON CONFLICT (id) DO NOTHING;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- Trigger function to update cohort status based on dates
CREATE OR REPLACE FUNCTION public.update_cohort_status()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.start_date <= CURRENT_DATE AND (NEW.end_date IS NULL OR NEW.end_date >= CURRENT_DATE) THEN
NEW.status = 'active';
ELSIF NEW.end_date IS NOT NULL AND NEW.end_date < CURRENT_DATE THEN
NEW.status = 'completed';
ELSIF NEW.start_date > CURRENT_DATE THEN
NEW.status = 'upcoming';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Trigger function to update last activity timestamp
CREATE OR REPLACE FUNCTION public.update_last_activity_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.last_accessed = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Trigger function to increment completed lessons count
CREATE OR REPLACE FUNCTION public.increment_completed_lessons()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.completed = TRUE AND OLD.completed = FALSE AND NEW.cohort_id IS NOT NULL THEN
UPDATE public.cohort_enrollments
SET completed_lessons = completed_lessons + 1,
last_activity_at = NOW()
WHERE cohort_id = NEW.cohort_id
AND user_id = NEW.user_id;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SET search_path = '';
-- Function to refresh student roster materialized view
-- Call this after bulk updates to cohort_enrollments, lesson_discussions, or course_forums
-- Uses CONCURRENTLY to avoid locking the view during refresh (requires unique index)
CREATE OR REPLACE FUNCTION public.refresh_student_roster_view()
RETURNS VOID AS $$
BEGIN
REFRESH MATERIALIZED VIEW CONCURRENTLY student_roster_view;
EXCEPTION
WHEN OTHERS THEN
-- Fallback to non-concurrent refresh if concurrent fails
-- (e.g., if unique index doesn't exist yet)
REFRESH MATERIALIZED VIEW student_roster_view;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- ============================================================================
-- AUTHENTICATION & USER MANAGEMENT
-- ============================================================================
-- Applications table (user profiles with roles)
CREATE TABLE IF NOT EXISTS applications (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
program TEXT NOT NULL CHECK (program IN ('bootcamp', 'accelerator', 'hackathon')),
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected', 'waitlisted')),
role TEXT CHECK (role IN ('student', 'teacher', 'admin')),
name TEXT NOT NULL,
email TEXT NOT NULL,
whatsapp TEXT,
location TEXT,
discord TEXT,
interests TEXT[],
motivation TEXT,
technical_experience TEXT,
commitment TEXT,
-- Diversity and career fields (both programs)
protected_class TEXT,
career_goals TEXT,
-- Scholarship fields (bootcamp only)
scholarship_requested BOOLEAN DEFAULT FALSE,
scholarship_category TEXT CHECK (scholarship_category IS NULL OR scholarship_category IN ('SC', 'OBC', 'EWS', 'DNT', 'Transgender')),
-- Accelerator-specific fields
track TEXT,
project_name TEXT,
project_description TEXT,
prototype_link TEXT,
tech_stack TEXT,
target_users TEXT,
production_needs TEXT,
team_size INTEGER,
current_stage TEXT CHECK (current_stage IS NULL OR current_stage IN ('Prototype/MVP', 'Beta with users', 'Live in production')),
funding TEXT CHECK (funding IS NULL OR funding IN ('For-profit', 'Non-profit', 'Not sure yet')),
-- Review fields
assigned_reviewer_id UUID REFERENCES auth.users(id),
assignment_date TIMESTAMPTZ,
reviewed_by UUID REFERENCES auth.users(id),
reviewed_at TIMESTAMPTZ,
decision_note TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_applications_user_id ON applications(user_id);
CREATE INDEX IF NOT EXISTS idx_applications_program ON applications(program);
CREATE INDEX IF NOT EXISTS idx_applications_status ON applications(status);
CREATE INDEX IF NOT EXISTS idx_applications_role ON applications(role);
CREATE INDEX IF NOT EXISTS idx_applications_assigned_reviewer ON applications(assigned_reviewer_id);
CREATE INDEX IF NOT EXISTS idx_applications_created_at ON applications(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_applications_scholarship ON applications(scholarship_requested) WHERE scholarship_requested = TRUE;
-- Profiles table (extended user info)
CREATE TABLE IF NOT EXISTS profiles (
id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
email TEXT,
full_name TEXT,
display_name TEXT,
avatar_url TEXT,
bio TEXT,
role TEXT DEFAULT 'student' CHECK (role IN ('student', 'teacher', 'admin')),
timezone TEXT DEFAULT 'UTC',
preferences JSONB DEFAULT '{}',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
-- Auth logs table (security audit)
CREATE TABLE IF NOT EXISTS auth_logs (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
event_type TEXT NOT NULL,
ip_address INET,
user_agent TEXT,
details JSONB,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_auth_logs_user_id ON auth_logs(user_id);
CREATE INDEX IF NOT EXISTS idx_auth_logs_event_type ON auth_logs(event_type);
CREATE INDEX IF NOT EXISTS idx_auth_logs_created_at ON auth_logs(created_at DESC);
-- ============================================================================
-- COURSE STRUCTURE
-- ============================================================================
-- Courses table
CREATE TABLE IF NOT EXISTS courses (
id BIGSERIAL PRIMARY KEY,
slug TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
description TEXT,
thumbnail_url TEXT,
track TEXT CHECK (track IN ('animal_advocacy', 'climate', 'ai_safety', 'general')),
difficulty TEXT CHECK (difficulty IN ('beginner', 'intermediate', 'advanced')),
is_published BOOLEAN DEFAULT FALSE,
is_cohort_based BOOLEAN DEFAULT TRUE,
default_duration_weeks INTEGER DEFAULT 8,
enrollment_type TEXT DEFAULT 'open' CHECK (enrollment_type IN ('open', 'cohort_only', 'hybrid')),
created_by UUID REFERENCES auth.users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_courses_slug ON courses(slug);
CREATE INDEX IF NOT EXISTS idx_courses_published ON courses(is_published) WHERE is_published = TRUE;
CREATE INDEX IF NOT EXISTS idx_courses_track ON courses(track);
CREATE INDEX IF NOT EXISTS idx_courses_created_by ON courses(created_by);
-- Modules table
CREATE TABLE IF NOT EXISTS modules (
id BIGSERIAL PRIMARY KEY,
course_id BIGINT REFERENCES courses(id) ON DELETE CASCADE,
title TEXT NOT NULL,
description TEXT,
order_index INTEGER NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_modules_course ON modules(course_id, order_index);
-- Lessons table
CREATE TABLE IF NOT EXISTS lessons (
id BIGSERIAL PRIMARY KEY,
module_id BIGINT REFERENCES modules(id) ON DELETE CASCADE,
title TEXT NOT NULL,
slug TEXT NOT NULL,
content TEXT,
video_url TEXT,
youtube_url TEXT,
duration_minutes INTEGER,
order_index INTEGER NOT NULL,
is_preview BOOLEAN DEFAULT FALSE,
resources JSONB DEFAULT '[]',
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(module_id, slug),
CONSTRAINT unique_lessons_slug UNIQUE (slug)
);
CREATE INDEX IF NOT EXISTS idx_lessons_module ON lessons(module_id, order_index);
CREATE INDEX IF NOT EXISTS idx_lessons_slug ON lessons(slug);
-- ============================================================================
-- COHORT SYSTEM
-- ============================================================================
-- NOTE: Cohorts must be defined before lesson_progress due to FK dependency
--
-- TABLES WITH cohort_id FOREIGN KEY:
-- - cohort_enrollments (CASCADE delete)
-- - cohort_schedules (CASCADE delete)
-- - lesson_progress (SET NULL on delete)
-- - enrollments (SET NULL on delete)
-- - lesson_discussions (CASCADE delete)
-- - course_forums (CASCADE delete)
-- - quiz_attempts (SET NULL on delete)
--
-- DELETE BEHAVIOR:
-- - CASCADE: Child records deleted when cohort is deleted
-- - SET NULL: cohort_id set to NULL, record preserved
--
-- DATA INTEGRITY RATIONALE:
-- CASCADE is used for cohort-scoped data where records lose meaning without
-- the cohort context (enrollments, schedules, discussions, forums).
-- SET NULL is used for historical records where student work should be
-- preserved even if the cohort is deleted (lesson_progress, quiz_attempts).
--
-- QUERY PERFORMANCE:
-- All cohort_id columns have B-tree indexes (idx_*_cohort) for efficient
-- filtering by cohort. Enables fast WHERE cohort_id = ? queries for
-- teacher dashboards, progress reports, and roster views.
--
-- MIGRATION NOTES:
-- For existing databases, use migrations/add_cohort_id_columns.sql to add
-- cohort_id columns to tables that may lack them. For fresh installs, this
-- schema.sql file includes all cohort_id columns by default.
--
-- COHORT FOREIGN KEY DEPENDENCY TREE:
--
-- cohorts (id: UUID)
-- ├── cohort_enrollments (CASCADE) ─── tracks student membership
-- ├── cohort_schedules (CASCADE) ───── defines module unlock dates
-- ├── lesson_progress (SET NULL) ───── preserves completion history
-- ├── enrollments (SET NULL) ────────── legacy course enrollment
-- ├── lesson_discussions (CASCADE) ─── cohort-scoped Q&A threads
-- ├── course_forums (CASCADE) ──────── cohort-scoped forum posts
-- └── quiz_attempts (SET NULL) ──────── preserves quiz history
--
-- COHORT_ID INDEXES (Performance Optimization):
-- - idx_cohort_enrollments_cohort (cohort_enrollments table)
-- - idx_cohort_schedules_cohort (cohort_schedules table)
-- - idx_progress_cohort (lesson_progress table)
-- - idx_enrollments_cohort (enrollments table)
-- - idx_lesson_discussions_cohort (lesson_discussions table)
-- - idx_course_forums_cohort (course_forums table)
-- - idx_quiz_attempts_cohort (quiz_attempts table)
--
-- ============================================================================
-- Cohorts table
CREATE TABLE IF NOT EXISTS cohorts (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
course_id BIGINT REFERENCES courses(id) ON DELETE CASCADE,
name TEXT NOT NULL,
start_date DATE NOT NULL,
end_date DATE,
status TEXT NOT NULL DEFAULT 'upcoming' CHECK (status IN ('upcoming', 'active', 'completed', 'archived')),
max_students INTEGER DEFAULT 50 CHECK (max_students > 0),
created_by UUID REFERENCES auth.users(id),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
CHECK (end_date IS NULL OR end_date >= start_date)
);
CREATE INDEX IF NOT EXISTS idx_cohorts_course ON cohorts(course_id);
CREATE INDEX IF NOT EXISTS idx_cohorts_status ON cohorts(status);
CREATE INDEX IF NOT EXISTS idx_cohorts_start_date ON cohorts(start_date DESC);
-- Cohort enrollments table
-- Primary enrollment tracking table for cohort-based learning
-- cohort_id: CASCADE delete - enrollment meaningless without cohort
-- Tracks student progress, status, and activity within specific cohort
CREATE TABLE IF NOT EXISTS cohort_enrollments (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
cohort_id UUID REFERENCES cohorts(id) ON DELETE CASCADE,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
enrolled_at TIMESTAMPTZ DEFAULT NOW(),
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'completed', 'dropped', 'paused')),
completed_lessons INTEGER DEFAULT 0,
progress JSONB DEFAULT '{"completed_lessons": 0, "completed_modules": 0, "percentage": 0}',
last_activity_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(cohort_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_cohort_enrollments_cohort ON cohort_enrollments(cohort_id);
CREATE INDEX IF NOT EXISTS idx_cohort_enrollments_user ON cohort_enrollments(user_id);
CREATE INDEX IF NOT EXISTS idx_cohort_enrollments_status ON cohort_enrollments(status);
-- Cohort schedules table (time-gating)
-- Time-gating configuration per cohort (module unlock/lock dates)
-- cohort_id: CASCADE delete - schedule only relevant to specific cohort
-- Enables cohort-specific pacing and content release schedules
CREATE TABLE IF NOT EXISTS cohort_schedules (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
cohort_id UUID REFERENCES cohorts(id) ON DELETE CASCADE,
module_id BIGINT REFERENCES modules(id) ON DELETE CASCADE,
unlock_date DATE NOT NULL,
lock_date DATE,
created_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(cohort_id, module_id),
CHECK (lock_date IS NULL OR lock_date > unlock_date)
);
CREATE INDEX IF NOT EXISTS idx_cohort_schedules_cohort ON cohort_schedules(cohort_id);
CREATE INDEX IF NOT EXISTS idx_cohort_schedules_unlock ON cohort_schedules(unlock_date);
-- Lesson progress table (depends on cohorts)
-- Individual lesson completion tracking across all courses
-- cohort_id: SET NULL on delete - preserves student progress history
-- Nullable to support both cohort-based and self-paced enrollment
-- Used for analytics, certificates, and progress dashboards
CREATE TABLE IF NOT EXISTS lesson_progress (
id BIGSERIAL PRIMARY KEY,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
lesson_id BIGINT REFERENCES lessons(id) ON DELETE CASCADE,
cohort_id UUID REFERENCES cohorts(id) ON DELETE SET NULL,
completed BOOLEAN DEFAULT FALSE,
completed_at TIMESTAMPTZ, -- Timestamp when lesson was marked complete
video_position_seconds INTEGER DEFAULT 0,
time_spent_seconds INTEGER DEFAULT 0,
watch_count INTEGER DEFAULT 1, -- Number of times lesson was watched/revisited
last_accessed_at TIMESTAMPTZ DEFAULT NOW(),
created_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE(user_id, lesson_id)
);
CREATE INDEX IF NOT EXISTS idx_progress_user ON lesson_progress(user_id);
CREATE INDEX IF NOT EXISTS idx_progress_lesson ON lesson_progress(lesson_id);
CREATE INDEX IF NOT EXISTS idx_progress_cohort ON lesson_progress(cohort_id);
CREATE INDEX IF NOT EXISTS idx_progress_completed ON lesson_progress(completed);
-- Enrollments table (legacy/hybrid)
-- Legacy/hybrid enrollment table (course-level tracking)
-- cohort_id: SET NULL on delete - preserves enrollment record
-- Coexists with cohort_enrollments for backward compatibility
-- Gradually being replaced by cohort_enrollments for cohort-based courses
CREATE TABLE IF NOT EXISTS enrollments (
id BIGSERIAL PRIMARY KEY,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
course_id BIGINT REFERENCES courses(id) ON DELETE CASCADE,
cohort_id UUID REFERENCES cohorts(id) ON DELETE SET NULL,
enrolled_at TIMESTAMPTZ DEFAULT NOW(),
completed_at TIMESTAMPTZ,
status TEXT DEFAULT 'active' CHECK (status IN ('active', 'completed', 'dropped', 'paused')),
progress_percentage INTEGER DEFAULT 0 CHECK (progress_percentage BETWEEN 0 AND 100),
UNIQUE(user_id, course_id)
);
CREATE INDEX IF NOT EXISTS idx_enrollments_user ON enrollments(user_id);
CREATE INDEX IF NOT EXISTS idx_enrollments_course ON enrollments(course_id);
CREATE INDEX IF NOT EXISTS idx_enrollments_cohort ON enrollments(cohort_id);
-- ============================================================================
-- DISCUSSIONS & FORUMS
-- ============================================================================
-- Lesson discussions table
-- Lesson-specific discussion threads (Q&A, peer interaction)
-- cohort_id: CASCADE delete - discussions scoped to cohort context
-- Enables cohort-isolated conversations (students only see their cohort)
-- Supports threaded replies via parent_id self-reference
-- NOTE: This table may be missing from src/types/generated.ts
-- Run `npm run db:types` after schema deployment to regenerate types
CREATE TABLE IF NOT EXISTS lesson_discussions (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
lesson_id BIGINT REFERENCES lessons(id) ON DELETE CASCADE,
cohort_id UUID REFERENCES cohorts(id) ON DELETE CASCADE,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
parent_id UUID REFERENCES lesson_discussions(id) ON DELETE CASCADE,
content TEXT NOT NULL CHECK (length(content) BETWEEN 1 AND 10000),
is_teacher_response BOOLEAN DEFAULT FALSE,
is_pinned BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_lesson_discussions_lesson ON lesson_discussions(lesson_id);
CREATE INDEX IF NOT EXISTS idx_lesson_discussions_cohort ON lesson_discussions(cohort_id);
CREATE INDEX IF NOT EXISTS idx_lesson_discussions_user ON lesson_discussions(user_id);
CREATE INDEX IF NOT EXISTS idx_lesson_discussions_parent ON lesson_discussions(parent_id);
-- Course forums table
-- Course-wide forum posts (announcements, general discussion)
-- cohort_id: CASCADE delete - forum posts scoped to cohort
-- Broader than lesson_discussions, covers course-level topics
-- Teachers can pin/lock posts for cohort-wide visibility
-- NOTE: This table may be missing from src/types/generated.ts
-- Run `npm run db:types` after schema deployment to regenerate types
CREATE TABLE IF NOT EXISTS course_forums (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
course_id BIGINT REFERENCES courses(id) ON DELETE CASCADE,
cohort_id UUID REFERENCES cohorts(id) ON DELETE CASCADE,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
title TEXT NOT NULL CHECK (length(title) BETWEEN 1 AND 200),
content TEXT NOT NULL CHECK (length(content) BETWEEN 1 AND 10000),
is_pinned BOOLEAN DEFAULT FALSE,
is_locked BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_course_forums_course ON course_forums(course_id);
CREATE INDEX IF NOT EXISTS idx_course_forums_cohort ON course_forums(cohort_id);
-- Forum replies table
CREATE TABLE IF NOT EXISTS forum_replies (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
forum_post_id UUID REFERENCES course_forums(id) ON DELETE CASCADE,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
content TEXT NOT NULL CHECK (length(content) BETWEEN 1 AND 10000),
is_teacher_response BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_forum_replies_post ON forum_replies(forum_post_id);
-- ============================================================================
-- MATERIALIZED VIEWS
-- ============================================================================
--
-- student_roster_view
-- -------------------
-- Purpose: Pre-aggregated student roster with progress and engagement metrics
--
-- Columns:
-- - cohort_id: UUID reference to cohorts
-- - user_id: UUID reference to auth.users
-- - name: Student name (from applications or profiles)
-- - email: Student email (from applications or profiles)
-- - enrolled_at: Enrollment timestamp
-- - status: Enrollment status (active/completed/dropped/paused)
-- - last_activity_at: Last activity timestamp
-- - completed_lessons: Count of completed lessons
-- - discussion_posts: Count of lesson discussion posts
-- - forum_posts: Count of course forum posts
--
-- Usage:
-- SELECT * FROM student_roster_view WHERE cohort_id = ?;
--
-- Refresh:
-- SELECT refresh_student_roster_view();
--
-- Performance:
-- - Indexed on cohort_id, user_id, status, last_activity_at
-- - Refresh time: <2 seconds for typical cohort sizes (<500 students)
-- - Query time: <200ms for filtered queries
--
-- Dependencies:
-- - cohort_enrollments (base table)
-- - applications (student identity)
-- - profiles (fallback identity)
-- - lesson_discussions (aggregated counts)
-- - course_forums (aggregated counts)
--
-- ============================================================================
CREATE MATERIALIZED VIEW IF NOT EXISTS student_roster_view AS
SELECT
ce.cohort_id,
ce.user_id,
COALESCE(a.name, p.full_name, p.email) AS name,
COALESCE(a.email, p.email) AS email,
ce.enrolled_at,
ce.status,
ce.last_activity_at,
ce.completed_lessons,
COALESCE(ld.discussion_posts, 0) AS discussion_posts,
COALESCE(cf.forum_posts, 0) AS forum_posts
FROM cohort_enrollments ce
LEFT JOIN applications a ON ce.user_id = a.user_id
LEFT JOIN profiles p ON ce.user_id = p.id
LEFT JOIN (
SELECT
user_id,
cohort_id,
COUNT(*) AS discussion_posts
FROM lesson_discussions
GROUP BY user_id, cohort_id
) ld ON ce.user_id = ld.user_id AND ce.cohort_id = ld.cohort_id
LEFT JOIN (
SELECT
user_id,
cohort_id,
COUNT(*) AS forum_posts
FROM course_forums
GROUP BY user_id, cohort_id
) cf ON ce.user_id = cf.user_id AND ce.cohort_id = cf.cohort_id;
-- Indexes for student_roster_view (materialized view)
CREATE INDEX IF NOT EXISTS idx_student_roster_cohort
ON student_roster_view(cohort_id);
CREATE INDEX IF NOT EXISTS idx_student_roster_user
ON student_roster_view(user_id);
CREATE INDEX IF NOT EXISTS idx_student_roster_status
ON student_roster_view(status);
CREATE INDEX IF NOT EXISTS idx_student_roster_last_activity
ON student_roster_view(last_activity_at DESC);
-- Unique index required for REFRESH MATERIALIZED VIEW CONCURRENTLY
-- Ensures each student appears only once per cohort
CREATE UNIQUE INDEX IF NOT EXISTS idx_student_roster_unique_cohort_user
ON student_roster_view(cohort_id, user_id);
-- ============================================================================
-- ASSESSMENTS - QUIZZES
-- ============================================================================
-- Quizzes table
CREATE TABLE IF NOT EXISTS quizzes (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
course_id BIGINT REFERENCES courses(id) ON DELETE CASCADE,
module_id BIGINT REFERENCES modules(id) ON DELETE SET NULL,
lesson_id BIGINT REFERENCES lessons(id) ON DELETE SET NULL,
title TEXT NOT NULL,
description TEXT,
time_limit_minutes INTEGER,
passing_score INTEGER DEFAULT 70 CHECK (passing_score BETWEEN 0 AND 100),
max_attempts INTEGER DEFAULT 3,
randomize_questions BOOLEAN DEFAULT FALSE,
show_correct_answers BOOLEAN DEFAULT TRUE,
show_results_immediately BOOLEAN DEFAULT TRUE,
is_published BOOLEAN DEFAULT FALSE,
available_from TIMESTAMPTZ,
available_until TIMESTAMPTZ,
created_by UUID REFERENCES auth.users(id),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_quizzes_course ON quizzes(course_id);
CREATE INDEX IF NOT EXISTS idx_quizzes_module ON quizzes(module_id);
CREATE INDEX IF NOT EXISTS idx_quizzes_lesson ON quizzes(lesson_id);
CREATE INDEX IF NOT EXISTS idx_quizzes_published ON quizzes(is_published);
-- Quiz questions table
CREATE TABLE IF NOT EXISTS quiz_questions (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
quiz_id UUID REFERENCES quizzes(id) ON DELETE CASCADE,
question_type TEXT NOT NULL CHECK (question_type IN ('multiple_choice', 'true_false', 'short_answer', 'essay', 'multiple_select')),
question_text TEXT NOT NULL,
points INTEGER DEFAULT 1 CHECK (points > 0),
order_index INTEGER NOT NULL,
options JSONB,
correct_answer TEXT,
answer_explanation TEXT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_quiz_questions_quiz ON quiz_questions(quiz_id, order_index);
-- Quiz attempts table
-- Student quiz submission records with grading
-- cohort_id: SET NULL on delete - preserves attempt history for analytics
-- Nullable to support both cohort-based and self-paced quizzes
-- Tracks attempt_number for max_attempts enforcement
CREATE TABLE IF NOT EXISTS quiz_attempts (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
quiz_id UUID REFERENCES quizzes(id) ON DELETE CASCADE,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
cohort_id UUID REFERENCES cohorts(id) ON DELETE SET NULL,
attempt_number INTEGER NOT NULL,
started_at TIMESTAMPTZ DEFAULT NOW(),
submitted_at TIMESTAMPTZ,
time_taken_seconds INTEGER,
score DECIMAL(5,2) CHECK (score BETWEEN 0 AND 100),
total_points INTEGER,
points_earned INTEGER,
passed BOOLEAN,
answers_json JSONB DEFAULT '[]',
grading_status TEXT DEFAULT 'pending' CHECK (grading_status IN ('pending', 'auto_graded', 'needs_review')),
graded_by UUID REFERENCES auth.users(id),
graded_at TIMESTAMPTZ,
UNIQUE(quiz_id, user_id, attempt_number)
);
CREATE INDEX IF NOT EXISTS idx_quiz_attempts_quiz ON quiz_attempts(quiz_id);
CREATE INDEX IF NOT EXISTS idx_quiz_attempts_user ON quiz_attempts(user_id);
CREATE INDEX IF NOT EXISTS idx_quiz_attempts_cohort ON quiz_attempts(cohort_id);
-- ============================================================================
-- ASSESSMENTS - ASSIGNMENTS
-- ============================================================================
-- Assignments table
CREATE TABLE IF NOT EXISTS assignments (