Spaces:
Running

File size: 20,424 Bytes
b146445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
-- =====================================================================
-- k12-math-rag-tutor : 001_schema.sql
-- Supabase(PostgreSQL 15+) SQL Editor μ—μ„œ ν†΅μ§Έλ‘œ μ‹€ν–‰ν•©λ‹ˆλ‹€. (μ—¬λŸ¬ 번 싀행해도 μ•ˆμ „)
-- μˆœμ„œ: 001_schema.sql -> 002_seed_units.sql
--
-- λ³΄μ•ˆ 원칙
--  * 학생 λΈŒλΌμš°μ €/νŒ¨λ“œλŠ” Supabase 에 직접 μ ‘μ†ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.
--    Gradio μ„œλ²„(HF Space)만 service_role ν‚€λ‘œ μ ‘μ†ν•©λ‹ˆλ‹€. (ν‚€λŠ” HF Secrets μ—λ§Œ 보관)
--  * κ·Έλž˜λ„ λ§ŒμΌμ„ λŒ€λΉ„ν•΄ λͺ¨λ“  ν…Œμ΄λΈ”μ— RLS λ₯Ό 켜고, μ •λ‹΅/해섀이 λ“ 
--    questions λŠ” service_role μ™Έμ—λŠ” 읽을 수 μ—†κ²Œ λ‘‘λ‹ˆλ‹€.
-- =====================================================================

-- ---------------------------------------------------------------------
-- 0. 곡톡: enum, updated_at 트리거
-- ---------------------------------------------------------------------
do $$ begin
  create type user_role      as enum ('student', 'teacher', 'admin');
exception when duplicate_object then null; end $$;

do $$ begin
  create type question_type  as enum ('multiple_choice', 'short_answer');
exception when duplicate_object then null; end $$;

do $$ begin
  create type difficulty     as enum ('low', 'mid', 'high');          -- ν•˜ / 쀑 / 상
exception when duplicate_object then null; end $$;

do $$ begin
  create type question_status as enum ('draft', 'review', 'published', 'retired');
exception when duplicate_object then null; end $$;

do $$ begin
  create type rights_status  as enum ('unreviewed', 'cleared', 'restricted'); -- 이용 ν—ˆλ½ 확인 μƒνƒœ
exception when duplicate_object then null; end $$;

do $$ begin
  create type session_status as enum ('in_progress', 'completed', 'abandoned');
exception when duplicate_object then null; end $$;

do $$ begin
  create type step_phase     as enum ('ladder', 'retry');             -- ν•˜β†’μ€‘β†’μƒ 사닀리 / μ˜€λ‹΅ μž¬λ„μ „
exception when duplicate_object then null; end $$;

do $$ begin
  create type step_outcome   as enum ('pending', 'correct', 'wrong');
exception when duplicate_object then null; end $$;

create or replace function set_updated_at()
returns trigger language plpgsql as $$
begin
  new.updated_at = now();
  return new;
end $$;

-- ---------------------------------------------------------------------
-- 1. κ΅μœ‘κ³Όμ • λ§ˆμŠ€ν„° (μ˜μ—­ 5개 / 단원 77개 = κ³ λ“± 42 + 쀑학ꡐ 볡슡 35)
--    'μˆœμ—΄κ³Ό μ‘°ν•©'은 κ³΅ν†΅μˆ˜ν•™κ³Ό ν™•λ₯ κ³Ό 톡계 μ–‘μͺ½μ— λ³΄μ΄μ§€λ§Œ 단원은 1κ°œμž…λ‹ˆλ‹€.
--    -> units(단원 1개) + unit_areas(μ˜μ—­ μ†Œμ†, λ‹€λŒ€λ‹€)
-- ---------------------------------------------------------------------
create table if not exists areas (
  area_id     text primary key,            -- common | math1 | math2 | stats | middle
  name_ko     text not null unique,
  sort_order  smallint not null
);

create table if not exists units (
  unit_id     text primary key,            -- U01~U42(κ³ λ“±), M01~M35(쀑학ꡐ). λ°”λ€Œμ§€ μ•ŠλŠ” μ‹λ³„μž
  name_ko     text not null unique,
  keywords    text[] not null default '{}',-- 04_tag_curriculum_meta.py ν‚€μ›Œλ“œ (1μ°¨ νƒœκΉ…μš©)
  sort_order  smallint not null
);

-- 학ꡐ급과 μ‹œλ²” 운영 λ²”μœ„ (이미 λ§Œλ“  DB 에도 μ•ˆμ „ν•˜κ²Œ μΆ”κ°€λ©λ‹ˆλ‹€)
alter table units add column if not exists level text not null default 'high';
alter table units add column if not exists pilot boolean not null default false;
do $$ begin
  if not exists (select 1 from pg_constraint where conname = 'units_level_check') then
    alter table units add constraint units_level_check check (level in ('high', 'middle'));
  end if;
