-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path(supabase)db.sql
More file actions
1582 lines (1383 loc) · 51.6 KB
/
(supabase)db.sql
File metadata and controls
1582 lines (1383 loc) · 51.6 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
-- ----------------------------
-- Create `profiles` table
-- ----------------------------
create table if not exists
public.profiles (
id uuid not null,
name text null,
role text not null default 'student'::text,
avatar_url text null,
email text null,
constraint profiles_pkey primary key (id),
constraint profiles_id_fkey foreign key (id) references auth.users (id) on delete cascade
);
-- ----------------------------
-- Enable RLS for `profiles`
-- ----------------------------
alter table public.profiles enable row level security;
-- ----------------------------
-- Create policies for `profiles`
-- ----------------------------
drop policy if exists "Public profiles are viewable by everyone." on public.profiles;
create policy "Public profiles are viewable by everyone." on public.profiles for
select
using (true);
drop policy if exists "Users can insert their own profile." on public.profiles;
create policy "Users can insert their own profile." on public.profiles for
insert
with check (auth.uid () = id);
drop policy if exists "Users can update own profile." on public.profiles;
create policy "Users can update own profile." on public.profiles for
update
using (auth.uid () = id);
-- ----------------------------
-- Create `student_keys` table
-- ----------------------------
create table if not exists
public.student_keys (
id bigint generated by default as identity,
student_id uuid not null,
secret_key uuid not null default gen_random_uuid (),
created_at timestamp with time zone not null default now(),
constraint student_keys_pkey primary key (id),
constraint student_keys_student_id_key unique (student_id),
constraint student_keys_secret_key_key unique (secret_key),
constraint student_keys_student_id_fkey foreign key (student_id) references public.profiles (id) on delete cascade
);
-- ----------------------------
-- Enable RLS for `student_keys`
-- ----------------------------
alter table public.student_keys enable row level security;
-- ----------------------------
-- Create policies for `student_keys`
-- ----------------------------
drop policy if exists "Students can view their own secret key." on public.student_keys;
create policy "Students can view their own secret key." on public.student_keys for
select
using (auth.uid () = student_id);
-- ----------------------------
-- Create `parent_student_links` table
-- ----------------------------
create table if not exists
public.parent_student_links (
id bigint generated by default as identity,
parent_id uuid not null,
student_id uuid not null,
created_at timestamp with time zone not null default now(),
constraint parent_student_links_pkey primary key (id),
constraint parent_student_links_parent_id_fkey foreign key (parent_id) references public.profiles (id) on delete cascade,
constraint parent_student_links_student_id_fkey foreign key (student_id) references public.profiles (id) on delete cascade,
constraint parent_student_links_parent_id_student_id_key unique (parent_id, student_id)
);
-- ----------------------------
-- Enable RLS for `parent_student_links`
-- ----------------------------
alter table public.parent_student_links enable row level security;
-- ----------------------------
-- Create policies for `parent_student_links`
-- ----------------------------
drop policy if exists "Parents can view their own links." on public.parent_student_links;
create policy "Parents can view their own links." on public.parent_student_links for
select
using (auth.uid () = parent_id);
-- ----------------------------
-- Set up storage for avatars
-- ----------------------------
insert into
storage.buckets (id, name, public)
values
('avatars', 'avatars', true)
on conflict (id) do nothing;
drop policy if exists "Avatar images are publicly accessible." on storage.objects;
create policy "Avatar images are publicly accessible." on storage.objects for
select
using (bucket_id = 'avatars');
drop policy if exists "Anyone can upload an avatar." on storage.objects;
create policy "Anyone can upload an avatar." on storage.objects for
insert
with check (bucket_id = 'avatars');
drop policy if exists "Users can update their own avatars." on storage.objects;
create policy "Users can update their own avatars." on storage.objects for
update
using (auth.uid () = owner)
with check (bucket_id = 'avatars');
drop policy if exists "Users can delete their own avatars." on storage.objects;
create policy "Users can delete their own avatars." on storage.objects for
delete
using (auth.uid () = owner);
-- ----------------------------
-- Create `exam_settings` table
-- ----------------------------
create table if not exists
public.exam_settings (
id uuid not null default gen_random_uuid (),
user_id uuid not null,
exam_name text not null,
created_at timestamp with time zone not null default now(),
constraint exam_settings_pkey primary key (id),
constraint exam_settings_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade
);
alter table public.exam_settings enable row level security;
drop policy if exists "Users can view their own exam settings." on public.exam_settings;
create policy "Users can view their own exam settings." on public.exam_settings for
select
using (auth.uid () = user_id);
drop policy if exists "Users can insert their own exam settings." on public.exam_settings;
create policy "Users can insert their own exam settings." on public.exam_settings for
insert
with check (auth.uid () = user_id);
-- ----------------------------
-- Create `subjects` table
-- ----------------------------
create table if not exists
public.subjects (
id bigint generated by default as identity,
user_id uuid not null,
name text not null,
created_at timestamp with time zone not null default now(),
constraint subjects_pkey primary key (id),
constraint subjects_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade,
constraint subjects_user_id_name_key unique (user_id, name)
);
alter table public.subjects enable row level security;
drop policy if exists "Users can manage their own subjects." on public.subjects;
create policy "Users can manage their own subjects." on public.subjects for all using (auth.uid () = user_id);
-- ----------------------------
-- Create `chapters` table
-- ----------------------------
create table if not exists
public.chapters (
id bigint generated by default as identity,
user_id uuid not null,
subject_id bigint not null,
name text not null,
created_at timestamp with time zone not null default now(),
constraint chapters_pkey primary key (id),
constraint chapters_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade,
constraint chapters_subject_id_fkey foreign key (subject_id) references public.subjects (id) on delete cascade,
constraint chapters_subject_id_name_key unique (subject_id, name)
);
alter table public.chapters enable row level security;
drop policy if exists "Users can manage their own chapters." on public.chapters;
create policy "Users can manage their own chapters." on public.chapters for all using (auth.uid () = user_id);
-- ----------------------------
-- Create `modules` table
-- ----------------------------
create table if not exists
public.modules (
id bigint generated by default as identity,
user_id uuid not null,
name text not null,
created_at timestamp with time zone not null default now(),
constraint modules_pkey primary key (id),
constraint modules_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade,
constraint modules_user_id_name_key unique (user_id, name)
);
alter table public.modules enable row level security;
drop policy if exists "Users can manage their own modules." on public.modules;
create policy "Users can manage their own modules." on public.modules for all using (auth.uid () = user_id);
-- ----------------------------
-- Create `progress` table
-- ----------------------------
create table if not exists
public.progress (
id bigint generated by default as identity,
user_id uuid not null,
chapter_id bigint not null,
module_id bigint not null,
completed boolean not null default false,
created_at timestamp with time zone not null default now(),
completed_at timestamp with time zone null,
constraint progress_pkey primary key (id),
constraint progress_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade,
constraint progress_chapter_id_fkey foreign key (chapter_id) references public.chapters (id) on delete cascade,
constraint progress_module_id_fkey foreign key (module_id) references public.modules (id) on delete cascade,
constraint progress_user_id_chapter_id_module_id_key unique (user_id, chapter_id, module_id)
);
alter table public.progress enable row level security;
drop policy if exists "Users can manage their own progress." on public.progress;
create policy "Users can manage their own progress." on public.progress for all using (auth.uid () = user_id);
-- ----------------------------
-- Create `goals` table
-- ----------------------------
create table if not exists
public.goals (
id bigint generated by default as identity,
user_id uuid not null,
goal_text text not null,
is_completed boolean not null default false,
created_at timestamp with time zone not null default now(),
completed_at timestamp with time zone null,
constraint goals_pkey primary key (id),
constraint goals_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade
);
alter table public.goals enable row level security;
drop policy if exists "Users can manage their own goals." on public.goals;
create policy "Users can manage their own goals." on public.goals for all using (auth.uid () = user_id);
-- ----------------------------
-- Create `question_logs` table
-- ----------------------------
create table if not exists
public.question_logs (
id bigint generated by default as identity,
user_id uuid not null,
chapter_id bigint not null,
total_questions integer not null,
correct_questions integer not null,
incorrect_questions integer not null,
created_at timestamp with time zone not null default now(),
constraint question_logs_pkey primary key (id),
constraint question_logs_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade,
constraint question_logs_chapter_id_fkey foreign key (chapter_id) references public.chapters (id) on delete cascade
);
alter table public.question_logs enable row level security;
drop policy if exists "Users can manage their own question logs." on public.question_logs;
create policy "Users can manage their own question logs." on public.question_logs for all using (auth.uid () = user_id);
-- ----------------------------
-- Create `test_categories` table
-- ----------------------------
create table if not exists
public.test_categories (
id bigint generated by default as identity,
user_id uuid not null,
name text not null,
created_at timestamp with time zone not null default now(),
constraint test_categories_pkey primary key (id),
constraint test_categories_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade,
constraint test_categories_user_id_name_key unique (user_id, name)
);
alter table public.test_categories enable row level security;
drop policy if exists "Users can manage their own test categories." on public.test_categories;
create policy "Users can manage their own test categories." on public.test_categories for all using (auth.uid () = user_id);
-- ----------------------------
-- Create `test_results` table
-- ----------------------------
create table if not exists
public.test_results (
id bigint generated by default as identity,
user_id uuid not null,
name text not null,
test_date timestamp with time zone not null,
test_type text not null,
subjects integer[] null,
chapters integer[] null,
total_marks numeric not null,
marks_for_correct numeric not null,
negative_marks numeric not null,
correct_questions integer null,
incorrect_questions integer null,
unattempted_questions integer null,
total_marks_obtained numeric null,
status text not null default 'completed'::text,
category_id bigint null,
created_at timestamp with time zone not null default now(),
constraint test_results_pkey primary key (id),
constraint test_results_user_id_fkey foreign key (user_id) references auth.users (id) on delete cascade,
constraint test_results_category_id_fkey foreign key (category_id) references public.test_categories (id) on delete set null
);
alter table public.test_results enable row level security;
drop policy if exists "Users can manage their own test results." on public.test_results;
create policy "Users can manage their own test results." on public.test_results for all using (auth.uid () = user_id);
-- ----------------------------
-- Drop existing functions and triggers before creating new ones
-- ----------------------------
drop function if exists public.handle_new_user() cascade;
drop function if exists public.create_student_key_if_not_exists(p_student_id uuid) cascade;
drop function if exists public.get_goal_analytics_data(p_user_id uuid) cascade;
drop function if exists public.get_linked_students(p_parent_id uuid) cascade;
drop function if exists public.get_question_analytics_data(p_user_id uuid) cascade;
drop function if exists public.get_student_analysis_data(p_user_id uuid) cascade;
drop function if exists public.get_student_dashboard_overview(p_user_id uuid) cascade;
drop function if exists public.get_test_analytics_data(p_user_id uuid) cascade;
drop function if exists public.get_user_progress(p_user_id uuid) cascade;
drop function if exists public.link_student_by_key(p_parent_id uuid, p_secret_key uuid) cascade;
drop function if exists public.reset_student_key(p_user_id uuid) cascade;
drop function if exists public.setup_user_exam(p_user_id uuid, p_exam_name text, p_subjects text[], p_modules text[]) cascade;
drop function if exists public.update_test_result(p_test_id bigint, p_name text, p_category_id bigint, p_test_date timestamp with time zone, p_total_marks numeric, p_marks_for_correct numeric, p_negative_marks numeric, p_correct_questions integer, p_incorrect_questions integer, p_unattempted_questions integer, p_status text) cascade;
-- ----------------------------
-- Create `handle_new_user` function and trigger
-- ----------------------------
create function
public.handle_new_user () returns trigger as $$
begin
insert into public.profiles (id, name, role, email)
values (new.id, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'role', new.email);
return new;
end;
$$ language plpgsql security definer;
create trigger on_auth_user_created
after insert on auth.users for each row
execute procedure public.handle_new_user ();
-- ----------------------------
-- Create `create_student_key_if_not_exists` function
-- ----------------------------
create function
public.create_student_key_if_not_exists (p_student_id uuid) returns uuid as $$
declare
existing_key uuid;
new_key uuid;
begin
select secret_key into existing_key from public.student_keys where student_id = p_student_id;
if existing_key is not null then
return existing_key;
else
insert into public.student_keys (student_id) values (p_student_id) returning secret_key into new_key;
return new_key;
end if;
end;
$$ language plpgsql security definer;
-- ----------------------------
-- Create `link_student_by_key` function
-- ----------------------------
create function
public.link_student_by_key (p_parent_id uuid, p_secret_key uuid) returns void as $$
declare
student_user_id uuid;
begin
select student_id into student_user_id from public.student_keys where secret_key = p_secret_key;
if student_user_id is null then
raise exception 'Invalid secret key';
end if;
insert into public.parent_student_links (parent_id, student_id)
values (p_parent_id, student_user_id)
on conflict (parent_id, student_id) do nothing;
end;
$$ language plpgsql security definer;
-- ----------------------------
-- Create `get_linked_students` function
-- ----------------------------
create function
public.get_linked_students (p_parent_id uuid) returns table (id uuid, name text) as $$
begin
return query
select p.id, p.name
from public.parent_student_links psl
join public.profiles p on psl.student_id = p.id
where psl.parent_id = p_parent_id;
end;
$$ language plpgsql;
-- ----------------------------
-- Create `setup_user_exam` function
-- ----------------------------
create function
public.setup_user_exam(p_user_id uuid, p_exam_name text, p_subjects text[], p_modules text[]) returns void as $$
declare
subject_name text;
module_name text;
begin
-- Insert exam setting
insert into public.exam_settings (user_id, exam_name) values (p_user_id, p_exam_name);
-- Insert subjects
foreach subject_name in array p_subjects
loop
insert into public.subjects (user_id, name) values (p_user_id, subject_name);
end loop;
-- Insert modules
foreach module_name in array p_modules
loop
insert into public.modules (user_id, name) values (p_user_id, module_name);
end loop;
end;
$$ language plpgsql;
-- ----------------------------
-- Create `get_user_progress` function
-- ----------------------------
create function
public.get_user_progress (p_user_id uuid) returns json as $$
declare
result json;
begin
select
json_build_object(
'exam_setting', (select to_json(es) from exam_settings es where es.user_id = p_user_id limit 1),
'subjects', (select json_agg(s) from subjects s where s.user_id = p_user_id),
'chapters', (select json_agg(c) from chapters c where c.user_id = p_user_id),
'modules', (select json_agg(m) from modules m where m.user_id = p_user_id),
'progress', (select json_agg(p) from progress p where p.user_id = p_user_id)
)
into result;
return result;
end;
$$ language plpgsql;
-- ----------------------------
-- Create `get_goal_analytics_data` function
-- ----------------------------
create function
public.get_goal_analytics_data (p_user_id uuid) returns json as $$
begin
return (
select json_build_object(
'all_goals', (select json_agg(g) from goals g where g.user_id = p_user_id)
)
);
end;
$$ language plpgsql;
-- ----------------------------
-- Create `get_question_analytics_data` function
-- ----------------------------
create function
public.get_question_analytics_data (p_user_id uuid) returns json as $$
begin
return (
select json_build_object(
'subjects', (select json_agg(s) from subjects s where s.user_id = p_user_id),
'chapters', (select json_agg(c) from chapters c where c.user_id = p_user_id),
'logs', (select json_agg(ql) from question_logs ql where ql.user_id = p_user_id),
'categories', (select json_agg(tc) from test_categories tc where tc.user_id = p_user_id),
'tests', (select json_agg(tr) from test_results tr where tr.user_id = p_user_id)
)
);
end;
$$ language plpgsql;
-- ----------------------------
-- Create `get_test_analytics_data` function
-- ----------------------------
create function
public.get_test_analytics_data (p_user_id uuid) returns json as $$
begin
return (
select json_build_object(
'subjects', (select json_agg(s) from subjects s where s.user_id = p_user_id),
'chapters', (select json_agg(c) from chapters c where c.user_id = p_user_id),
'tests', (select json_agg(tr) from test_results tr where tr.user_id = p_user_id),
'categories', (select json_agg(tc) from test_categories tc where tc.user_id = p_user_id)
)
);
end;
$$ language plpgsql;
-- ----------------------------
-- Create `update_test_result` function
-- ----------------------------
create or replace function
public.update_test_result(
p_test_id bigint,
p_name text,
p_category_id bigint,
p_test_date timestamptz,
p_total_marks numeric,
p_marks_for_correct numeric,
p_negative_marks numeric,
p_correct_questions int,
p_incorrect_questions int,
p_unattempted_questions int,
p_status text
) returns void as $$
declare
total_obtained numeric;
begin
if p_status = 'completed' then
total_obtained := (p_correct_questions * p_marks_for_correct) - (p_incorrect_questions * p_negative_marks);
else
total_obtained := null;
end if;
update public.test_results
set
name = p_name,
category_id = p_category_id,
test_date = p_test_date,
total_marks = p_total_marks,
marks_for_correct = p_marks_for_correct,
negative_marks = p_negative_marks,
correct_questions = p_correct_questions,
incorrect_questions = p_incorrect_questions,
unattempted_questions = p_unattempted_questions,
total_marks_obtained = total_obtained,
status = p_status
where
id = p_test_id;
end;
$$ language plpgsql;
-- ----------------------------
-- Create `reset_student_key` function
-- ----------------------------
create or replace function public.reset_student_key(p_user_id uuid)
returns void
language plpgsql
security definer
as $function$
begin
-- Update the secret_key for the specified student_id
update public.student_keys
set secret_key = gen_random_uuid()
where student_id = p_user_id;
end;
$function$;
-- ----------------------------
-- Create `get_student_dashboard_overview` function
-- ----------------------------
create or replace function
public.get_student_dashboard_overview (p_user_id uuid) returns json as $$
declare
overview json;
begin
select
json_build_object(
'progress_percent',
(
select
case
when count(c.id) = 0 or count(m.id) = 0 then 0
else (count(p.id)::decimal / (count(distinct c.id) * count(distinct m.id)) * 100)
end
from
chapters c
cross join modules m
left join progress p on p.chapter_id = c.id
and p.module_id = m.id and p.completed = true and p.user_id = p_user_id
where
c.user_id = p_user_id and m.user_id = p_user_id
),
'subject_progress',
(
select
json_agg(sp)
from
(
select
s.id as subject_id,
s.name as subject_name,
case
when count(c.id) = 0 or count(m.id) = 0 then 0
else (count(p.id)::decimal / (count(distinct c.id) * count(distinct m.id)) * 100)
end as progress_percent
from
subjects s
cross join modules m
left join chapters c on c.subject_id = s.id
left join progress p on p.chapter_id = c.id
and p.module_id = m.id and p.completed = true and p.user_id = p_user_id
where
s.user_id = p_user_id and m.user_id = p_user_id
group by
s.id,
s.name
) sp
),
'today_goals',
(
select json_agg(g)
from goals g
where g.user_id = p_user_id and date(g.created_at at time zone 'Asia/Kolkata') = date(now() at time zone 'Asia/Kolkata')
),
'total_questions_logged', (select sum(total_questions) from question_logs where user_id = p_user_id),
'total_correct_questions', (select sum(correct_questions) from question_logs where user_id = p_user_id),
'total_incorrect_questions', (select sum(incorrect_questions) from question_logs where user_id = p_user_id),
'questions_last_7_days', (
select json_agg(q) from (
select (i.date)::date::text as date, coalesce(count(ql.id), 0) as count
from generate_series(
date_trunc('day', timezone('utc', now())) - interval '6 days',
date_trunc('day', timezone('utc', now())),
'1 day'
) as i(date)
left join question_logs ql on date_trunc('day', ql.created_at) = i.date and ql.user_id = p_user_id
group by i.date
order by i.date
) q
),
'total_tests_completed', (select count(*) from test_results where user_id = p_user_id and status = 'completed'),
'avg_test_score', (select avg((total_marks_obtained / total_marks) * 100) from test_results where user_id = p_user_id and status = 'completed'),
'highest_test_score', (select max((total_marks_obtained / total_marks) * 100) from test_results where user_id = p_user_id and status = 'completed'),
'upcoming_tests', (
select json_agg(t) from (
select id, name, test_date
from test_results
where user_id = p_user_id and status = 'scheduled' and test_date >= date_trunc('day', timezone('utc', now()))
order by test_date asc
limit 5
) t
),
'progress_over_time', (
with daily_progress as (
select
p.completed_at::date as date,
c.subject_id,
s.name as subject_name,
count(*) as completed_today
from progress p
join chapters c on p.chapter_id = c.id
join subjects s on c.subject_id = s.id
where p.user_id = p_user_id and p.completed = true and p.completed_at is not null
group by 1, 2, 3
),
cumulative_progress as (
select
date,
subject_name,
sum(completed_today) over (partition by subject_name order by date) as cumulative_completed
from daily_progress
),
total_modules as (
select c.subject_id, count(*) as total
from chapters c, modules m
where c.user_id = p_user_id and m.user_id = p_user_id
group by c.subject_id
),
daily_percentage as (
select
cp.date::text,
cp.subject_name,
(cp.cumulative_completed::decimal / tm.total * 100) as percentage
from cumulative_progress cp
join subjects s on s.name = cp.subject_name and s.user_id = p_user_id
join total_modules tm on tm.subject_id = s.id
)
select json_build_object(
'subjectNames', (select json_agg(distinct subject_name) from daily_percentage),
'chartData', (
select json_agg(
json_build_object(
'date', date,
'subjects', (select json_object_agg(subject_name, percentage) from daily_percentage where date = d.date)
)
)
from (select distinct date from daily_percentage) d
)
)
),
'progress_analysis', (
select json_build_object('subjects', json_agg(s_analysis))
from (
select
s.id,
s.name,
(
select count(*)
from chapters c, modules m
where c.subject_id = s.id and c.user_id = p_user_id and m.user_id = p_user_id
) as total_modules,
(
select count(*)
from progress p
join chapters c on p.chapter_id = c.id
where p.user_id = p_user_id and c.subject_id = s.id and p.completed = true
) as completed_modules,
(
select json_agg(c_analysis)
from (
select
c.id,
c.name,
(
select json_agg(m.name)
from progress p
join modules m on p.module_id = m.id
where p.user_id = p_user_id and p.chapter_id = c.id and p.completed = true
) as completed_modules
from chapters c
where c.subject_id = s.id and c.user_id = p_user_id
) c_analysis
) as chapters
from subjects s
where s.user_id = p_user_id
group by s.id
) s_analysis
)
)
into overview;
return overview;
end;
$$ language plpgsql;
-- ----------------------------
-- Create `get_student_analysis_data` function
-- ----------------------------
create or replace function
public.get_student_analysis_data (p_user_id uuid) returns json as $$
declare
analysis_data json;
begin
select
json_build_object(
'strengths', (
select json_agg(s)
from (
select
c.name as chapter_name,
s.name as subject_name,
(sum(ql.correct_questions)::decimal / sum(ql.total_questions)) * 100 as accuracy
from question_logs ql
join chapters c on ql.chapter_id = c.id
join subjects s on c.subject_id = s.id
where ql.user_id = p_user_id
group by c.id, s.id
having sum(ql.total_questions) > 10 -- Minimum 10 questions to be considered
and (sum(ql.correct_questions)::decimal / sum(ql.total_questions)) >= 0.8
order by accuracy desc
limit 5
) s
),
'weaknesses', (
select json_agg(w)
from (
select
c.name as chapter_name,
s.name as subject_name,
(sum(ql.correct_questions)::decimal / sum(ql.total_questions)) * 100 as accuracy
from question_logs ql
join chapters c on ql.chapter_id = c.id
join subjects s on c.subject_id = s.id
where ql.user_id = p_user_id
group by c.id, s.id
having sum(ql.total_questions) > 10 -- Minimum 10 questions to be considered
and (sum(ql.correct_questions)::decimal / sum(ql.total_questions)) < 0.6
order by accuracy asc
limit 5
) w
)
)
into analysis_data;
return analysis_data;
end;
$$ language plpgsql;
2nd query
-- This script fixes the security policy for the 'goals' table.
-- It allows users to properly update their goals (e.g., check them as complete).
-- 1. Drop the old, potentially conflicting policies on the 'goals' table.
DROP POLICY IF EXISTS "Users can manage their own goals." ON public.goals;
DROP POLICY IF EXISTS "Users can only update their own goals created today." ON public.goals;
-- 2. Create the new, correct policy.
-- This policy allows a user to perform any action (select, insert, update, delete)
-- on a goal, as long as they are the user who created it.
CREATE POLICY "Users can manage their own goals."
ON public.goals
FOR ALL
USING (auth.uid() = user_id);
3rd
-- Create the revisions table
CREATE TABLE IF NOT EXISTS public.revisions (
id bigint generated by default as identity primary key,
user_id uuid references public.profiles not null,
chapter_id bigint references public.chapters not null,
revision_count integer not null default 0,
created_at timestamp with time zone default timezone('utc'::text, now()) not null,
updated_at timestamp with time zone default timezone('utc'::text, now()) not null,
constraint revisions_user_id_chapter_id_key unique (user_id, chapter_id)
);
ALTER TABLE public.revisions ENABLE ROW LEVEL SECURITY;
-- Create policy for revisions table
DROP POLICY IF EXISTS "Enable all access for users based on user_id" ON "public"."revisions";
CREATE POLICY "Enable all access for users based on user_id" ON "public"."revisions"
AS PERMISSIVE FOR ALL
TO public
USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id);
-- Function to get revision data
CREATE OR REPLACE FUNCTION get_revision_data(p_user_id uuid)
RETURNS json
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
RETURN (
SELECT json_build_object(
'subjects', (
SELECT json_agg(
json_build_object(
'id', s.id,
'name', s.name,
'chapters', (
SELECT json_agg(
json_build_object(
'id', c.id,
'name', c.name,
'revision_count', coalesce(r.revision_count, 0)
)
)
FROM chapters c
LEFT JOIN revisions r ON c.id = r.chapter_id AND r.user_id = p_user_id
WHERE c.subject_id = s.id AND c.user_id = p_user_id
)
)
)
FROM subjects s
WHERE s.user_id = p_user_id
)
)
);
END;
$$;
-- Function to update revision count
CREATE OR REPLACE FUNCTION update_revision_count(p_user_id uuid, p_chapter_id bigint, p_increment int)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO revisions (user_id, chapter_id, revision_count, created_at, updated_at)
VALUES (p_user_id, p_chapter_id, p_increment, now(), now())
ON CONFLICT (user_id, chapter_id)
DO UPDATE SET
revision_count = GREATEST(0, revisions.revision_count + p_increment),
updated_at = now();
END;
$$;
4th
DROP TABLE IF EXISTS public.revisions;
DROP FUNCTION IF EXISTS public.get_revision_data();
DROP FUNCTION IF EXISTS public.update_revision_count(p_user_id uuid, p_chapter_id integer, p_increment integer);
CREATE TABLE public.revision_logs (
id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
user_id uuid NOT NULL REFERENCES public.profiles(id) ON DELETE CASCADE,
chapter_id integer NOT NULL REFERENCES public.chapters(id) ON DELETE CASCADE,
created_at timestamp with time zone NOT NULL DEFAULT now()
);
ALTER TABLE public.revision_logs ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users can manage their own revision logs"
ON public.revision_logs
FOR ALL
USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id);
CREATE OR REPLACE FUNCTION get_revision_data(p_user_id uuid)
RETURNS json
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
DECLARE
subjects_json json;
chapters_json json;
logs_json json;
BEGIN
SELECT json_agg(s) INTO subjects_json FROM (
SELECT id, name, created_at FROM public.subjects WHERE user_id = p_user_id ORDER BY created_at
) s;
SELECT json_agg(c) INTO chapters_json FROM (
SELECT id, subject_id, name, created_at FROM public.chapters WHERE user_id = p_user_id ORDER BY created_at
) c;
SELECT json_agg(l) INTO logs_json FROM (
SELECT id, user_id, chapter_id, created_at FROM public.revision_logs WHERE user_id = p_user_id
) l;
RETURN json_build_object(
'subjects', subjects_json,
'chapters', chapters_json,
'logs', logs_json
);
END;
$$;
CREATE OR REPLACE FUNCTION add_revision_log(p_user_id uuid, p_chapter_id integer)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
INSERT INTO public.revision_logs (user_id, chapter_id)
VALUES (p_user_id, p_chapter_id);
END;
$$;
CREATE OR REPLACE FUNCTION delete_latest_revision_log(p_user_id uuid, p_chapter_id integer)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
DECLARE
latest_log_id bigint;
BEGIN
SELECT id INTO latest_log_id
FROM public.revision_logs
WHERE user_id = p_user_id AND chapter_id = p_chapter_id
ORDER BY created_at DESC
LIMIT 1;
IF latest_log_id IS NOT NULL THEN
DELETE FROM public.revision_logs
WHERE id = latest_log_id;
END IF;
END;
$$;
GRANT EXECUTE ON FUNCTION public.get_revision_data(uuid) TO authenticated;