-- ===================================================================== -- 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));