end $$;

create table if not exists unit_areas (
  unit_id     text not null references units(unit_id) on delete cascade,
  area_id     text not null references areas(area_id) on delete cascade,
  sort_order  smallint not null,           -- μ˜μ—­ μ•ˆμ—μ„œμ˜ ν‘œμ‹œ μˆœμ„œ
  primary key (unit_id, area_id)
);

create table if not exists unit_prerequisites (
  unit_id          text not null references units(unit_id) on delete cascade,
  prerequisite_id  text not null references units(unit_id) on delete cascade,
  primary key (unit_id, prerequisite_id),
  check (unit_id <> prerequisite_id)
);

-- ---------------------------------------------------------------------
-- 2. μ‚¬μš©μž / ν•™κΈ‰
-- ---------------------------------------------------------------------
create table if not exists profiles (
  id          uuid primary key references auth.users(id) on delete cascade,
  email       text,
  name        text,
  role        user_role not null default 'student',   -- μ—­ν•  변경은 κ΄€λ¦¬μž(service_role)만
  created_at  timestamptz not null default now(),
  updated_at  timestamptz not null default now()
);
drop trigger if exists trg_profiles_updated on profiles;
create trigger trg_profiles_updated before update on profiles
  for each row execute function set_updated_at();

-- ꡬ글 둜그인으둜 auth.users κ°€ 생기면 profiles 행을 μžλ™ 생성 (κΈ°λ³Έ μ—­ν• : student)
create or replace function handle_new_user()
returns trigger language plpgsql security definer set search_path = public as $$
begin
  insert into public.profiles (id, email, name)
  values (
    new.id,
    new.email,
    coalesce(new.raw_user_meta_data ->> 'full_name', new.raw_user_meta_data ->> 'name')
  )
  on conflict (id) do nothing;
  return new;
end $$;

drop trigger if exists on_auth_user_created on auth.users;
create trigger on_auth_user_created after insert on auth.users
  for each row execute function handle_new_user();

create table if not exists classes (
  id                    uuid primary key default gen_random_uuid(),
  school_year           smallint not null,             -- 예: 2027
  grade                 smallint not null check (grade between 1 and 3),
  class_no              smallint not null check (class_no >= 1),
  homeroom_teacher_id   uuid references profiles(id) on delete set null,
  created_at            timestamptz not null default now(),
  unique (school_year, grade, class_no)
);

create table if not exists class_members (
  class_id    uuid not null references classes(id) on delete cascade,
  student_id  uuid not null references profiles(id) on delete cascade,
  student_no  smallint,                                -- 번호
  primary key (class_id, student_id)
);
create index if not exists idx_class_members_student on class_members(student_id);

-- ---------------------------------------------------------------------
-- 3. λ¬Έμ œμ€ν–‰
--    ETL(05 검증, 06 적재)을 ν†΅κ³Όν•œ λ¬Έν•­λ§Œ published κ°€ 될 수 μžˆμŠ΅λ‹ˆλ‹€.
-- ---------------------------------------------------------------------
create table if not exists questions (
  id                uuid primary key default gen_random_uuid(),

  -- 좜처 좔적 (재적재/쀑볡 λ°©μ§€)
  source            text not null check (source in ('aihub', 'ebsi', 'jsj50', 'teacher', 'other')),
  source_ref        text not null,                     -- 원본 λ¬Έν•­ μ‹λ³„μž (예: 2026_10_hs1_q07)
  source_meta       jsonb not null default '{}'::jsonb,-- 원본 메타(ai_hub_meta λ“±)
  rights_status     rights_status not null default 'unreviewed',

  -- λΆ„λ₯˜
  grade_code        text not null check (grade_code in ('e3','e4','e5','e6','m1','m2','m3','h1','h2','h3')),
  unit_id           text references units(unit_id),    -- νƒœκΉ… μ „μ—λŠ” null
  difficulty        difficulty,                        -- νƒœκΉ… μ „μ—λŠ” null
  score             smallint,                          -- EBSi 배점 (λ‚œμ΄λ„ μž„μ‹œ κΈ°μ€€)

  -- λ³Έλ¬Έ (μˆ˜μ‹μ€ LaTeX λ₯Ό $...$ 둜 감싸 μ €μž₯)
  qtype             question_type not null,
  stem_md           text not null,
  choices           jsonb not null default '[]'::jsonb,-- ["β‘ ...", "β‘‘..."]  κ°κ΄€μ‹λ§Œ
  figure_description text,                             -- VLM λ„ν˜• λ¬˜μ‚¬
  figure_path       text,                              -- Supabase Storage 경둜

  -- μ •λ‹΅/ν•΄μ„€ (ν•™μƒμ—κ²Œ 직접 λ…ΈμΆœ κΈˆμ§€)
  answer            text not null,                     -- 객관식: '1'~'5', 주관식: μ •λ‹΅ λ¬Έμžμ—΄
  accepted_answers  text[] not null default '{}',      -- λ™μΉ˜ ν‘œκΈ° ν—ˆμš© λͺ©λ‘
  solution_md       text,
  intent            text,                              -- 좜제 μ˜λ„

  -- ν’ˆμ§ˆ 관리
  verified          boolean not null default false,    -- 05 검증(μ •λ‹΅ν‘œΒ·ν•΄μ„€Β·μž¬κ³„μ‚°) 톡과 μ—¬λΆ€
  verify_note       text,
  status            question_status not null default 'draft',

  created_at        timestamptz not null default now(),
  updated_at        timestamptz not null default now(),

  unique (source, source_ref),

  -- 객관식은 선택지가 μžˆμ–΄μ•Ό 함
  check (qtype <> 'multiple_choice' or jsonb_array_length(choices) >= 2),

  -- κ²Œμ‹œ(published) 쑰건: λ‹¨μ›Β·λ‚œμ΄λ„ νƒœκΉ… + 검증 + 이용 ν—ˆλ½ 확인
  -- (νŒŒμΌλŸΏμ—μ„œ μ™„ν™”ν•˜λ €λ©΄ rights_status 쑰건만 μ‘°μ •ν•˜μ„Έμš”)
  check (
    status <> 'published'
    or (unit_id is not null and difficulty is not null
        and verified and rights_status = 'cleared'
        and solution_md is not null)
  )
);
drop trigger if exists trg_questions_updated on questions;
create trigger trg_questions_updated before update on questions
  for each row execute function set_updated_at();

-- 문제 λ½‘κΈ°μš©: 단원 x λ‚œμ΄λ„ x κ²Œμ‹œ μƒνƒœ
create index if not exists idx_questions_pick
  on questions (unit_id, difficulty) where status = 'published';
create index if not exists idx_questions_grade on questions (grade_code);

-- 학생 였λ₯˜ μ‹ κ³ 
create table if not exists question_reports (
  id           uuid primary key default gen_random_uuid(),
  question_id  uuid not null references questions(id) on delete cascade,
  reporter_id  uuid references profiles(id) on delete set null,
  reason       text not null,
  resolved     boolean not null default false,
  created_at   timestamptz not null default now()
);
create index if not exists idx_reports_open on question_reports (resolved, created_at);

-- ---------------------------------------------------------------------
-- 4. ν•™μŠ΅ μ„Έμ…˜ / 좜제 λͺ©λ‘ / μ‹œλ„
--    study_sessions   : 학생이 μ–΄λŠ λ‚  μ–΄λŠ 단원을 κ³¨λžλŠ”μ§€ (ν•˜λ£¨ 1μ„Έμ…˜/단원)
--    session_questions: κ·Έ μ„Έμ…˜μ—μ„œ λ‚Έ 문제 μˆœμ„œ (사닀리 + μ˜€λ‹΅ μž¬λ„μ „)
--    attempts         : 제좜 기둝 (ν•œ λ¬Έμ œμ— μ—¬λŸ¬ 번 제좜 κ°€λŠ₯)
-- ---------------------------------------------------------------------
create table if not exists study_sessions (
  id              uuid primary key default gen_random_uuid(),
  student_id      uuid not null references profiles(id) on delete cascade,
  session_date    date not null,
  unit_id         text not null references units(unit_id),
  status          session_status not null default 'in_progress',
  min_required    smallint not null default 3,         -- ν•˜λ£¨ μ΅œμ†Œ 문제 수
  time_limit_sec  integer  not null default 900,       -- 점심 15λΆ„
  started_at      timestamptz not null default now(),
  ended_at        timestamptz,
  unique (student_id, session_date, unit_id)
);
create index if not exists idx_sessions_student_date on study_sessions (student_id, session_date);
create index if not exists idx_sessions_date on study_sessions (session_date);

create table if not exists session_questions (
  id            uuid primary key default gen_random_uuid(),
  session_id    uuid not null references study_sessions(id) on delete cascade,
  seq           smallint not null,                     -- 좜제 μˆœμ„œ (μ΄μ–΄ν•˜κΈ° κΈ°μ€€)
  question_id   uuid not null references questions(id),
  phase         step_phase not null default 'ladder',
  stage         difficulty not null,                   -- μ–΄λŠ λ‚œμ΄λ„ λ‹¨κ³„μ—μ„œ λ‚˜μ™”λŠ”μ§€
  retry_of      uuid references session_questions(id), -- μž¬λ„μ „μ΄λ©΄ μ›λž˜ λ¬Έν•­ ν–‰
  outcome       step_outcome not null default 'pending',
  resolved_at   timestamptz,                           -- ν‹€λ¦° 문제λ₯Ό μž¬λ„μ „μœΌλ‘œ 맞힌 μ‹œκ°
  created_at    timestamptz not null default now(),
  unique (session_id, seq),
  check (phase = 'ladder' or retry_of is not null)
);
create index if not exists idx_sq_session on session_questions (session_id);
create index if not exists idx_sq_question on session_questions (question_id);

create table if not exists attempts (
  id                   uuid primary key default gen_random_uuid(),
  session_question_id  uuid not null references session_questions(id) on delete cascade,
  student_id           uuid not null references profiles(id) on delete cascade, -- 쑰회 편의용 쀑볡 μ €μž₯
  submitted_answer     text,
  is_correct           boolean not null,
  time_spent_sec       integer,
  scratch_path         text,                           -- 풀이 μŠ€μΌ€μΉ˜ 이미지(Storage 경둜)
  created_at           timestamptz not null default now()
);
create index if not exists idx_attempts_sq on attempts (session_question_id);
create index if not exists idx_attempts_student on attempts (student_id, created_at);

-- ---------------------------------------------------------------------
-- 5. 상담 / 일정 μ˜ˆμ™Έ
-- ---------------------------------------------------------------------
create table if not exists counseling_notes (
  id            uuid primary key default gen_random_uuid(),
  student_id    uuid not null references profiles(id) on delete cascade,
  teacher_id    uuid not null references profiles(id),
  reason        text not null,
  note          text,
  follow_up_on  date,
  created_at    timestamptz not null default now()
);
create index if not exists idx_counseling_student on counseling_notes (student_id, created_at);

create table if not exists calendar_exceptions (
  exception_date  date primary key,                    -- 학ꡐ 행사 λ“± 루틴 면제일
  title           text not null
);

-- ---------------------------------------------------------------------
-- 6. ꡐ사 λŒ€μ‹œλ³΄λ“œμš© λ·°: 학생 x λ‚ μ§œ x 단원 μš”μ•½
--    unresolved_count = ν‹€λ Έκ³  아직 μž¬λ„μ „μœΌλ‘œ ν•΄κ²°ν•˜μ§€ λͺ»ν•œ 문제 수
-- ---------------------------------------------------------------------
create or replace view v_student_day_unit
with (security_invoker = true) as
select
  s.id            as session_id,
  s.student_id,
  s.session_date,
  s.unit_id,
  s.status,
  count(*) filter (where sq.phase = 'ladder' and sq.outcome <> 'pending')                       as answered_count,
  count(*) filter (where sq.phase = 'ladder' and sq.outcome = 'correct')                        as correct_count,
  count(*) filter (where sq.phase = 'ladder' and sq.outcome = 'wrong' and sq.resolved_at is null) as unresolved_count
from study_sessions s
left join session_questions sq on sq.session_id = s.id
group by s.id;

-- ---------------------------------------------------------------------
-- 7. RLS (ν–‰ μˆ˜μ€€ λ³΄μ•ˆ)
-- ---------------------------------------------------------------------
create or replace function my_role()
returns user_role language sql stable security definer set search_path = public as $$
  select role from public.profiles where id = auth.uid()
$$;

create or replace function is_teacher_of(target_student uuid)
returns boolean language sql stable security definer set search_path = public as $$
  select exists (
    select 1
    from public.class_members cm
    join public.classes c on c.id = cm.class_id
    where cm.student_id = target_student
      and c.homeroom_teacher_id = auth.uid()
  )
$$;

alter table areas               enable row level security;
alter table units               enable row level security;
alter table unit_areas          enable row level security;
alter table unit_prerequisites  enable row level security;
alter table profiles            enable row level security;
alter table classes             enable row level security;
alter table class_members       enable row level security;
alter table questions           enable row level security;
alter table question_reports    enable row level security;
alter table study_sessions      enable row level security;
alter table session_questions   enable row level security;
alter table attempts            enable row level security;
alter table counseling_notes    enable row level security;
alter table calendar_exceptions enable row level security;

-- κ΅μœ‘κ³Όμ • λ§ˆμŠ€ν„°/일정: λ‘œκ·ΈμΈν•œ μ‚¬μš©μžλŠ” 읽기 κ°€λŠ₯
drop policy if exists read_areas on areas;
create policy read_areas on areas               for select to authenticated using (true);
drop policy if exists read_units on units;
create policy read_units on units               for select to authenticated using (true);
drop policy if exists read_unit_areas on unit_areas;
create policy read_unit_areas on unit_areas          for select to authenticated using (true);
drop policy if exists read_unit_prereq on unit_prerequisites;
create policy read_unit_prereq on unit_prerequisites for select to authenticated using (true);
drop policy if exists read_cal_exc on calendar_exceptions;
create policy read_cal_exc on calendar_exceptions for select to authenticated using (true);

-- ν”„λ‘œν•„: 본인 / λ‹΄μž„κ΅μ‚¬ / κ΄€λ¦¬μž
drop policy if exists read_profiles on profiles;
create policy read_profiles on profiles for select to authenticated
  using (id = auth.uid() or is_teacher_of(id) or my_role() = 'admin');

-- ν•™κΈ‰ (classes <-> class_members κ°€ μ„œλ‘œ μ°Έμ‘°ν•˜λ©΄ μ •μ±… λ¬΄ν•œ μž¬κ·€κ°€ λ‚˜λ―€λ‘œ
-- RLS λ₯Ό μš°νšŒν•˜λŠ” security definer ν•¨μˆ˜λ‘œ νŒμ •ν•©λ‹ˆλ‹€)
create or replace function is_class_member(cid uuid)
returns boolean language sql stable security definer set search_path = public as $$
  select exists (select 1 from public.class_members where class_id = cid and student_id = auth.uid())
$$;

create or replace function is_homeroom_of(cid uuid)
returns boolean language sql stable security definer set search_path = public as $$
  select exists (select 1 from public.classes where id = cid and homeroom_teacher_id = auth.uid())
$$;

drop policy if exists read_classes on classes;
create policy read_classes on classes for select to authenticated
  using (homeroom_teacher_id = auth.uid() or my_role() = 'admin' or is_class_member(id));

drop policy if exists read_class_members on class_members;
create policy read_class_members on class_members for select to authenticated
  using (student_id = auth.uid() or my_role() = 'admin' or is_homeroom_of(class_id));

-- λ¬Έμ œμ€ν–‰(questions): authenticated 용 정책을 λ§Œλ“€μ§€ μ•ŠμŒ => service_role 만 μ ‘κ·Ό

-- ν•™μŠ΅ 기둝: 본인 / λ‹΄μž„κ΅μ‚¬ / κ΄€λ¦¬μž 읽기 (μ“°κΈ°λŠ” Gradio μ„œλ²„μ˜ service_role 만)
drop policy if exists read_sessions on study_sessions;
create policy read_sessions on study_sessions for select to authenticated
  using (student_id = auth.uid() or is_teacher_of(student_id) or my_role() = 'admin');

drop policy if exists read_session_questions on session_questions;
create policy read_session_questions on session_questions for select to authenticated
  using (exists (
    select 1 from study_sessions s
    where s.id = session_questions.session_id
      and (s.student_id = auth.uid() or is_teacher_of(s.student_id) or my_role() = 'admin')
  ));

drop policy if exists read_attempts on attempts;
create policy read_attempts on attempts for select to authenticated
  using (student_id = auth.uid() or is_teacher_of(student_id) or my_role() = 'admin');

-- 였λ₯˜ μ‹ κ³ : 둜그인 μ‚¬μš©μžκ°€ μž‘μ„±, 본인/κ΄€λ¦¬μžκ°€ 쑰회
drop policy if exists insert_reports on question_reports;
create policy insert_reports on question_reports for insert to authenticated
  with check (reporter_id = auth.uid());
drop policy if exists read_reports on question_reports;
create policy read_reports on question_reports for select to authenticated
  using (reporter_id = auth.uid() or my_role() = 'admin');

-- 상담 기둝: λ‹΄μž„κ΅μ‚¬(자기 학생) / κ΄€λ¦¬μž. ν•™μƒμ—κ²ŒλŠ” λΉ„κ³΅κ°œ
drop policy if exists read_counseling on counseling_notes;
create policy read_counseling on counseling_notes for select to authenticated
  using ((my_role() = 'teacher' and is_teacher_of(student_id)) or my_role() = 'admin');
drop policy if exists insert_counseling on counseling_notes;
create policy insert_counseling on counseling_notes for insert to authenticated
  with check (teacher_id = auth.uid() and my_role() = 'teacher' and is_teacher_of(student_id));