RezinaLMS-BackEnd/db/migrations/000001_Rezina.up.sql

4996 lines
197 KiB
PL/PgSQL
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- Consolidated baseline for a fresh or rebuilt Rezina database.
-- Original migrations are retained below in filename order.
-- >>> BEGIN SOURCE: 000001_Rezina.up.sql
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
first_name VARCHAR(255),
last_name VARCHAR(255),
gender VARCHAR(255),
birth_day DATE,
email VARCHAR(255),
phone_number VARCHAR(20),
role VARCHAR(50) NOT NULL, -- SUPER_ADMIN, INSTRUCTOR, STUDENT, SUPPORT
password BYTEA NOT NULL,
age INT,
education_level VARCHAR(100),
country VARCHAR(100),
region VARCHAR(100),
knowledge_level VARCHAR(50), -- BEGINNER, INTERMEDIATE, ADVANCED
nick_name VARCHAR(100),
occupation VARCHAR(150),
learning_goal TEXT,
language_goal TEXT,
language_challange TEXT,
favourite_topic TEXT,
initial_assessment_completed BOOLEAN NOT NULL DEFAULT FALSE,
email_verified BOOLEAN NOT NULL DEFAULT FALSE,
phone_verified BOOLEAN NOT NULL DEFAULT FALSE,
status VARCHAR(50) NOT NULL, -- PENDING, ACTIVE, SUSPENDED, DEACTIVATED
last_login TIMESTAMPTZ,
profile_completed BOOLEAN,
profile_picture_url TEXT,
preferred_language VARCHAR(50),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ,
-- Enforce: at least one contact method must be provided
CONSTRAINT users_email_or_phone_required
CHECK (email IS NOT NULL OR phone_number IS NOT NULL)
);
-- Remove the old column
ALTER TABLE users
DROP COLUMN age;
-- Add age_group with constrained values
ALTER TABLE users
ADD COLUMN age_group VARCHAR(20);
ALTER TABLE users
ADD CONSTRAINT users_age_group_check
CHECK (
age_group IN (
'UNDER_13',
'13_17',
'18_24',
'25_34',
'35_44',
'45_54',
'55_PLUS'
)
);
ALTER TABLE users
ADD COLUMN google_id VARCHAR(255) UNIQUE,
ADD COLUMN google_email_verified BOOLEAN DEFAULT FALSE;
ALTER TABLE users
ALTER COLUMN password DROP NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_google_id
ON users (google_id)
WHERE google_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS assessment_questions (
id BIGSERIAL PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
question_type VARCHAR(50) NOT NULL,
-- MULTIPLE_CHOICE, TRUE_FALSE, SHORT_ANSWER
difficulty_level VARCHAR(50),
-- EASY, MEDIUM, HARD
points INT NOT NULL DEFAULT 1,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS assessment_question_options (
id BIGSERIAL PRIMARY KEY,
question_id BIGINT NOT NULL REFERENCES assessment_questions(id) ON DELETE CASCADE,
option_text TEXT NOT NULL,
option_order INT NOT NULL,
is_correct BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (question_id, option_order)
);
CREATE TABLE IF NOT EXISTS assessment_short_answers (
id BIGSERIAL PRIMARY KEY,
question_id BIGINT NOT NULL REFERENCES assessment_questions(id) ON DELETE CASCADE,
correct_answer TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE assessment_questions
ADD CONSTRAINT chk_question_type
CHECK (question_type IN ('MULTIPLE_CHOICE', 'TRUE_FALSE', 'SHORT_ANSWER'));
CREATE TABLE IF NOT EXISTS assessment_attempts (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
total_questions INT NOT NULL,
total_points INT NOT NULL,
score INT,
percentage NUMERIC(5,2),
status VARCHAR(50) NOT NULL,
-- IN_PROGRESS, SUBMITTED, EVALUATED
started_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
submitted_at TIMESTAMPTZ,
evaluated_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS assessment_attempt_questions (
id BIGSERIAL PRIMARY KEY,
attempt_id BIGINT NOT NULL REFERENCES assessment_attempts(id) ON DELETE CASCADE,
question_id BIGINT NOT NULL REFERENCES assessment_questions(id),
question_type VARCHAR(50) NOT NULL,
points INT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (attempt_id, question_id)
);
CREATE TABLE IF NOT EXISTS assessment_attempt_answers (
id BIGSERIAL PRIMARY KEY,
attempt_id BIGINT NOT NULL REFERENCES assessment_attempts(id) ON DELETE CASCADE,
question_id BIGINT NOT NULL REFERENCES assessment_questions(id) ON DELETE CASCADE,
-- For MCQ / TRUE_FALSE
selected_option_id BIGINT
REFERENCES assessment_question_options(id),
-- For SHORT_ANSWER
submitted_text TEXT,
is_correct BOOLEAN,
awarded_points INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (attempt_id, question_id),
CHECK (
(selected_option_id IS NOT NULL AND submitted_text IS NULL)
OR
(selected_option_id IS NULL AND submitted_text IS NOT NULL)
)
);
ALTER TABLE assessment_attempts
ADD CONSTRAINT chk_attempt_status
CHECK (status IN ('IN_PROGRESS', 'SUBMITTED', 'EVALUATED'));
ALTER TABLE assessment_attempt_questions
ADD CONSTRAINT chk_attempt_question_type
CHECK (question_type IN ('MULTIPLE_CHOICE', 'TRUE_FALSE', 'SHORT_ANSWER'));
CREATE TABLE refresh_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
revoked BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE otps (
id BIGSERIAL PRIMARY KEY,
user_id BIGSERIAL NOT NULL,
sent_to VARCHAR(255) NOT NULL,
medium VARCHAR(50) NOT NULL, -- email, sms
otp_for VARCHAR(50) NOT NULL, -- register, reset
otp VARCHAR(10) NOT NULL,
used BOOLEAN NOT NULL DEFAULT FALSE,
used_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE devices (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
device_token TEXT NOT NULL,
platform VARCHAR(20), -- web, android, ios
is_active BOOLEAN DEFAULT TRUE,
last_seen TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS notifications (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type TEXT NOT NULL CHECK (
type IN (
'course_enrolled',
'lesson_completed',
'assessment_assigned',
'assessment_submitted',
'assessment_graded',
'course_completed',
'certificate_issued',
'announcement',
'otp_sent',
'signup_welcome',
'system_alert'
)
),
level TEXT NOT NULL CHECK (
level IN ('info', 'warning', 'success', 'error')
),
channel TEXT CHECK (
channel IN ('email', 'sms', 'push', 'in_app')
),
title TEXT NOT NULL,
message TEXT NOT NULL,
payload JSONB,
is_read BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
read_at TIMESTAMPTZ
);
CREATE TABLE global_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS reported_issues (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
user_role VARCHAR(255) NOT NULL,
subject TEXT NOT NULL,
description TEXT NOT NULL,
issue_type TEXT NOT NULL,
-- e.g., "deposit", "withdrawal", "bet", "technical"
status TEXT NOT NULL DEFAULT 'pending',
-- pending, in_progress, resolved, rejected
metadata JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- <<< END SOURCE: 000001_Rezina.up.sql
-- >>> BEGIN SOURCE: 000002_courses.up.sql
CREATE TABLE IF NOT EXISTS course_categories (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(150) NOT NULL, -- "Learning English", "Other Courses"
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS courses (
id BIGSERIAL PRIMARY KEY,
category_id BIGINT NOT NULL REFERENCES course_categories(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
is_active BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE TABLE IF NOT EXISTS programs (
id BIGSERIAL PRIMARY KEY,
course_id BIGINT NOT NULL REFERENCES courses(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
thumbnail TEXT,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE TABLE IF NOT EXISTS levels (
id BIGSERIAL PRIMARY KEY,
program_id BIGINT NOT NULL REFERENCES programs(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
level_index INT NOT NULL, -- 1,2,3...
number_of_modules INT NOT NULL DEFAULT 0,
number_of_practices INT NOT NULL DEFAULT 0,
number_of_videos INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE TABLE IF NOT EXISTS modules (
id BIGSERIAL PRIMARY KEY,
level_id BIGINT NOT NULL REFERENCES levels(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
content TEXT,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE TABLE IF NOT EXISTS module_videos (
id BIGSERIAL PRIMARY KEY,
module_id BIGINT NOT NULL REFERENCES modules(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
video_url TEXT NOT NULL,
duration INT NOT NULL, -- seconds
resolution VARCHAR(20), -- "720p", "1080p"
is_published BOOLEAN NOT NULL DEFAULT FALSE,
publish_date TIMESTAMPTZ,
visibility VARCHAR(50), -- public, private, unlisted
instructor_id VARCHAR(100),
thumbnail TEXT,
is_active BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE TABLE IF NOT EXISTS practices (
id BIGSERIAL PRIMARY KEY,
owner_type VARCHAR(50) NOT NULL, -- LEVEL | MODULE
owner_id BIGINT NOT NULL,
title VARCHAR(255) NOT NULL,
description TEXT,
banner_image TEXT,
persona VARCHAR(100),
is_active BOOLEAN NOT NULL DEFAULT TRUE,
CHECK (owner_type IN ('LEVEL', 'MODULE'))
);
CREATE TABLE IF NOT EXISTS practice_questions (
id BIGSERIAL PRIMARY KEY,
practice_id BIGINT NOT NULL REFERENCES practices(id) ON DELETE CASCADE,
question TEXT NOT NULL,
question_voice_prompt TEXT,
sample_answer_voice_prompt TEXT,
sample_answer TEXT,
tips TEXT,
type VARCHAR(50) NOT NULL -- MCQ, TRUE_FALSE, SHORT
);
CREATE INDEX IF NOT EXISTS idx_courses_category_id ON courses(category_id);
CREATE INDEX IF NOT EXISTS idx_programs_course_id ON programs(course_id);
CREATE INDEX IF NOT EXISTS idx_levels_program_id ON levels(program_id);
CREATE INDEX IF NOT EXISTS idx_modules_level_id ON modules(level_id);
CREATE INDEX IF NOT EXISTS idx_videos_module_id ON module_videos(module_id);
CREATE INDEX IF NOT EXISTS idx_practices_owner ON practices(owner_type, owner_id);
CREATE INDEX IF NOT EXISTS idx_practice_questions_practice_id ON practice_questions(practice_id);
-- <<< END SOURCE: 000002_courses.up.sql
-- >>> BEGIN SOURCE: 000003_simplify_courses.up.sql
-- Migration: Simplify course hierarchy
-- OLD: Course Category → Course → Program → Level → Module → (Video, Practice)
-- NEW: Course Category → Course → Sub-course (with level) → (Video, Practice)
-- Step 1: Create new tables
CREATE TABLE IF NOT EXISTS sub_courses (
id BIGSERIAL PRIMARY KEY,
course_id BIGINT NOT NULL REFERENCES courses(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
thumbnail TEXT,
display_order INT NOT NULL DEFAULT 0,
level VARCHAR(50) NOT NULL, -- BEGINNER, INTERMEDIATE, ADVANCED
is_active BOOLEAN NOT NULL DEFAULT TRUE,
CHECK (level IN ('BEGINNER', 'INTERMEDIATE', 'ADVANCED'))
);
CREATE INDEX IF NOT EXISTS idx_sub_courses_course_id ON sub_courses(course_id);
CREATE TABLE IF NOT EXISTS sub_course_videos (
id BIGSERIAL PRIMARY KEY,
sub_course_id BIGINT NOT NULL REFERENCES sub_courses(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
video_url TEXT NOT NULL,
duration INT NOT NULL, -- seconds
resolution VARCHAR(20), -- "720p", "1080p"
is_published BOOLEAN NOT NULL DEFAULT FALSE,
publish_date TIMESTAMPTZ,
visibility VARCHAR(50), -- public, private, unlisted
instructor_id VARCHAR(100),
thumbnail TEXT,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE INDEX IF NOT EXISTS idx_sub_course_videos_sub_course_id ON sub_course_videos(sub_course_id);
-- Step 2: Add sub_course_id to practices (nullable during migration)
ALTER TABLE practices ADD COLUMN IF NOT EXISTS sub_course_id BIGINT NULL;
CREATE INDEX IF NOT EXISTS idx_practices_sub_course_id ON practices(sub_course_id);
-- Step 3: Migrate data from old structure to new structure
-- Insert sub-courses from (program, level) combinations
INSERT INTO sub_courses (course_id, title, description, thumbnail, display_order, level, is_active)
SELECT
p.course_id,
(p.title || ' - ' || l.title) as title,
COALESCE(l.description, p.description) as description,
p.thumbnail,
(p.display_order * 100 + l.level_index) as display_order,
CASE l.level_index
WHEN 1 THEN 'BEGINNER'
WHEN 2 THEN 'INTERMEDIATE'
WHEN 3 THEN 'ADVANCED'
ELSE 'BEGINNER'
END as level,
(l.is_active AND p.is_active) as is_active
FROM levels l
JOIN programs p ON p.id = l.program_id;
-- Create temporary mapping table for migration
CREATE TEMP TABLE level_to_sub_course AS
SELECT
l.id as level_id,
sc.id as sub_course_id
FROM levels l
JOIN programs p ON p.id = l.program_id
JOIN sub_courses sc
ON sc.course_id = p.course_id
AND sc.title = (p.title || ' - ' || l.title);
-- Create temporary mapping for modules to sub-courses
CREATE TEMP TABLE module_to_sub_course AS
SELECT
m.id as module_id,
lsc.sub_course_id
FROM modules m
JOIN level_to_sub_course lsc ON lsc.level_id = m.level_id;
-- Migrate videos from module_videos to sub_course_videos
INSERT INTO sub_course_videos (
sub_course_id, title, description, video_url, duration, resolution,
is_published, publish_date, visibility, instructor_id, thumbnail, display_order, is_active
)
SELECT
msc.sub_course_id,
mv.title,
mv.description,
mv.video_url,
mv.duration,
mv.resolution,
mv.is_published,
mv.publish_date,
mv.visibility,
mv.instructor_id,
mv.thumbnail,
(m.display_order * 100 + mv.id) as display_order,
mv.is_active
FROM module_videos mv
JOIN modules m ON m.id = mv.module_id
JOIN module_to_sub_course msc ON msc.module_id = m.id;
-- Migrate practices owned by LEVEL
UPDATE practices pr
SET sub_course_id = lsc.sub_course_id
FROM level_to_sub_course lsc
WHERE pr.owner_type = 'LEVEL'
AND pr.owner_id = lsc.level_id;
-- Migrate practices owned by MODULE
UPDATE practices pr
SET sub_course_id = msc.sub_course_id
FROM module_to_sub_course msc
WHERE pr.owner_type = 'MODULE'
AND pr.owner_id = msc.module_id;
-- Step 4: Enforce integrity on practices
ALTER TABLE practices
ADD CONSTRAINT practices_sub_course_id_fkey
FOREIGN KEY (sub_course_id) REFERENCES sub_courses(id) ON DELETE CASCADE;
-- Make sub_course_id NOT NULL (only if there's data to migrate)
-- If practices table has rows without sub_course_id after migration, this will fail
-- ALTER TABLE practices ALTER COLUMN sub_course_id SET NOT NULL;
-- Step 5: Drop old columns from practices
ALTER TABLE practices DROP CONSTRAINT IF EXISTS practices_owner_type_check;
ALTER TABLE practices DROP COLUMN IF EXISTS owner_type;
ALTER TABLE practices DROP COLUMN IF EXISTS owner_id;
-- Step 6: Drop old indexes
DROP INDEX IF EXISTS idx_videos_module_id;
DROP INDEX IF EXISTS idx_modules_level_id;
DROP INDEX IF EXISTS idx_levels_program_id;
DROP INDEX IF EXISTS idx_programs_course_id;
DROP INDEX IF EXISTS idx_practices_owner;
-- Step 7: Drop old tables (CASCADE to remove FK references)
DROP TABLE IF EXISTS module_videos CASCADE;
DROP TABLE IF EXISTS modules CASCADE;
DROP TABLE IF EXISTS levels CASCADE;
DROP TABLE IF EXISTS programs CASCADE;
-- <<< END SOURCE: 000003_simplify_courses.up.sql
-- >>> BEGIN SOURCE: 000004_add_course_thumbnail.up.sql
-- Add thumbnail column to courses table
ALTER TABLE courses ADD COLUMN IF NOT EXISTS thumbnail TEXT;
-- <<< END SOURCE: 000004_add_course_thumbnail.up.sql
-- >>> BEGIN SOURCE: 000005_add_status_field.up.sql
-- Add status field to sub_course_videos and practices
-- Status values: DRAFT, PUBLISHED, INACTIVE, ARCHIVED
-- ARCHIVED is used for soft deletes
-- Add status column to sub_course_videos
ALTER TABLE sub_course_videos
ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT 'DRAFT'
CHECK (status IN ('DRAFT', 'PUBLISHED', 'INACTIVE', 'ARCHIVED'));
-- Migrate existing data based on is_active and is_published
UPDATE sub_course_videos
SET status = CASE
WHEN is_published = true AND is_active = true THEN 'PUBLISHED'
WHEN is_active = false THEN 'INACTIVE'
ELSE 'DRAFT'
END;
-- Drop is_active column from sub_course_videos (keep is_published for publish_date tracking)
ALTER TABLE sub_course_videos DROP COLUMN IF EXISTS is_active;
-- Add status column to practices
ALTER TABLE practices
ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT 'DRAFT'
CHECK (status IN ('DRAFT', 'PUBLISHED', 'INACTIVE', 'ARCHIVED'));
-- Migrate existing data based on is_active
UPDATE practices
SET status = CASE
WHEN is_active = true THEN 'PUBLISHED'
ELSE 'INACTIVE'
END;
-- Drop is_active column from practices
ALTER TABLE practices DROP COLUMN IF EXISTS is_active;
-- Create indexes for status queries
CREATE INDEX IF NOT EXISTS idx_sub_course_videos_status ON sub_course_videos(status);
CREATE INDEX IF NOT EXISTS idx_practices_status ON practices(status);
-- <<< END SOURCE: 000005_add_status_field.up.sql
-- >>> BEGIN SOURCE: 000006_unified_questions.up.sql
-- Unified Question System Migration
-- Replaces: practice_questions, assessment_questions, assessment_question_options, assessment_short_answers
-- 1. Create unified questions table
CREATE TABLE IF NOT EXISTS questions (
id BIGSERIAL PRIMARY KEY,
question_text TEXT NOT NULL,
question_type VARCHAR(20) NOT NULL CHECK (question_type IN ('MCQ', 'TRUE_FALSE', 'SHORT_ANSWER')),
difficulty_level VARCHAR(20) CHECK (difficulty_level IN ('EASY', 'MEDIUM', 'HARD')),
points INT NOT NULL DEFAULT 1,
explanation TEXT,
tips TEXT,
voice_prompt TEXT,
sample_answer_voice_prompt TEXT,
status VARCHAR(20) NOT NULL DEFAULT 'DRAFT' CHECK (status IN ('DRAFT', 'PUBLISHED', 'INACTIVE', 'ARCHIVED')),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_questions_type ON questions(question_type);
CREATE INDEX idx_questions_status ON questions(status);
CREATE INDEX idx_questions_difficulty ON questions(difficulty_level);
-- 2. Create question options table (for MCQ and TRUE_FALSE)
CREATE TABLE IF NOT EXISTS question_options (
id BIGSERIAL PRIMARY KEY,
question_id BIGINT NOT NULL REFERENCES questions(id) ON DELETE CASCADE,
option_text TEXT NOT NULL,
option_order INT NOT NULL DEFAULT 0,
is_correct BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_question_options_question_id ON question_options(question_id);
-- 3. Create question short answers table (for SHORT_ANSWER type)
CREATE TABLE IF NOT EXISTS question_short_answers (
id BIGSERIAL PRIMARY KEY,
question_id BIGINT NOT NULL REFERENCES questions(id) ON DELETE CASCADE,
acceptable_answer TEXT NOT NULL,
match_type VARCHAR(20) NOT NULL DEFAULT 'EXACT' CHECK (match_type IN ('EXACT', 'CONTAINS', 'CASE_INSENSITIVE')),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_question_short_answers_question_id ON question_short_answers(question_id);
-- 4. Create question sets table (replaces practices for grouping questions)
CREATE TABLE IF NOT EXISTS question_sets (
id BIGSERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description TEXT,
set_type VARCHAR(30) NOT NULL CHECK (set_type IN ('PRACTICE', 'INITIAL_ASSESSMENT', 'QUIZ', 'EXAM', 'SURVEY')),
owner_type VARCHAR(30), -- SUB_COURSE, COURSE, CATEGORY, STANDALONE
owner_id BIGINT, -- References the owning entity
banner_image TEXT,
persona VARCHAR(100),
time_limit_minutes INT, -- Optional time limit
passing_score INT, -- Optional passing percentage
shuffle_questions BOOLEAN NOT NULL DEFAULT FALSE,
status VARCHAR(20) NOT NULL DEFAULT 'DRAFT' CHECK (status IN ('DRAFT', 'PUBLISHED', 'INACTIVE', 'ARCHIVED')),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_question_sets_type ON question_sets(set_type);
CREATE INDEX idx_question_sets_owner ON question_sets(owner_type, owner_id);
CREATE INDEX idx_question_sets_status ON question_sets(status);
-- 5. Create question set items table (links questions to sets)
CREATE TABLE IF NOT EXISTS question_set_items (
id BIGSERIAL PRIMARY KEY,
set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
question_id BIGINT NOT NULL REFERENCES questions(id) ON DELETE CASCADE,
display_order INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(set_id, question_id)
);
CREATE INDEX idx_question_set_items_set_id ON question_set_items(set_id);
CREATE INDEX idx_question_set_items_question_id ON question_set_items(question_id);
-- 6. Migrate data from assessment_questions to new questions table
INSERT INTO questions (id, question_text, question_type, difficulty_level, points, status, created_at)
SELECT
id,
title,
CASE question_type
WHEN 'MULTIPLE_CHOICE' THEN 'MCQ'
WHEN 'SHORT_ANSWER' THEN 'SHORT_ANSWER'
WHEN 'TRUE_FALSE' THEN 'TRUE_FALSE'
ELSE 'MCQ'
END,
CASE difficulty_level
WHEN 'EASY' THEN 'EASY'
WHEN 'MEDIUM' THEN 'MEDIUM'
WHEN 'HARD' THEN 'HARD'
ELSE 'MEDIUM'
END,
points,
CASE WHEN is_active THEN 'PUBLISHED' ELSE 'INACTIVE' END,
created_at
FROM assessment_questions;
-- 7. Migrate assessment_question_options to question_options
INSERT INTO question_options (question_id, option_text, option_order, is_correct, created_at)
SELECT question_id, option_text, option_order, is_correct, created_at
FROM assessment_question_options;
-- 8. Migrate assessment_short_answers to question_short_answers
INSERT INTO question_short_answers (question_id, acceptable_answer, match_type, created_at)
SELECT question_id, correct_answer, 'EXACT', created_at
FROM assessment_short_answers;
-- 9. Create initial assessment question set from existing data
INSERT INTO question_sets (title, description, set_type, owner_type, status, created_at)
VALUES ('Initial Assessment', 'Default initial assessment for new users', 'INITIAL_ASSESSMENT', 'STANDALONE', 'PUBLISHED', CURRENT_TIMESTAMP);
-- Link existing assessment questions to the initial assessment set
INSERT INTO question_set_items (set_id, question_id, display_order)
SELECT
(SELECT id FROM question_sets WHERE set_type = 'INITIAL_ASSESSMENT' LIMIT 1),
id,
id -- Use ID as initial display order
FROM questions
WHERE id IN (SELECT id FROM assessment_questions);
-- 10. Migrate practice_questions to new structure
-- First, get max ID from questions to avoid conflicts
DO $$
DECLARE
max_q_id BIGINT;
practice_rec RECORD;
new_set_id BIGINT;
new_question_id BIGINT;
BEGIN
SELECT COALESCE(MAX(id), 0) INTO max_q_id FROM questions;
-- For each practice in the old system, create a question_set
FOR practice_rec IN
SELECT DISTINCT p.id, p.sub_course_id, p.title, p.description, p.banner_image, p.persona, p.status
FROM practices p
LOOP
-- Create question set for this practice
INSERT INTO question_sets (title, description, set_type, owner_type, owner_id, banner_image, persona, status, created_at)
VALUES (
practice_rec.title,
practice_rec.description,
'PRACTICE',
'SUB_COURSE',
practice_rec.sub_course_id,
practice_rec.banner_image,
practice_rec.persona,
practice_rec.status,
CURRENT_TIMESTAMP
)
RETURNING id INTO new_set_id;
-- Migrate questions from this practice
FOR new_question_id IN
INSERT INTO questions (question_text, question_type, tips, sample_answer_voice_prompt, voice_prompt, status, created_at)
SELECT
pq.question,
pq.type,
pq.tips,
pq.sample_answer_voice_prompt,
pq.question_voice_prompt,
'PUBLISHED',
CURRENT_TIMESTAMP
FROM practice_questions pq
WHERE pq.practice_id = practice_rec.id
RETURNING id
LOOP
-- Link question to set
INSERT INTO question_set_items (set_id, question_id, display_order)
VALUES (new_set_id, new_question_id, new_question_id);
END LOOP;
END LOOP;
END $$;
-- 11. Reset sequences
SELECT setval(pg_get_serial_sequence('questions', 'id'), COALESCE((SELECT MAX(id) FROM questions), 1), true);
SELECT setval(pg_get_serial_sequence('question_options', 'id'), COALESCE((SELECT MAX(id) FROM question_options), 1), true);
SELECT setval(pg_get_serial_sequence('question_short_answers', 'id'), COALESCE((SELECT MAX(id) FROM question_short_answers), 1), true);
SELECT setval(pg_get_serial_sequence('question_sets', 'id'), COALESCE((SELECT MAX(id) FROM question_sets), 1), true);
SELECT setval(pg_get_serial_sequence('question_set_items', 'id'), COALESCE((SELECT MAX(id) FROM question_set_items), 1), true);
-- 12. Drop old tables
DROP TABLE IF EXISTS practice_questions CASCADE;
DROP TABLE IF EXISTS practices CASCADE;
DROP TABLE IF EXISTS assessment_attempt_answers CASCADE;
DROP TABLE IF EXISTS assessment_attempt_questions CASCADE;
DROP TABLE IF EXISTS assessment_attempts CASCADE;
DROP TABLE IF EXISTS assessment_short_answers CASCADE;
DROP TABLE IF EXISTS assessment_question_options CASCADE;
DROP TABLE IF EXISTS assessment_questions CASCADE;
-- <<< END SOURCE: 000006_unified_questions.up.sql
-- >>> BEGIN SOURCE: 000007_personas_and_practice_enhancements.up.sql
-- Junction table to link users (as personas) to a question_set (practice)
CREATE TABLE question_set_personas (
id BIGSERIAL PRIMARY KEY,
question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
display_order INT DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
UNIQUE(question_set_id, user_id)
);
-- Add video context to question_sets for practice-video linking
ALTER TABLE question_sets
ADD COLUMN sub_course_video_id BIGINT REFERENCES sub_course_videos(id) ON DELETE SET NULL;
-- Indexes
CREATE INDEX idx_question_set_personas_question_set_id ON question_set_personas(question_set_id);
CREATE INDEX idx_question_set_personas_user_id ON question_set_personas(user_id);
CREATE INDEX idx_question_sets_sub_course_video_id ON question_sets(sub_course_video_id);
-- <<< END SOURCE: 000007_personas_and_practice_enhancements.up.sql
-- >>> BEGIN SOURCE: 000008_subscriptions.up.sql
-- Subscription Plans table
CREATE TABLE subscription_plans (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description TEXT,
duration_value INT NOT NULL,
duration_unit VARCHAR(10) NOT NULL CHECK (duration_unit IN ('DAY', 'WEEK', 'MONTH', 'YEAR')),
price DECIMAL(10, 2) NOT NULL,
currency VARCHAR(3) NOT NULL DEFAULT 'ETB',
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_subscription_plans_active ON subscription_plans(is_active);
-- User Subscriptions table
CREATE TABLE user_subscriptions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
plan_id BIGINT NOT NULL REFERENCES subscription_plans(id) ON DELETE RESTRICT,
starts_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMPTZ NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('PENDING', 'ACTIVE', 'EXPIRED', 'CANCELLED')),
payment_reference VARCHAR(255),
payment_method VARCHAR(50),
auto_renew BOOLEAN NOT NULL DEFAULT FALSE,
cancelled_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_user_subscriptions_user_id ON user_subscriptions(user_id);
CREATE INDEX idx_user_subscriptions_status ON user_subscriptions(status);
CREATE INDEX idx_user_subscriptions_expires_at ON user_subscriptions(expires_at);
CREATE INDEX idx_user_subscriptions_user_status ON user_subscriptions(user_id, status);
-- <<< END SOURCE: 000008_subscriptions.up.sql
-- >>> BEGIN SOURCE: 000009_payments.up.sql
-- Payments table for tracking all payment transactions
CREATE TABLE payments (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
plan_id BIGINT REFERENCES subscription_plans(id) ON DELETE SET NULL,
subscription_id BIGINT REFERENCES user_subscriptions(id) ON DELETE SET NULL,
-- ArifPay specific fields
session_id VARCHAR(100),
transaction_id VARCHAR(100),
nonce VARCHAR(255) NOT NULL UNIQUE,
-- Payment details
amount DECIMAL(10, 2) NOT NULL,
currency VARCHAR(3) NOT NULL DEFAULT 'ETB',
payment_method VARCHAR(50),
-- Status tracking
status VARCHAR(20) NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING', 'PROCESSING', 'SUCCESS', 'FAILED', 'CANCELLED', 'EXPIRED')),
-- URLs for redirect
payment_url TEXT,
-- Timestamps
paid_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_payments_user_id ON payments(user_id);
CREATE INDEX idx_payments_session_id ON payments(session_id);
CREATE INDEX idx_payments_nonce ON payments(nonce);
CREATE INDEX idx_payments_status ON payments(status);
CREATE INDEX idx_payments_subscription_id ON payments(subscription_id);
-- <<< END SOURCE: 000009_payments.up.sql
-- >>> BEGIN SOURCE: 000010_vimeo_video_hosting.up.sql
-- Add Vimeo video hosting fields to sub_course_videos table
ALTER TABLE sub_course_videos
ADD COLUMN IF NOT EXISTS vimeo_id TEXT,
ADD COLUMN IF NOT EXISTS vimeo_embed_url TEXT,
ADD COLUMN IF NOT EXISTS vimeo_player_html TEXT,
ADD COLUMN IF NOT EXISTS vimeo_status TEXT DEFAULT 'pending',
ADD COLUMN IF NOT EXISTS video_host_provider TEXT DEFAULT 'DIRECT';
-- Create index on vimeo_id for faster lookups
CREATE INDEX IF NOT EXISTS idx_sub_course_videos_vimeo_id ON sub_course_videos(vimeo_id) WHERE vimeo_id IS NOT NULL;
-- Add comment for documentation
COMMENT ON COLUMN sub_course_videos.vimeo_id IS 'Vimeo video ID for videos hosted on Vimeo';
COMMENT ON COLUMN sub_course_videos.vimeo_embed_url IS 'Vimeo player embed URL';
COMMENT ON COLUMN sub_course_videos.vimeo_player_html IS 'Vimeo iframe embed HTML code';
COMMENT ON COLUMN sub_course_videos.vimeo_status IS 'Vimeo video status: pending, uploading, transcoding, available, error';
COMMENT ON COLUMN sub_course_videos.video_host_provider IS 'Video hosting provider: DIRECT or VIMEO';
-- <<< END SOURCE: 000010_vimeo_video_hosting.up.sql
-- >>> BEGIN SOURCE: 000011_team_management.up.sql
-- Team members table for managing internal LMS company staff
CREATE TABLE IF NOT EXISTS team_members (
id BIGSERIAL PRIMARY KEY,
-- Basic info
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
phone_number VARCHAR(20),
-- Authentication
password BYTEA NOT NULL,
-- Role within the team (different from learner roles)
team_role VARCHAR(50) NOT NULL CHECK (
team_role IN (
'SUPER_ADMIN', -- Full system access
'ADMIN', -- Administrative tasks
'CONTENT_MANAGER', -- Manages courses, content
'SUPPORT_AGENT', -- Customer support
'INSTRUCTOR', -- Creates/manages courses
'FINANCE', -- Payment/subscription management
'HR', -- Team member management
'ANALYST' -- Reports and analytics
)
),
-- Department
department VARCHAR(100),
-- Job title
job_title VARCHAR(150),
-- Employment details
employment_type VARCHAR(50) CHECK (
employment_type IN ('full_time', 'part_time', 'contract', 'intern')
),
hire_date DATE,
-- Profile
profile_picture_url TEXT,
bio TEXT,
-- Contact
work_phone VARCHAR(20),
emergency_contact VARCHAR(255),
-- Status
status VARCHAR(50) NOT NULL DEFAULT 'active' CHECK (
status IN ('active', 'inactive', 'suspended', 'terminated')
),
-- Verification
email_verified BOOLEAN NOT NULL DEFAULT FALSE,
-- Permissions (JSON array of permission strings)
permissions JSONB DEFAULT '[]'::jsonb,
-- Tracking
last_login TIMESTAMPTZ,
created_by BIGINT REFERENCES team_members(id),
updated_by BIGINT REFERENCES team_members(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
-- Indexes
CREATE INDEX IF NOT EXISTS idx_team_members_email ON team_members(email);
CREATE INDEX IF NOT EXISTS idx_team_members_team_role ON team_members(team_role);
CREATE INDEX IF NOT EXISTS idx_team_members_department ON team_members(department);
CREATE INDEX IF NOT EXISTS idx_team_members_status ON team_members(status);
-- <<< END SOURCE: 000011_team_management.up.sql
-- >>> BEGIN SOURCE: 000012_profile_completion.up.sql
-- Add profile_completion_percentage column
ALTER TABLE users ADD COLUMN profile_completion_percentage SMALLINT NOT NULL DEFAULT 0;
-- Create function to calculate profile completion
CREATE OR REPLACE FUNCTION calculate_profile_completion()
RETURNS TRIGGER AS $$
DECLARE
filled_count INTEGER := 0;
BEGIN
-- Check first_name
IF NULLIF(TRIM(NEW.first_name), '') IS NOT NULL THEN
filled_count := filled_count + 1;
END IF;
-- Check last_name
IF NULLIF(TRIM(NEW.last_name), '') IS NOT NULL THEN
filled_count := filled_count + 1;
END IF;
-- Check email OR phone_number (counts as 1 if either is filled)
IF NULLIF(TRIM(NEW.email), '') IS NOT NULL OR NULLIF(TRIM(NEW.phone_number), '') IS NOT NULL THEN
filled_count := filled_count + 1;
END IF;
-- Check preferred_language
IF NULLIF(TRIM(NEW.preferred_language), '') IS NOT NULL THEN
filled_count := filled_count + 1;
END IF;
--- Check country
IF NULLIF(TRIM(NEW.country), '') IS NOT NULL THEN
filled_count := filled_count + 1;
END IF;
-- Check age_group
IF NULLIF(TRIM(NEW.age_group), '') IS NOT NULL THEN
filled_count := filled_count + 1;
END IF;
-- Check learning_goal
IF NULLIF(TRIM(NEW.learning_goal), '') IS NOT NULL THEN
filled_count := filled_count + 1;
END IF;
-- Check language_goal
IF NULLIF(TRIM(NEW.language_goal), '') IS NOT NULL THEN
filled_count := filled_count + 1;
END IF;
-- Calculate percentage (8 total required fields)
NEW.profile_completion_percentage := (filled_count * 100 / 8)::SMALLINT;
-- Set profile_completed if 100%
IF NEW.profile_completion_percentage = 100 THEN
NEW.profile_completed := true;
ELSE
NEW.profile_completed := false;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Create trigger
CREATE TRIGGER trg_update_profile_completion
BEFORE INSERT OR UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION calculate_profile_completion();
-- Backfill existing rows
UPDATE users SET updated_at = updated_at;
-- <<< END SOURCE: 000012_profile_completion.up.sql
-- >>> BEGIN SOURCE: 000013_devices_constraints.up.sql
-- Add unique constraint for ON CONFLICT to work in CreateDevice query
ALTER TABLE devices
ADD CONSTRAINT devices_user_id_device_token_uniq UNIQUE (user_id, device_token);
-- Add foreign key to users table for data integrity and cascade deletion
ALTER TABLE devices
ADD CONSTRAINT devices_user_fk
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
-- <<< END SOURCE: 000013_devices_constraints.up.sql
-- >>> BEGIN SOURCE: 000014_activity_logs.up.sql
CREATE TABLE IF NOT EXISTS activity_logs (
id BIGSERIAL PRIMARY KEY,
actor_id BIGINT NULL,
actor_role TEXT NULL,
action TEXT NOT NULL,
resource_type TEXT NOT NULL,
resource_id BIGINT NULL,
message TEXT NULL,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
ip_address TEXT NULL,
user_agent TEXT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_activity_logs_created_at ON activity_logs (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_activity_logs_actor ON activity_logs (actor_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_activity_logs_resource ON activity_logs (resource_type, resource_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_activity_logs_action ON activity_logs (action, created_at DESC);
-- <<< END SOURCE: 000014_activity_logs.up.sql
-- >>> BEGIN SOURCE: 000015_notification_types.up.sql
-- Drop the existing CHECK constraint on notifications.type and replace with an expanded one
ALTER TABLE notifications
DROP CONSTRAINT IF EXISTS notifications_type_check;
ALTER TABLE notifications
ADD CONSTRAINT notifications_type_check CHECK (
type IN (
'course_enrolled',
'lesson_completed',
'assessment_assigned',
'assessment_submitted',
'assessment_graded',
'course_completed',
'certificate_issued',
'announcement',
'otp_sent',
'signup_welcome',
'system_alert',
'knowledge_level_update',
'payment_verified',
'subscription_activated',
'course_created',
'sub_course_created',
'video_added',
'issue_status_updated',
'issue_created',
'admin_created',
'team_member_created',
'user_deleted'
)
);
-- <<< END SOURCE: 000015_notification_types.up.sql
-- >>> BEGIN SOURCE: 000016_notifications_receiver_type.up.sql
-- Drop the foreign key constraint on user_id so notifications can reference
-- either users or team_members depending on receiver_type.
ALTER TABLE notifications
DROP CONSTRAINT IF EXISTS notifications_user_id_fkey;
-- Add a receiver_type column to distinguish between user and team_member recipients.
ALTER TABLE notifications
ADD COLUMN IF NOT EXISTS receiver_type TEXT NOT NULL DEFAULT 'user'
CHECK (receiver_type IN ('user', 'team_member'));
-- <<< END SOURCE: 000016_notifications_receiver_type.up.sql
-- >>> BEGIN SOURCE: 000017_ratings.up.sql
CREATE TABLE IF NOT EXISTS ratings (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
target_type VARCHAR(20) NOT NULL, -- 'app', 'course', 'sub_course'
target_id BIGINT NOT NULL DEFAULT 0, -- 0 for app rating, course_id or sub_course_id otherwise
stars SMALLINT NOT NULL CHECK (stars >= 1 AND stars <= 5),
review TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (user_id, target_type, target_id)
);
CREATE INDEX idx_ratings_target ON ratings (target_type, target_id);
CREATE INDEX idx_ratings_user ON ratings (user_id);
-- <<< END SOURCE: 000017_ratings.up.sql
-- >>> BEGIN SOURCE: 000018_course_intro_video.up.sql
ALTER TABLE courses ADD COLUMN IF NOT EXISTS intro_video_url TEXT;
-- <<< END SOURCE: 000018_course_intro_video.up.sql
-- >>> BEGIN SOURCE: 000019_sub_course_progression.up.sql
-- Sub-course prerequisite links (admin-defined course flow)
CREATE TABLE IF NOT EXISTS sub_course_prerequisites (
id BIGSERIAL PRIMARY KEY,
sub_course_id BIGINT NOT NULL REFERENCES sub_courses(id) ON DELETE CASCADE,
prerequisite_sub_course_id BIGINT NOT NULL REFERENCES sub_courses(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(sub_course_id, prerequisite_sub_course_id),
CHECK(sub_course_id != prerequisite_sub_course_id)
);
CREATE INDEX IF NOT EXISTS idx_sub_course_prerequisites_sub_course_id
ON sub_course_prerequisites(sub_course_id);
CREATE INDEX IF NOT EXISTS idx_sub_course_prerequisites_prerequisite_id
ON sub_course_prerequisites(prerequisite_sub_course_id);
-- User progress per sub-course
CREATE TABLE IF NOT EXISTS user_sub_course_progress (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
sub_course_id BIGINT NOT NULL REFERENCES sub_courses(id) ON DELETE CASCADE,
status VARCHAR(20) NOT NULL DEFAULT 'IN_PROGRESS' CHECK (
status IN ('IN_PROGRESS', 'COMPLETED')
),
progress_percentage SMALLINT NOT NULL DEFAULT 0 CHECK (
progress_percentage BETWEEN 0 AND 100
),
started_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ,
UNIQUE(user_id, sub_course_id)
);
CREATE INDEX IF NOT EXISTS idx_user_sub_course_progress_user_id
ON user_sub_course_progress(user_id);
CREATE INDEX IF NOT EXISTS idx_user_sub_course_progress_sub_course_id
ON user_sub_course_progress(sub_course_id);
CREATE INDEX IF NOT EXISTS idx_user_sub_course_progress_status
ON user_sub_course_progress(user_id, status);
-- <<< END SOURCE: 000019_sub_course_progression.up.sql
-- >>> BEGIN SOURCE: 000020_scheduled_notifications.up.sql
CREATE TABLE IF NOT EXISTS scheduled_notifications (
id BIGSERIAL PRIMARY KEY,
channel TEXT NOT NULL CHECK (channel IN ('email', 'sms', 'push')),
title TEXT,
message TEXT NOT NULL,
html TEXT,
scheduled_at TIMESTAMPTZ NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'processing', 'sent', 'failed', 'cancelled')),
target_user_ids BIGINT[],
target_role TEXT,
target_raw JSONB,
attempt_count INT NOT NULL DEFAULT 0,
last_error TEXT,
processing_started_at TIMESTAMPTZ,
sent_at TIMESTAMPTZ,
cancelled_at TIMESTAMPTZ,
created_by BIGINT NOT NULL REFERENCES users(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT scheduled_notifications_target_required CHECK (
(target_user_ids IS NOT NULL AND array_length(target_user_ids, 1) > 0)
OR target_role IS NOT NULL
OR target_raw IS NOT NULL
)
);
CREATE INDEX IF NOT EXISTS idx_scheduled_notifications_due
ON scheduled_notifications (scheduled_at)
WHERE status = 'pending';
CREATE INDEX IF NOT EXISTS idx_scheduled_notifications_status
ON scheduled_notifications (status, scheduled_at);
-- <<< END SOURCE: 000020_scheduled_notifications.up.sql
-- >>> BEGIN SOURCE: 000021_rbac.up.sql
-- RBAC: Roles, Permissions, Role-Permissions
CREATE TABLE IF NOT EXISTS roles (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
description TEXT NOT NULL DEFAULT '',
is_system BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS permissions (
id BIGSERIAL PRIMARY KEY,
key TEXT NOT NULL UNIQUE,
name TEXT NOT NULL DEFAULT '',
description TEXT NOT NULL DEFAULT '',
group_name TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS role_permissions (
role_id BIGINT NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
permission_id BIGINT NOT NULL REFERENCES permissions(id) ON DELETE CASCADE,
PRIMARY KEY (role_id, permission_id)
);
CREATE INDEX IF NOT EXISTS idx_role_permissions_role_id ON role_permissions(role_id);
CREATE INDEX IF NOT EXISTS idx_role_permissions_permission_id ON role_permissions(permission_id);
-- Seed system roles
INSERT INTO roles (name, description, is_system) VALUES
('SUPER_ADMIN', 'System super administrator with full access', true),
('ADMIN', 'System administrator', true),
('STUDENT', 'Student user', true),
('INSTRUCTOR', 'Instructor user', true),
('SUPPORT', 'Support staff', true)
ON CONFLICT (name) DO NOTHING;
-- <<< END SOURCE: 000021_rbac.up.sql
-- >>> BEGIN SOURCE: 000022_audio_questions.up.sql
-- Add AUDIO question type and image_url support
-- 1. Extend question_type CHECK constraint to include AUDIO
ALTER TABLE questions
DROP CONSTRAINT IF EXISTS questions_question_type_check;
ALTER TABLE questions
ADD CONSTRAINT questions_question_type_check
CHECK (question_type IN ('MCQ', 'TRUE_FALSE', 'SHORT_ANSWER', 'AUDIO'));
-- 2. Add image_url column to questions
ALTER TABLE questions
ADD COLUMN IF NOT EXISTS image_url TEXT;
-- 3. Create question_audio_answers table for storing correct answer text
CREATE TABLE IF NOT EXISTS question_audio_answers (
id BIGSERIAL PRIMARY KEY,
question_id BIGINT NOT NULL REFERENCES questions(id) ON DELETE CASCADE,
correct_answer_text TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_question_audio_answers_question_id
ON question_audio_answers(question_id);
-- <<< END SOURCE: 000022_audio_questions.up.sql
-- >>> BEGIN SOURCE: 000023_reorder_support.up.sql
ALTER TABLE course_categories ADD COLUMN display_order INT NOT NULL DEFAULT 0;
ALTER TABLE courses ADD COLUMN display_order INT NOT NULL DEFAULT 0;
ALTER TABLE question_sets ADD COLUMN display_order INT NOT NULL DEFAULT 0;
-- <<< END SOURCE: 000023_reorder_support.up.sql
-- >>> BEGIN SOURCE: 000024_subcourse_entry_assessment_and_sub_levels.up.sql
-- Add sub-level support to sub_courses and enforce valid level/sub-level combinations.
ALTER TABLE sub_courses
ADD COLUMN sub_level VARCHAR(2);
UPDATE sub_courses
SET sub_level = CASE level
WHEN 'BEGINNER' THEN 'A1'
WHEN 'INTERMEDIATE' THEN 'B1'
WHEN 'ADVANCED' THEN 'C1'
ELSE 'A1'
END
WHERE sub_level IS NULL;
ALTER TABLE sub_courses
ALTER COLUMN sub_level SET NOT NULL;
ALTER TABLE sub_courses
ADD CONSTRAINT sub_courses_level_sub_level_check CHECK (
(level = 'BEGINNER' AND sub_level IN ('A1', 'A2', 'A3')) OR
(level = 'INTERMEDIATE' AND sub_level IN ('B1', 'B2', 'B3')) OR
(level = 'ADVANCED' AND sub_level IN ('C1', 'C2', 'C3'))
);
CREATE INDEX idx_sub_courses_level_sub_level ON sub_courses(level, sub_level);
-- Ensure each sub-course has an entry-assessment question set.
CREATE UNIQUE INDEX idx_question_sets_unique_subcourse_initial_assessment
ON question_sets(owner_type, owner_id, set_type)
WHERE owner_type = 'SUB_COURSE' AND set_type = 'INITIAL_ASSESSMENT' AND status != 'ARCHIVED';
CREATE OR REPLACE FUNCTION clone_default_initial_assessment_items(target_set_id BIGINT)
RETURNS VOID AS $$
DECLARE
template_set_id BIGINT;
BEGIN
SELECT id
INTO template_set_id
FROM question_sets
WHERE set_type = 'INITIAL_ASSESSMENT'
AND owner_type = 'STANDALONE'
AND status = 'PUBLISHED'
ORDER BY created_at DESC
LIMIT 1;
IF template_set_id IS NULL THEN
RETURN;
END IF;
INSERT INTO question_set_items (set_id, question_id, display_order)
SELECT target_set_id, qsi.question_id, qsi.display_order
FROM question_set_items qsi
WHERE qsi.set_id = template_set_id
AND NOT EXISTS (
SELECT 1
FROM question_set_items existing
WHERE existing.set_id = target_set_id
AND existing.question_id = qsi.question_id
);
END;
$$ LANGUAGE plpgsql;
INSERT INTO question_sets (
title,
description,
set_type,
owner_type,
owner_id,
shuffle_questions,
status
)
SELECT
sc.title || ' Entry Assessment',
'Entry assessment used to evaluate learners before joining this sub-course.',
'INITIAL_ASSESSMENT',
'SUB_COURSE',
sc.id,
false,
'DRAFT'
FROM sub_courses sc
WHERE NOT EXISTS (
SELECT 1
FROM question_sets qs
WHERE qs.owner_type = 'SUB_COURSE'
AND qs.owner_id = sc.id
AND qs.set_type = 'INITIAL_ASSESSMENT'
AND qs.status != 'ARCHIVED'
);
DO $$
DECLARE
r RECORD;
BEGIN
FOR r IN
SELECT id
FROM question_sets
WHERE owner_type = 'SUB_COURSE'
AND set_type = 'INITIAL_ASSESSMENT'
AND status != 'ARCHIVED'
LOOP
IF NOT EXISTS (SELECT 1 FROM question_set_items WHERE set_id = r.id) THEN
PERFORM clone_default_initial_assessment_items(r.id);
END IF;
END LOOP;
END;
$$;
CREATE OR REPLACE FUNCTION create_sub_course_entry_assessment()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO question_sets (
title,
description,
set_type,
owner_type,
owner_id,
shuffle_questions,
status
)
VALUES (
NEW.title || ' Entry Assessment',
'Entry assessment used to evaluate learners before joining this sub-course.',
'INITIAL_ASSESSMENT',
'SUB_COURSE',
NEW.id,
false,
'DRAFT'
)
ON CONFLICT DO NOTHING;
PERFORM clone_default_initial_assessment_items((
SELECT id
FROM question_sets
WHERE owner_type = 'SUB_COURSE'
AND owner_id = NEW.id
AND set_type = 'INITIAL_ASSESSMENT'
AND status != 'ARCHIVED'
ORDER BY created_at DESC
LIMIT 1
));
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_sub_courses_create_entry_assessment
AFTER INSERT ON sub_courses
FOR EACH ROW
EXECUTE FUNCTION create_sub_course_entry_assessment();
-- <<< END SOURCE: 000024_subcourse_entry_assessment_and_sub_levels.up.sql
-- >>> BEGIN SOURCE: 000025_video_sequence_progress.up.sql
CREATE TABLE IF NOT EXISTS user_sub_course_video_progress (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
sub_course_id BIGINT NOT NULL REFERENCES sub_courses(id) ON DELETE CASCADE,
video_id BIGINT NOT NULL REFERENCES sub_course_videos(id) ON DELETE CASCADE,
completed_at TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_video_progress_unique
ON user_sub_course_video_progress(user_id, video_id);
CREATE INDEX IF NOT EXISTS idx_user_video_progress_sub_course
ON user_sub_course_video_progress(user_id, sub_course_id);
-- <<< END SOURCE: 000025_video_sequence_progress.up.sql
-- >>> BEGIN SOURCE: 000026_practice_sequence_progress.up.sql
CREATE TABLE IF NOT EXISTS user_practice_progress (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
sub_course_id BIGINT NOT NULL REFERENCES sub_courses(id) ON DELETE CASCADE,
question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
completed_at TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_practice_progress_unique
ON user_practice_progress(user_id, question_set_id);
CREATE INDEX IF NOT EXISTS idx_user_practice_progress_sub_course
ON user_practice_progress(user_id, sub_course_id);
-- <<< END SOURCE: 000026_practice_sequence_progress.up.sql
-- >>> BEGIN SOURCE: 000027_two_phase_account_deletion.up.sql
ALTER TABLE users
ADD COLUMN IF NOT EXISTS deletion_requested_at TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS deletion_scheduled_at TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS deletion_cancelled_at TIMESTAMPTZ;
CREATE INDEX IF NOT EXISTS idx_users_deletion_scheduled_at
ON users (deletion_scheduled_at)
WHERE deletion_scheduled_at IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_users_deletion_due
ON users (deletion_scheduled_at, id)
WHERE deletion_scheduled_at IS NOT NULL;
-- <<< END SOURCE: 000027_two_phase_account_deletion.up.sql
-- >>> BEGIN SOURCE: 000028_user_audio_responses.up.sql
-- Store learner audio answer submissions for AUDIO-type questions
CREATE TABLE IF NOT EXISTS user_audio_responses (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
question_id BIGINT NOT NULL REFERENCES questions(id) ON DELETE CASCADE,
question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
audio_object_key TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_user_audio_responses_user_question
ON user_audio_responses(user_id, question_id, question_set_id);
-- <<< END SOURCE: 000028_user_audio_responses.up.sql
-- >>> BEGIN SOURCE: 000029_question_sets_intro_video_url.up.sql
ALTER TABLE question_sets
ADD COLUMN intro_video_url TEXT;
-- <<< END SOURCE: 000029_question_sets_intro_video_url.up.sql
-- >>> BEGIN SOURCE: 000030_unified_hierarchy.up.sql
-- Unified hierarchy
-- Course Category -> Course Sub-category -> Course -> Level -> Module -> Sub-Module
-- -> Sub-Module Videos
-- -> Sub-Module Practices (question sets)
CREATE TABLE IF NOT EXISTS course_sub_categories (
id BIGSERIAL PRIMARY KEY,
category_id BIGINT NOT NULL REFERENCES course_categories(id) ON DELETE CASCADE,
name VARCHAR(150) NOT NULL,
description TEXT,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
display_order INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(category_id, name)
);
ALTER TABLE courses
ADD COLUMN IF NOT EXISTS sub_category_id BIGINT REFERENCES course_sub_categories(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_courses_sub_category_id ON courses(sub_category_id);
CREATE TABLE IF NOT EXISTS levels (
id BIGSERIAL PRIMARY KEY,
course_id BIGINT NOT NULL REFERENCES courses(id) ON DELETE CASCADE,
cefr_level VARCHAR(2) NOT NULL,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(course_id, cefr_level),
CHECK (cefr_level IN ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'))
);
CREATE INDEX IF NOT EXISTS idx_levels_course_id ON levels(course_id);
CREATE TABLE IF NOT EXISTS modules (
id BIGSERIAL PRIMARY KEY,
level_id BIGINT NOT NULL REFERENCES levels(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_modules_level_id ON modules(level_id);
CREATE TABLE IF NOT EXISTS sub_modules (
id BIGSERIAL PRIMARY KEY,
module_id BIGINT NOT NULL REFERENCES modules(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
legacy_sub_course_id BIGINT UNIQUE
);
CREATE INDEX IF NOT EXISTS idx_sub_modules_module_id ON sub_modules(module_id);
CREATE TABLE IF NOT EXISTS sub_module_videos (
id BIGSERIAL PRIMARY KEY,
sub_module_id BIGINT NOT NULL REFERENCES sub_modules(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
video_url TEXT NOT NULL,
duration INT,
resolution VARCHAR(20),
is_published BOOLEAN NOT NULL DEFAULT FALSE,
publish_date TIMESTAMPTZ,
visibility VARCHAR(50),
instructor_id VARCHAR(100),
thumbnail TEXT,
display_order INT NOT NULL DEFAULT 0,
status VARCHAR(20) NOT NULL DEFAULT 'DRAFT',
vimeo_id TEXT,
vimeo_embed_url TEXT,
vimeo_player_html TEXT,
vimeo_status VARCHAR(50),
video_host_provider VARCHAR(20),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_sub_module_videos_sub_module_id ON sub_module_videos(sub_module_id);
CREATE TABLE IF NOT EXISTS sub_module_practices (
id BIGSERIAL PRIMARY KEY,
sub_module_id BIGINT NOT NULL REFERENCES sub_modules(id) ON DELETE CASCADE,
question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
intro_video_url TEXT,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(question_set_id)
);
CREATE INDEX IF NOT EXISTS idx_sub_module_practices_sub_module_id ON sub_module_practices(sub_module_id);
-- Practice progress now supports sub-module owned practices where no legacy sub_course exists.
ALTER TABLE user_practice_progress
ALTER COLUMN sub_course_id DROP NOT NULL;
-- Backfill from existing structure
INSERT INTO course_sub_categories (category_id, name, description, display_order, is_active)
SELECT cc.id, c.title || ' Group', 'Auto-generated from existing course structure', 0, TRUE
FROM courses c
JOIN course_categories cc ON cc.id = c.category_id
LEFT JOIN course_sub_categories csc
ON csc.category_id = cc.id AND csc.name = c.title || ' Group'
WHERE csc.id IS NULL;
UPDATE courses c
SET sub_category_id = csc.id
FROM course_sub_categories csc
WHERE csc.category_id = c.category_id
AND csc.name = c.title || ' Group'
AND c.sub_category_id IS NULL;
INSERT INTO levels (course_id, cefr_level, display_order, is_active)
SELECT
sc.course_id,
sc.sub_level,
MIN(sc.display_order),
BOOL_AND(sc.is_active)
FROM sub_courses sc
WHERE sc.sub_level IN ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3')
GROUP BY sc.course_id, sc.sub_level
ON CONFLICT (course_id, cefr_level) DO NOTHING;
INSERT INTO modules (level_id, title, description, display_order, is_active)
SELECT
l.id,
l.cefr_level || ' Module 1',
'Auto-generated default module for ' || l.cefr_level,
1,
l.is_active
FROM levels l
LEFT JOIN modules m ON m.level_id = l.id AND m.display_order = 1
WHERE m.id IS NULL;
INSERT INTO sub_modules (module_id, title, description, display_order, is_active, legacy_sub_course_id)
SELECT
m.id,
sc.title,
sc.description,
sc.display_order,
sc.is_active,
sc.id
FROM sub_courses sc
JOIN levels l
ON l.course_id = sc.course_id
AND l.cefr_level = sc.sub_level
JOIN modules m
ON m.level_id = l.id
AND m.display_order = 1
LEFT JOIN sub_modules sm ON sm.legacy_sub_course_id = sc.id
WHERE sm.id IS NULL;
INSERT INTO sub_module_videos (
sub_module_id,
title,
description,
video_url,
duration,
resolution,
is_published,
publish_date,
visibility,
instructor_id,
thumbnail,
display_order,
status,
vimeo_id,
vimeo_embed_url,
vimeo_player_html,
vimeo_status,
video_host_provider
)
SELECT
sm.id,
scv.title,
scv.description,
scv.video_url,
scv.duration,
scv.resolution,
scv.is_published,
scv.publish_date,
scv.visibility,
scv.instructor_id,
scv.thumbnail,
scv.display_order,
scv.status,
scv.vimeo_id,
scv.vimeo_embed_url,
scv.vimeo_player_html,
scv.vimeo_status,
scv.video_host_provider
FROM sub_course_videos scv
JOIN sub_modules sm ON sm.legacy_sub_course_id = scv.sub_course_id
WHERE NOT EXISTS (
SELECT 1
FROM sub_module_videos smv
WHERE smv.sub_module_id = sm.id
AND smv.title = scv.title
AND COALESCE(smv.video_url, '') = COALESCE(scv.video_url, '')
);
UPDATE question_sets qs
SET owner_type = 'SUB_MODULE',
owner_id = sm.id
FROM sub_modules sm
WHERE qs.owner_type = 'SUB_COURSE'
AND qs.owner_id = sm.legacy_sub_course_id
AND qs.set_type = 'PRACTICE';
INSERT INTO sub_module_practices (sub_module_id, question_set_id, intro_video_url, display_order, is_active)
SELECT
sm.id,
qs.id,
qs.intro_video_url,
COALESCE(qs.display_order, 0),
(qs.status != 'ARCHIVED')
FROM question_sets qs
JOIN sub_modules sm
ON qs.owner_type = 'SUB_MODULE'
AND qs.owner_id = sm.id
WHERE qs.set_type = 'PRACTICE'
ON CONFLICT (question_set_id) DO NOTHING;
-- <<< END SOURCE: 000030_unified_hierarchy.up.sql
-- >>> BEGIN SOURCE: 000031_rename_sub_module_practices_to_lessons.up.sql
-- Keep practices as a separate feature and introduce lessons as a new table.
CREATE TABLE IF NOT EXISTS sub_module_lessons (
id BIGSERIAL PRIMARY KEY,
sub_module_id BIGINT NOT NULL REFERENCES sub_modules(id) ON DELETE CASCADE,
question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
intro_video_url TEXT,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(question_set_id)
);
CREATE INDEX IF NOT EXISTS idx_sub_module_lessons_sub_module_id
ON sub_module_lessons(sub_module_id);
-- <<< END SOURCE: 000031_rename_sub_module_practices_to_lessons.up.sql
-- >>> BEGIN SOURCE: 000032_add_sub_module_practices.up.sql
CREATE TABLE IF NOT EXISTS sub_module_practices (
id BIGSERIAL PRIMARY KEY,
sub_module_id BIGINT NOT NULL REFERENCES sub_modules(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
thumbnail TEXT,
intro_video_url TEXT,
question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(question_set_id)
);
-- If the table already existed from older unified hierarchy migrations,
-- backfill missing columns so practices keep their own richer schema.
ALTER TABLE sub_module_practices
ADD COLUMN IF NOT EXISTS title VARCHAR(255);
ALTER TABLE sub_module_practices
ADD COLUMN IF NOT EXISTS description TEXT;
ALTER TABLE sub_module_practices
ADD COLUMN IF NOT EXISTS thumbnail TEXT;
UPDATE sub_module_practices
SET title = COALESCE(NULLIF(title, ''), 'Practice')
WHERE title IS NULL OR title = '';
ALTER TABLE sub_module_practices
ALTER COLUMN title SET NOT NULL;
CREATE INDEX IF NOT EXISTS idx_sub_module_practices_sub_module_id
ON sub_module_practices(sub_module_id);
-- <<< END SOURCE: 000032_add_sub_module_practices.up.sql
-- >>> BEGIN SOURCE: 000033_sub_module_lessons_teaching_content.up.sql
-- Lessons are teaching content only (text, images, audio, video, thumbnail).
-- Question sets remain linked to practices, not lessons.
ALTER TABLE sub_module_lessons
ADD COLUMN IF NOT EXISTS title VARCHAR(255),
ADD COLUMN IF NOT EXISTS description TEXT,
ADD COLUMN IF NOT EXISTS thumbnail TEXT,
ADD COLUMN IF NOT EXISTS teaching_text TEXT,
ADD COLUMN IF NOT EXISTS teaching_image_url TEXT,
ADD COLUMN IF NOT EXISTS teaching_audio_url TEXT,
ADD COLUMN IF NOT EXISTS teaching_video_url TEXT;
UPDATE sub_module_lessons sml
SET
title = qs.title,
description = qs.description
FROM question_sets qs
WHERE sml.question_set_id IS NOT NULL
AND qs.id = sml.question_set_id;
UPDATE sub_module_lessons
SET title = 'Lesson'
WHERE title IS NULL OR trim(title) = '';
UPDATE sub_module_lessons
SET teaching_video_url = intro_video_url
WHERE intro_video_url IS NOT NULL;
ALTER TABLE sub_module_lessons DROP CONSTRAINT IF EXISTS sub_module_lessons_question_set_id_fkey;
ALTER TABLE sub_module_lessons DROP CONSTRAINT IF EXISTS sub_module_lessons_question_set_id_key;
ALTER TABLE sub_module_lessons DROP COLUMN IF EXISTS question_set_id;
ALTER TABLE sub_module_lessons DROP COLUMN IF EXISTS intro_video_url;
ALTER TABLE sub_module_lessons
ALTER COLUMN title SET NOT NULL,
ALTER COLUMN title SET DEFAULT 'Lesson';
-- <<< END SOURCE: 000033_sub_module_lessons_teaching_content.up.sql
-- >>> BEGIN SOURCE: 000034_levels_title_description_thumbnail.up.sql
ALTER TABLE levels
ADD COLUMN IF NOT EXISTS title VARCHAR(255),
ADD COLUMN IF NOT EXISTS description TEXT,
ADD COLUMN IF NOT EXISTS thumbnail TEXT;
UPDATE levels
SET title = cefr_level
WHERE title IS NULL OR trim(title) = '';
ALTER TABLE levels
ALTER COLUMN title SET NOT NULL;
-- <<< END SOURCE: 000034_levels_title_description_thumbnail.up.sql
-- >>> BEGIN SOURCE: 000035_sub_module_capstones.up.sql
-- Capstone assessments: sub-module scoped, backed by question_sets (type CAPSTONE).
ALTER TABLE question_sets DROP CONSTRAINT IF EXISTS question_sets_set_type_check;
ALTER TABLE question_sets ADD CONSTRAINT question_sets_set_type_check
CHECK (set_type IN (
'PRACTICE',
'INITIAL_ASSESSMENT',
'QUIZ',
'EXAM',
'SURVEY',
'CAPSTONE'
));
CREATE TABLE IF NOT EXISTS sub_module_capstones (
id BIGSERIAL PRIMARY KEY,
sub_module_id BIGINT NOT NULL REFERENCES sub_modules(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
tips TEXT,
thumbnail TEXT,
question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (question_set_id)
);
CREATE INDEX IF NOT EXISTS idx_sub_module_capstones_sub_module_id
ON sub_module_capstones (sub_module_id);
-- <<< END SOURCE: 000035_sub_module_capstones.up.sql
-- >>> BEGIN SOURCE: 000036_module_icon_and_module_capstones.up.sql
ALTER TABLE modules
ADD COLUMN IF NOT EXISTS icon_url TEXT;
CREATE TABLE IF NOT EXISTS module_capstones (
id BIGSERIAL PRIMARY KEY,
module_id BIGINT NOT NULL REFERENCES modules(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT,
tips TEXT,
thumbnail TEXT,
question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
display_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (question_set_id)
);
CREATE INDEX IF NOT EXISTS idx_module_capstones_module_id
ON module_capstones (module_id);
-- <<< END SOURCE: 000036_module_icon_and_module_capstones.up.sql
-- >>> BEGIN SOURCE: 000037_sub_modules_thumbnail_tips.up.sql
ALTER TABLE sub_modules
ADD COLUMN IF NOT EXISTS thumbnail TEXT,
ADD COLUMN IF NOT EXISTS tips TEXT;
-- <<< END SOURCE: 000037_sub_modules_thumbnail_tips.up.sql
-- >>> BEGIN SOURCE: 000038_levels_flexible_cefr_level.up.sql
-- Allow arbitrary level codes/labels per course (not only fixed CEFR bands).
DO $$
DECLARE
con_name text;
BEGIN
SELECT c.conname INTO con_name
FROM pg_constraint c
JOIN pg_class t ON c.conrelid = t.oid
JOIN pg_namespace n ON t.relnamespace = n.oid
WHERE n.nspname = current_schema()
AND t.relname = 'levels'
AND c.contype = 'c'
AND pg_get_constraintdef(c.oid) LIKE '%cefr_level%IN (%A1%';
IF con_name IS NOT NULL THEN
EXECUTE format('ALTER TABLE levels DROP CONSTRAINT %I', con_name);
END IF;
END $$;
ALTER TABLE levels
ALTER COLUMN cefr_level TYPE VARCHAR(64);
-- <<< END SOURCE: 000038_levels_flexible_cefr_level.up.sql
-- >>> BEGIN SOURCE: 000039_team_refresh_tokens.up.sql
CREATE TABLE IF NOT EXISTS team_refresh_tokens (
id BIGSERIAL PRIMARY KEY,
team_member_id BIGINT NOT NULL REFERENCES team_members(id) ON DELETE CASCADE,
token TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
revoked BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_team_refresh_tokens_team_member_id
ON team_refresh_tokens (team_member_id);
-- <<< END SOURCE: 000039_team_refresh_tokens.up.sql
-- >>> BEGIN SOURCE: 000040_sub_module_content_inactive_purge_tracking.up.sql
-- Track when submodule lessons, practices, and capstones became inactive for retention-based hard delete.
ALTER TABLE sub_module_lessons
ADD COLUMN IF NOT EXISTS inactive_since TIMESTAMPTZ;
ALTER TABLE sub_module_practices
ADD COLUMN IF NOT EXISTS inactive_since TIMESTAMPTZ;
ALTER TABLE sub_module_capstones
ADD COLUMN IF NOT EXISTS inactive_since TIMESTAMPTZ;
-- Existing inactive rows: start retention window from migration time (conservative).
UPDATE sub_module_lessons
SET inactive_since = NOW()
WHERE is_active = FALSE
AND inactive_since IS NULL;
UPDATE sub_module_practices
SET inactive_since = NOW()
WHERE is_active = FALSE
AND inactive_since IS NULL;
UPDATE sub_module_capstones
SET inactive_since = NOW()
WHERE is_active = FALSE
AND inactive_since IS NULL;
-- <<< END SOURCE: 000040_sub_module_content_inactive_purge_tracking.up.sql
-- >>> BEGIN SOURCE: 000041_remove_course_management_schema.up.sql
-- Tear down the legacy course / learning-tree schema so a new hierarchy can be introduced.
BEGIN;
-- Entry-assessment automation on sub_courses (from 000024)
DROP TRIGGER IF EXISTS trg_sub_courses_create_entry_assessment ON sub_courses;
DROP FUNCTION IF EXISTS create_sub_course_entry_assessment();
DROP FUNCTION IF EXISTS clone_default_initial_assessment_items(BIGINT);
DROP INDEX IF EXISTS idx_question_sets_unique_subcourse_initial_assessment;
ALTER TABLE question_sets DROP COLUMN IF EXISTS sub_course_video_id;
-- Dependent objects first
DROP TABLE IF EXISTS user_sub_course_video_progress CASCADE;
DROP TABLE IF EXISTS user_practice_progress CASCADE;
DROP TABLE IF EXISTS sub_course_prerequisites CASCADE;
DROP TABLE IF EXISTS user_sub_course_progress CASCADE;
DROP TABLE IF EXISTS sub_module_practices CASCADE;
DROP TABLE IF EXISTS sub_module_capstones CASCADE;
DROP TABLE IF EXISTS sub_module_lessons CASCADE;
DROP TABLE IF EXISTS sub_module_videos CASCADE;
DROP TABLE IF EXISTS sub_modules CASCADE;
DROP TABLE IF EXISTS module_capstones CASCADE;
DROP TABLE IF EXISTS modules CASCADE;
DROP TABLE IF EXISTS levels CASCADE;
DROP TABLE IF EXISTS sub_course_videos CASCADE;
DROP TABLE IF EXISTS sub_courses CASCADE;
DROP TABLE IF EXISTS course_sub_categories CASCADE;
DROP TABLE IF EXISTS courses CASCADE;
DROP TABLE IF EXISTS course_categories CASCADE;
-- Keep learner practice completion for the questions system (no sub_course column)
CREATE TABLE user_practice_progress (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
completed_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (user_id, question_set_id)
);
CREATE INDEX idx_user_practice_progress_user_id ON user_practice_progress(user_id);
COMMIT;
-- <<< END SOURCE: 000041_remove_course_management_schema.up.sql
-- >>> BEGIN SOURCE: 000042_programs.up.sql
-- Top-level LMS program (e.g. Beginner / Intermediate / Advanced — labels come from admin config later).
CREATE TABLE programs (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
thumbnail TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_programs_created_at ON programs (created_at DESC);
-- <<< END SOURCE: 000042_programs.up.sql
-- >>> BEGIN SOURCE: 000043_seed_default_programs.up.sql
-- Default top-level programs (hierarchy: Program → Course → …).
INSERT INTO programs (name, description, thumbnail)
VALUES
('Beginner', 'Default program for the beginner level.', NULL),
('Intermediate', 'Default program for the intermediate level.', NULL),
('Advanced', 'Default program for the advanced level.', NULL);
-- <<< END SOURCE: 000043_seed_default_programs.up.sql
-- >>> BEGIN SOURCE: 000044_lms_courses.up.sql
-- Courses belong to a Program (CEFR-style labels like A1..C2 will be configured separately).
CREATE TABLE courses (
id BIGSERIAL PRIMARY KEY,
program_id BIGINT NOT NULL REFERENCES programs (id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
description TEXT,
thumbnail TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_courses_program_id ON courses (program_id);
CREATE INDEX idx_courses_program_created ON courses (program_id, created_at DESC);
-- <<< END SOURCE: 000044_lms_courses.up.sql
-- >>> BEGIN SOURCE: 000045_lms_modules.up.sql
-- Modules belong to a Course; program_id is denormalized and enforced with the course by a composite FK.
ALTER TABLE courses
ADD CONSTRAINT courses_program_id_id_key UNIQUE (program_id, id);
CREATE TABLE modules (
id BIGSERIAL PRIMARY KEY,
program_id BIGINT NOT NULL,
course_id BIGINT NOT NULL,
name VARCHAR(255) NOT NULL,
description TEXT,
icon TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ,
CONSTRAINT modules_course_scope_fkey
FOREIGN KEY (program_id, course_id)
REFERENCES courses (program_id, id)
ON DELETE CASCADE
);
CREATE INDEX idx_modules_course_id ON modules (course_id);
CREATE INDEX idx_modules_program_id ON modules (program_id);
CREATE INDEX idx_modules_program_course_created ON modules (program_id, course_id, created_at DESC);
-- <<< END SOURCE: 000045_lms_modules.up.sql
-- >>> BEGIN SOURCE: 000046_lms_lessons.up.sql
-- Lessons belong to a Module.
CREATE TABLE lessons (
id BIGSERIAL PRIMARY KEY,
module_id BIGINT NOT NULL REFERENCES modules (id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
video_url TEXT,
thumbnail TEXT,
description TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_lessons_module_id ON lessons (module_id);
CREATE INDEX idx_lessons_module_created ON lessons (module_id, created_at DESC);
-- <<< END SOURCE: 000046_lms_lessons.up.sql
-- >>> BEGIN SOURCE: 000047_lms_practices.up.sql
-- Practices attach to exactly one of: course, module, or lesson.
CREATE TABLE lms_practices (
id BIGSERIAL PRIMARY KEY,
course_id BIGINT REFERENCES courses (id) ON DELETE CASCADE,
module_id BIGINT REFERENCES modules (id) ON DELETE CASCADE,
lesson_id BIGINT REFERENCES lessons (id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
story_description TEXT,
story_image TEXT,
persona_id BIGINT REFERENCES users (id) ON DELETE SET NULL,
question_set_id BIGINT NOT NULL REFERENCES question_sets (id) ON DELETE RESTRICT,
quick_tips TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ,
CONSTRAINT lms_practices_one_parent CHECK (
(course_id IS NOT NULL)::int
+ (module_id IS NOT NULL)::int
+ (lesson_id IS NOT NULL)::int
= 1
)
);
CREATE INDEX idx_lms_practices_course_id ON lms_practices (course_id);
CREATE INDEX idx_lms_practices_module_id ON lms_practices (module_id);
CREATE INDEX idx_lms_practices_lesson_id ON lms_practices (lesson_id);
CREATE INDEX idx_lms_practices_question_set_id ON lms_practices (question_set_id);
CREATE INDEX idx_lms_practices_course_created ON lms_practices (course_id, created_at DESC);
CREATE INDEX idx_lms_practices_module_created ON lms_practices (module_id, created_at DESC);
CREATE INDEX idx_lms_practices_lesson_created ON lms_practices (lesson_id, created_at DESC);
-- <<< END SOURCE: 000047_lms_practices.up.sql
-- >>> BEGIN SOURCE: 000048_seed_default_courses.up.sql
-- Default CEFR-style courses per seeded program: Beginner→A1,A2; Intermediate→B1,B2; Advanced→C1,C2.
-- Custom courses can still be created via the API with any name.
INSERT INTO courses (program_id, name, description, thumbnail)
SELECT
p.id,
v.name,
'Default CEFR level course (system seed).',
NULL
FROM programs AS p
INNER JOIN (
VALUES
('Beginner', 'A1'),
('Beginner', 'A2'),
('Intermediate', 'B1'),
('Intermediate', 'B2'),
('Advanced', 'C1'),
('Advanced', 'C2')
) AS v (program_name, name)
ON p.name = v.program_name;
-- <<< END SOURCE: 000048_seed_default_courses.up.sql
-- >>> BEGIN SOURCE: 000049_lms_sequential_learning.up.sql
-- Sequential order for programs, courses, modules, and lessons (1 = first in each scope).
-- Progress tables mark completion; API enforces prerequisites for learners (STUDENT role).
ALTER TABLE programs
ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0;
ALTER TABLE courses
ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0;
ALTER TABLE modules
ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0;
ALTER TABLE lessons
ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0;
-- Program order (one global sequence): Beginner -> Intermediate -> Advanced; others by id
UPDATE programs
SET sort_order = v.so
FROM (
VALUES
('Beginner', 1),
('Intermediate', 2),
('Advanced', 3)
) AS v (name, so)
WHERE programs.name = v.name;
UPDATE programs
SET sort_order = 1000 + r.rn
FROM (
SELECT
id,
row_number() OVER (
ORDER BY id
) AS rn
FROM programs
WHERE
sort_order = 0
) AS r
WHERE
programs.id = r.id;
-- CEFR courses: A1..C2; remaining courses in each program: stable order
UPDATE courses
SET sort_order = CASE name
WHEN 'A1' THEN
1
WHEN 'A2' THEN
2
WHEN 'B1' THEN
3
WHEN 'B2' THEN
4
WHEN 'C1' THEN
5
WHEN 'C2' THEN
6
ELSE
0
END
WHERE
name IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2');
UPDATE courses c
SET sort_order = 2000 + s.rn
FROM (
SELECT
id,
row_number() OVER (
PARTITION BY program_id
ORDER BY
id
) AS rn
FROM courses
WHERE
sort_order = 0
) AS s
WHERE
c.id = s.id;
UPDATE modules m
SET sort_order = r.rn
FROM (
SELECT
id,
row_number() OVER (
PARTITION BY course_id
ORDER BY
id
) AS rn
FROM modules
) AS r
WHERE
m.id = r.id;
UPDATE lessons l
SET sort_order = r.rn
FROM (
SELECT
id,
row_number() OVER (
PARTITION BY module_id
ORDER BY
id
) AS rn
FROM lessons
) AS r
WHERE
l.id = r.id;
CREATE UNIQUE INDEX uq_programs_sort_order ON programs (sort_order);
CREATE UNIQUE INDEX uq_courses_program_sort ON courses (program_id, sort_order);
CREATE UNIQUE INDEX uq_modules_course_sort ON modules (course_id, sort_order);
CREATE UNIQUE INDEX uq_lessons_module_sort ON lessons (module_id, sort_order);
CREATE TABLE lms_user_lesson_progress (
user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
lesson_id BIGINT NOT NULL REFERENCES lessons (id) ON DELETE CASCADE,
completed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, lesson_id)
);
CREATE INDEX idx_lms_user_lesson_progress_user ON lms_user_lesson_progress (user_id);
CREATE INDEX idx_lms_user_lesson_progress_lesson ON lms_user_lesson_progress (lesson_id);
CREATE TABLE lms_user_module_progress (
user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
module_id BIGINT NOT NULL REFERENCES modules (id) ON DELETE CASCADE,
completed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, module_id)
);
CREATE INDEX idx_lms_user_module_progress_user ON lms_user_module_progress (user_id);
CREATE INDEX idx_lms_user_module_progress_module ON lms_user_module_progress (module_id);
CREATE TABLE lms_user_course_progress (
user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
course_id BIGINT NOT NULL REFERENCES courses (id) ON DELETE CASCADE,
completed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, course_id)
);
CREATE INDEX idx_lms_user_course_progress_user ON lms_user_course_progress (user_id);
CREATE INDEX idx_lms_user_course_progress_course ON lms_user_course_progress (course_id);
CREATE TABLE lms_user_program_progress (
user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
program_id BIGINT NOT NULL REFERENCES programs (id) ON DELETE CASCADE,
completed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, program_id)
);
CREATE INDEX idx_lms_user_program_progress_user ON lms_user_program_progress (user_id);
CREATE INDEX idx_lms_user_program_progress_program ON lms_user_program_progress (program_id);
-- <<< END SOURCE: 000049_lms_sequential_learning.up.sql
-- >>> BEGIN SOURCE: 000050_default_courses_per_program.up.sql
-- Align default seeded courses with program: Beginner→A1,A2; Intermediate→B1,B2; Advanced→C1,C2.
-- Only touches rows with the system seed description; custom courses are unchanged.
-- Removing a course cascades to modules, lessons, and related LMS progress (see FKs on those tables).
DELETE FROM courses AS c
USING programs AS p
WHERE c.program_id = p.id
AND c.description = 'Default CEFR level course (system seed).'
AND (
(
p.name = 'Beginner'
AND c.name IN ('B1', 'B2', 'C1', 'C2')
)
OR (
p.name = 'Intermediate'
AND c.name IN ('A1', 'A2', 'C1', 'C2')
)
OR (
p.name = 'Advanced'
AND c.name IN ('A1', 'A2', 'B1', 'B2')
)
);
INSERT INTO courses (program_id, name, description, thumbnail)
SELECT
p.id,
v.name,
'Default CEFR level course (system seed).',
NULL
FROM programs AS p
INNER JOIN (
VALUES
('Beginner', 'A1'),
('Beginner', 'A2'),
('Intermediate', 'B1'),
('Intermediate', 'B2'),
('Advanced', 'C1'),
('Advanced', 'C2')
) AS v (program_name, name)
ON p.name = v.program_name
WHERE
NOT EXISTS (
SELECT 1 FROM courses AS e
WHERE e.program_id = p.id AND e.name = v.name
);
-- <<< END SOURCE: 000050_default_courses_per_program.up.sql
-- >>> BEGIN SOURCE: 000051_exam_prep_schema.up.sql
-- Standalone exam-prep content hierarchy (DET, IELTS, TOEFL, etc.) — isolated from LMS Learn English tables.
CREATE SCHEMA IF NOT EXISTS exam_prep;
-- Top-level catalog "course" (e.g. Duolingo English Test, IELTS); admin-configurable labels.
CREATE TABLE exam_prep.catalog_courses (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
thumbnail TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_exam_prep_catalog_courses_sort ON exam_prep.catalog_courses (sort_order, id);
-- <<< END SOURCE: 000051_exam_prep_schema.up.sql
-- >>> BEGIN SOURCE: 000052_exam_prep_units.up.sql
-- Units under an exam-prep catalog course (e.g. "Introduction to the DET English Test").
CREATE TABLE exam_prep.units (
id BIGSERIAL PRIMARY KEY,
catalog_course_id BIGINT NOT NULL REFERENCES exam_prep.catalog_courses (id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
description TEXT,
thumbnail TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_exam_prep_units_catalog_course_id ON exam_prep.units (catalog_course_id);
CREATE INDEX idx_exam_prep_units_catalog_sort ON exam_prep.units (catalog_course_id, sort_order, id);
-- <<< END SOURCE: 000052_exam_prep_units.up.sql
-- >>> BEGIN SOURCE: 000053_exam_prep_unit_modules.up.sql
-- Modules under an exam-prep unit (table name unit_modules avoids sqlc/LMS collision with public.modules).
CREATE TABLE exam_prep.unit_modules (
id BIGSERIAL PRIMARY KEY,
unit_id BIGINT NOT NULL REFERENCES exam_prep.units (id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
description TEXT,
thumbnail TEXT,
icon TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_exam_prep_unit_modules_unit_id ON exam_prep.unit_modules (unit_id);
CREATE INDEX idx_exam_prep_unit_modules_unit_sort ON exam_prep.unit_modules (unit_id, sort_order, id);
-- <<< END SOURCE: 000053_exam_prep_unit_modules.up.sql
-- >>> BEGIN SOURCE: 000054_exam_prep_unit_module_lessons.up.sql
-- Lessons under an exam-prep unit module (mirrors LMS lessons under modules; avoids collision with public.lessons / sqlc).
CREATE TABLE exam_prep.unit_module_lessons (
id BIGSERIAL PRIMARY KEY,
unit_module_id BIGINT NOT NULL REFERENCES exam_prep.unit_modules (id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
video_url TEXT,
thumbnail TEXT,
description TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX uq_exam_prep_unit_module_lessons_sort ON exam_prep.unit_module_lessons (unit_module_id, sort_order);
CREATE INDEX idx_exam_prep_unit_module_lessons_module_id ON exam_prep.unit_module_lessons (unit_module_id);
CREATE INDEX idx_exam_prep_unit_module_lessons_module_created ON exam_prep.unit_module_lessons (unit_module_id, created_at DESC);
-- <<< END SOURCE: 000054_exam_prep_unit_module_lessons.up.sql
-- >>> BEGIN SOURCE: 000055_exam_prep_lesson_practices.up.sql
-- Exam-prep practices: one row per practice, attached to an exam-prep lesson only; reuses public.question_sets / questions.
CREATE TABLE exam_prep.lesson_practices (
id BIGSERIAL PRIMARY KEY,
unit_module_lesson_id BIGINT NOT NULL REFERENCES exam_prep.unit_module_lessons (id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
story_description TEXT,
story_image TEXT,
persona_id BIGINT REFERENCES users (id) ON DELETE SET NULL,
question_set_id BIGINT NOT NULL REFERENCES question_sets (id) ON DELETE RESTRICT,
quick_tips TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_exam_prep_lesson_practices_lesson_id ON exam_prep.lesson_practices (unit_module_lesson_id);
CREATE INDEX idx_exam_prep_lesson_practices_question_set_id ON exam_prep.lesson_practices (question_set_id);
CREATE INDEX idx_exam_prep_lesson_practices_lesson_created ON exam_prep.lesson_practices (unit_module_lesson_id, created_at DESC);
-- <<< END SOURCE: 000055_exam_prep_lesson_practices.up.sql
-- >>> BEGIN SOURCE: 000056_dynamic_question_type_definitions.up.sql
CREATE TABLE IF NOT EXISTS question_type_definitions (
id BIGSERIAL PRIMARY KEY,
key VARCHAR(64) NOT NULL UNIQUE,
display_name VARCHAR(120) NOT NULL,
description TEXT,
stimulus_component_kinds TEXT[] NOT NULL DEFAULT '{}',
response_component_kinds TEXT[] NOT NULL DEFAULT '{}',
is_system BOOLEAN NOT NULL DEFAULT FALSE,
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'INACTIVE')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_question_type_definitions_status
ON question_type_definitions(status);
INSERT INTO question_type_definitions
(key, display_name, description, stimulus_component_kinds, response_component_kinds, is_system, status)
VALUES
(
'multiple_choice',
'Multiple Choice',
'Select one correct answer from a list of options.',
ARRAY['INSTRUCTION']::TEXT[],
ARRAY['MULTIPLE_CHOICE']::TEXT[],
TRUE,
'ACTIVE'
),
(
'true_false',
'True / False',
'Binary response question with true/false options.',
ARRAY['INSTRUCTION']::TEXT[],
ARRAY['MULTIPLE_CHOICE']::TEXT[],
TRUE,
'ACTIVE'
),
(
'fill_in_the_blank',
'Fill In The Blank',
'Learner fills missing words in a prompt or passage.',
ARRAY['TEXT_PASSAGE', 'SELECT_MISSING_WORDS']::TEXT[],
ARRAY['TEXT_INPUT', 'SELECT_MISSING_WORDS']::TEXT[],
TRUE,
'ACTIVE'
),
(
'short_answer',
'Short Answer',
'Learner provides a concise text answer.',
ARRAY['INSTRUCTION']::TEXT[],
ARRAY['SHORT_ANSWER']::TEXT[],
TRUE,
'ACTIVE'
)
ON CONFLICT (key) DO NOTHING;
-- <<< END SOURCE: 000056_dynamic_question_type_definitions.up.sql
-- >>> BEGIN SOURCE: 000057_questions_dynamic_type_link.up.sql
ALTER TABLE questions
ADD COLUMN IF NOT EXISTS question_type_definition_id BIGINT NULL;
ALTER TABLE questions
DROP CONSTRAINT IF EXISTS questions_question_type_definition_id_fkey;
ALTER TABLE questions
ADD CONSTRAINT questions_question_type_definition_id_fkey
FOREIGN KEY (question_type_definition_id)
REFERENCES question_type_definitions(id)
ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_questions_question_type_definition_id
ON questions(question_type_definition_id);
-- <<< END SOURCE: 000057_questions_dynamic_type_link.up.sql
-- >>> BEGIN SOURCE: 000058_dynamic_question_builder_runtime.up.sql
ALTER TABLE questions
DROP CONSTRAINT IF EXISTS questions_question_type_check;
ALTER TABLE questions
ADD CONSTRAINT questions_question_type_check
CHECK (question_type IN ('MCQ', 'TRUE_FALSE', 'SHORT_ANSWER', 'AUDIO', 'DYNAMIC'));
ALTER TABLE questions
ADD COLUMN IF NOT EXISTS dynamic_payload JSONB NULL;
ALTER TABLE question_type_definitions
ADD COLUMN IF NOT EXISTS stimulus_schema JSONB NOT NULL DEFAULT '[]'::jsonb,
ADD COLUMN IF NOT EXISTS response_schema JSONB NOT NULL DEFAULT '[]'::jsonb;
-- <<< END SOURCE: 000058_dynamic_question_builder_runtime.up.sql
-- >>> BEGIN SOURCE: 000059_faqs.up.sql
CREATE TABLE IF NOT EXISTS faqs (
id BIGSERIAL PRIMARY KEY,
question TEXT NOT NULL,
answer TEXT NOT NULL,
category VARCHAR(100),
display_order INT NOT NULL DEFAULT 0,
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'INACTIVE')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_faqs_status ON faqs(status);
CREATE INDEX IF NOT EXISTS idx_faqs_category ON faqs(category);
CREATE INDEX IF NOT EXISTS idx_faqs_display_order ON faqs(display_order);
-- <<< END SOURCE: 000059_faqs.up.sql
-- >>> BEGIN SOURCE: 000060_practice_publish_status.up.sql
-- Draft vs published visibility for LMS and exam-prep practices.
ALTER TABLE lms_practices
ADD COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'PUBLISHED'
CONSTRAINT chk_lms_practices_publish_status CHECK (publish_status IN ('DRAFT', 'PUBLISHED'));
ALTER TABLE exam_prep.lesson_practices
ADD COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'PUBLISHED'
CONSTRAINT chk_exam_prep_lesson_practices_publish_status CHECK (publish_status IN ('DRAFT', 'PUBLISHED'));
-- <<< END SOURCE: 000060_practice_publish_status.up.sql
-- >>> BEGIN SOURCE: 000061_open_learner_role.up.sql
-- OPEN_LEARNER: learner role with STUDENT-like RBAC but without LMS sequential prerequisite locks (handled in app code).
CREATE EXTENSION IF NOT EXISTS pgcrypto;
INSERT INTO roles (name, description, is_system) VALUES
(
'OPEN_LEARNER',
'Learner with full LMS catalog access without sequential prerequisite locking',
TRUE
)
ON CONFLICT (name) DO NOTHING;
-- Demo OPEN_LEARNER (customer-login): openlearner@rezina.com / password@123
INSERT INTO users (
id,
first_name,
last_name,
gender,
birth_day,
email,
phone_number,
role,
password,
age_group,
education_level,
country,
region,
knowledge_level,
nick_name,
occupation,
learning_goal,
language_goal,
language_challange,
favourite_topic,
initial_assessment_completed,
email_verified,
phone_verified,
status,
last_login,
profile_completed,
profile_picture_url,
preferred_language,
created_at,
updated_at
)
VALUES
(
13,
'Demo',
'OpenLearner',
'Female',
'1999-06-01',
'openlearner@rezina.com',
NULL,
'OPEN_LEARNER',
crypt('password@123', gen_salt('bf'))::bytea,
'25_34',
'Bachelor',
'Ethiopia',
'Addis Ababa',
'BEGINNER',
'OpenLearner',
'Tester',
'Preview LMS content without sequential locks',
'English',
'Grammar',
'Technology',
FALSE,
TRUE,
FALSE,
'ACTIVE',
NULL,
FALSE,
NULL,
'en',
CURRENT_TIMESTAMP,
NULL
)
ON CONFLICT (id) DO NOTHING;
-- <<< END SOURCE: 000061_open_learner_role.up.sql
-- >>> BEGIN SOURCE: 000062_lesson_publish_status.up.sql
-- Draft vs published visibility for LMS lessons (mirrors lms_practices.publish_status).
ALTER TABLE lessons
ADD COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'PUBLISHED'
CONSTRAINT chk_lessons_publish_status CHECK (publish_status IN ('DRAFT', 'PUBLISHED'));
-- New inserts default to draft unless the API sends PUBLISHED; existing rows stay published.
ALTER TABLE lessons
ALTER COLUMN publish_status SET DEFAULT 'DRAFT';
-- <<< END SOURCE: 000062_lesson_publish_status.up.sql
-- >>> BEGIN SOURCE: 000063_lms_personas.up.sql
-- Catalog of LMS personas (coach/avatar profiles) referenced by Learn English + exam-prep practices.
CREATE TABLE lms_personas (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
avatar_url TEXT,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ
);
CREATE INDEX idx_lms_personas_is_active ON lms_personas (is_active)
WHERE is_active;
CREATE INDEX idx_lms_personas_created_at ON lms_personas (created_at DESC);
-- Default catalog personas (stable ids for envs and Postman); add more via API.
INSERT INTO lms_personas (id, name, description, avatar_url, is_active)
VALUES
(
1,
'Friendly Coach',
'Warm, encouraging tutor for everyday conversational practice.',
NULL,
TRUE
),
(
2,
'Exam Coach',
'Structured, exam-style guidance and clear checkpoints.',
NULL,
TRUE
),
(
3,
'Story Narrator',
'Story-led scenarios with character-driven prompts.',
NULL,
TRUE
);
SELECT setval(
pg_get_serial_sequence('lms_personas', 'id'),
(SELECT COALESCE(MAX(id), 1) FROM lms_personas)
);
-- persona_id historically referenced users.id; personas are now catalog rows on lms_personas.
ALTER TABLE lms_practices DROP CONSTRAINT IF EXISTS lms_practices_persona_id_fkey;
UPDATE lms_practices
SET persona_id = NULL
WHERE persona_id IS NOT NULL;
ALTER TABLE lms_practices
ADD CONSTRAINT lms_practices_persona_id_fkey FOREIGN KEY (persona_id) REFERENCES lms_personas (id) ON DELETE SET NULL;
ALTER TABLE exam_prep.lesson_practices DROP CONSTRAINT IF EXISTS lesson_practices_persona_id_fkey;
UPDATE exam_prep.lesson_practices
SET persona_id = NULL
WHERE persona_id IS NOT NULL;
ALTER TABLE exam_prep.lesson_practices
ADD CONSTRAINT lesson_practices_persona_id_fkey FOREIGN KEY (persona_id) REFERENCES lms_personas (id) ON DELETE SET NULL;
-- <<< END SOURCE: 000063_lms_personas.up.sql
-- >>> BEGIN SOURCE: 000064_lms_personas_profile_picture.up.sql
-- Persona profile image URL stored as profile_picture (replaces avatar_url naming).
ALTER TABLE lms_personas
RENAME COLUMN avatar_url TO profile_picture;
-- <<< END SOURCE: 000064_lms_personas_profile_picture.up.sql
-- >>> BEGIN SOURCE: 000065_lms_personas_gender.up.sql
ALTER TABLE lms_personas
ADD COLUMN gender TEXT;
-- <<< END SOURCE: 000065_lms_personas_gender.up.sql
-- >>> BEGIN SOURCE: 000066_email_templates.up.sql
CREATE TABLE IF NOT EXISTS email_templates (
id BIGSERIAL PRIMARY KEY,
slug VARCHAR(100) NOT NULL UNIQUE,
name VARCHAR(200) NOT NULL,
subject TEXT NOT NULL,
body_text TEXT NOT NULL,
body_html TEXT NOT NULL,
variables JSONB NOT NULL DEFAULT '[]'::jsonb,
is_system BOOLEAN NOT NULL DEFAULT FALSE,
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'INACTIVE')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_email_templates_status ON email_templates(status);
CREATE INDEX IF NOT EXISTS idx_email_templates_slug ON email_templates(slug);
INSERT INTO email_templates (slug, name, subject, body_text, body_html, variables, is_system, status)
VALUES
(
'otp',
'One-Time Password',
'Rezina — Your verification code',
'Rezina{{if .FirstName}}, {{.FirstName}}{{end}}
Your verification code is {{.OTP}}.
It expires in {{.ExpiresMinutes}} minutes.
Please do not share this code with anyone.',
$otp_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;letter-spacing:0.3px;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;line-height:1.3;">Your verification code</h1>
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}use the code below to continue signing in to Rezina.</p>
<table role="presentation" width="100%" cellspacing="0" cellpadding="0"><tr><td style="background-color:#eef4ff;border-radius:8px;padding:20px;border:1px solid #e0e8f5;text-align:center;">
<p style="margin:0 0 6px;color:#9d2a83;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;">One-time password</p>
<p style="margin:0;color:#333333;font-size:34px;font-weight:700;letter-spacing:8px;font-family:Consolas,Monaco,monospace;">{{.OTP}}</p>
<p style="margin:12px 0 0;color:#666666;font-size:13px;">Expires in {{.ExpiresMinutes}} minutes</p>
</td></tr></table>
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">If you did not request this code, you can safely ignore this email.</p>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;line-height:1.5;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$otp_html$,
'["OTP", "FirstName", "ExpiresMinutes"]'::jsonb,
TRUE,
'ACTIVE'
),
(
'invitation',
'User Invitation',
'You are invited to Rezina',
'Hi{{if .FirstName}} {{.FirstName}}{{end}},
You have been invited{{if .InviterName}} by {{.InviterName}}{{end}} to join Rezina.
Accept your invitation: {{.InviteLink}}',
$invite_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">You&rsquo;re invited</h1>
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}you have been invited{{if .InviterName}} by <strong style="color:#9d2a83;">{{.InviterName}}</strong>{{end}} to join Rezina.</p>
<p style="margin:0 0 24px;text-align:center;"><a href="{{.InviteLink}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Accept invitation</a></p>
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">Or copy this link: <a href="{{.InviteLink}}" style="color:#9d2a83;">{{.InviteLink}}</a></p>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$invite_html$,
'["FirstName", "InviterName", "InviteLink"]'::jsonb,
TRUE,
'ACTIVE'
),
(
'password_reset',
'Password Reset',
'Reset your Rezina password',
'Hi{{if .FirstName}} {{.FirstName}}{{end}},
Reset your password: {{.ResetLink}}
This link expires in {{.ExpiresMinutes}} minutes.',
$reset_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Reset your password</h1>
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}we received a request to reset your Rezina password. The link below expires in {{.ExpiresMinutes}} minutes.</p>
<p style="margin:0 0 24px;text-align:center;"><a href="{{.ResetLink}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Reset password</a></p>
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">If you did not request a reset, ignore this email.</p>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$reset_html$,
'["FirstName", "ResetLink", "ExpiresMinutes"]'::jsonb,
TRUE,
'ACTIVE'
),
(
'welcome',
'Welcome Email',
'Welcome to Rezina',
'Hi{{if .FirstName}} {{.FirstName}}{{end}},
Welcome to Rezina! Sign in to get started: {{.LoginURL}}',
$welcome_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Welcome aboard</h1>
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}your Rezina account is ready. Start learning at your own pace.</p>
<p style="margin:0 0 24px;text-align:center;"><a href="{{.LoginURL}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Sign in to Rezina</a></p>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$welcome_html$,
'["FirstName", "LoginURL"]'::jsonb,
TRUE,
'ACTIVE'
),
(
'custom_message',
'Custom Message',
'{{.Subject}}',
'{{.Message}}',
$custom_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">{{.Subject}}</h1>
<div style="margin:0;color:#666666;font-size:15px;line-height:1.6;">{{.Message}}</div>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$custom_html$,
'["Subject", "Message"]'::jsonb,
TRUE,
'ACTIVE'
)
ON CONFLICT (slug) DO NOTHING;
-- <<< END SOURCE: 000066_email_templates.up.sql
-- >>> BEGIN SOURCE: 000067_branded_email_template_seeds.up.sql
-- Refresh system email templates with Rezina branded HTML (admin portal colors).
-- Safe to run after 000066 when seeds used the original plain layout.
UPDATE email_templates SET
name = 'One-Time Password',
subject = 'Rezina — Your verification code',
body_text = 'Rezina{{if .FirstName}}, {{.FirstName}}{{end}}
Your verification code is {{.OTP}}.
It expires in {{.ExpiresMinutes}} minutes.
Please do not share this code with anyone.',
body_html = $otp_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;letter-spacing:0.3px;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;line-height:1.3;">Your verification code</h1>
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}use the code below to continue signing in to Rezina.</p>
<table role="presentation" width="100%" cellspacing="0" cellpadding="0"><tr><td style="background-color:#eef4ff;border-radius:8px;padding:20px;border:1px solid #e0e8f5;text-align:center;">
<p style="margin:0 0 6px;color:#9d2a83;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.08em;">One-time password</p>
<p style="margin:0;color:#333333;font-size:34px;font-weight:700;letter-spacing:8px;font-family:Consolas,Monaco,monospace;">{{.OTP}}</p>
<p style="margin:12px 0 0;color:#666666;font-size:13px;">Expires in {{.ExpiresMinutes}} minutes</p>
</td></tr></table>
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">If you did not request this code, you can safely ignore this email.</p>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;line-height:1.5;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$otp_html$,
updated_at = NOW()
WHERE slug = 'otp';
UPDATE email_templates SET
name = 'User Invitation',
subject = 'You are invited to Rezina',
body_text = 'Hi{{if .FirstName}} {{.FirstName}}{{end}},
You have been invited{{if .InviterName}} by {{.InviterName}}{{end}} to join Rezina.
Accept your invitation: {{.InviteLink}}',
body_html = $invite_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">You&rsquo;re invited</h1>
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}you have been invited{{if .InviterName}} by <strong style="color:#9d2a83;">{{.InviterName}}</strong>{{end}} to join Rezina.</p>
<p style="margin:0 0 24px;text-align:center;"><a href="{{.InviteLink}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Accept invitation</a></p>
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">Or copy this link: <a href="{{.InviteLink}}" style="color:#9d2a83;">{{.InviteLink}}</a></p>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$invite_html$,
updated_at = NOW()
WHERE slug = 'invitation';
UPDATE email_templates SET
name = 'Password Reset',
subject = 'Reset your Rezina password',
body_text = 'Hi{{if .FirstName}} {{.FirstName}}{{end}},
Reset your password: {{.ResetLink}}
This link expires in {{.ExpiresMinutes}} minutes.',
body_html = $reset_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Reset your password</h1>
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}we received a request to reset your Rezina password. The link below expires in {{.ExpiresMinutes}} minutes.</p>
<p style="margin:0 0 24px;text-align:center;"><a href="{{.ResetLink}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Reset password</a></p>
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">If you did not request a reset, ignore this email.</p>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$reset_html$,
updated_at = NOW()
WHERE slug = 'password_reset';
UPDATE email_templates SET
name = 'Welcome Email',
subject = 'Welcome to Rezina',
body_text = 'Hi{{if .FirstName}} {{.FirstName}}{{end}},
Welcome to Rezina! Sign in to get started: {{.LoginURL}}',
body_html = $welcome_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Welcome aboard</h1>
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}your Rezina account is ready. Start learning at your own pace.</p>
<p style="margin:0 0 24px;text-align:center;"><a href="{{.LoginURL}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Sign in to Rezina</a></p>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$welcome_html$,
updated_at = NOW()
WHERE slug = 'welcome';
UPDATE email_templates SET
name = 'Custom Message',
body_html = $custom_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">{{.Subject}}</h1>
<div style="margin:0;color:#666666;font-size:15px;line-height:1.6;">{{.Message}}</div>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$custom_html$,
updated_at = NOW()
WHERE slug = 'custom_message';
-- <<< END SOURCE: 000067_branded_email_template_seeds.up.sql
-- >>> BEGIN SOURCE: 000068_team_invitations.up.sql
CREATE TABLE IF NOT EXISTS team_invitations (
id BIGSERIAL PRIMARY KEY,
team_member_id BIGINT NOT NULL REFERENCES team_members(id) ON DELETE CASCADE,
token VARCHAR(128) NOT NULL UNIQUE,
status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (
status IN ('pending', 'accepted', 'expired', 'revoked')
),
expires_at TIMESTAMPTZ NOT NULL,
invited_by BIGINT,
accepted_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_team_invitations_token ON team_invitations(token);
CREATE INDEX IF NOT EXISTS idx_team_invitations_team_member_id ON team_invitations(team_member_id);
CREATE INDEX IF NOT EXISTS idx_team_invitations_status ON team_invitations(status);
CREATE INDEX IF NOT EXISTS idx_team_invitations_expires_at ON team_invitations(expires_at);
-- <<< END SOURCE: 000068_team_invitations.up.sql
-- >>> BEGIN SOURCE: 000069_profile_field_options.up.sql
CREATE TABLE IF NOT EXISTS field_options (
id BIGSERIAL PRIMARY KEY,
field_key VARCHAR(50) NOT NULL,
code VARCHAR(50) NOT NULL,
label VARCHAR(255) NOT NULL,
display_order INT NOT NULL DEFAULT 0,
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'INACTIVE')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ,
CONSTRAINT field_options_field_key_format CHECK (field_key ~ '^[a-z][a-z0-9_]*$'),
CONSTRAINT field_options_unique_field_code UNIQUE (field_key, code)
);
CREATE INDEX IF NOT EXISTS idx_field_options_field_key ON field_options(field_key);
CREATE INDEX IF NOT EXISTS idx_field_options_status ON field_options(status);
CREATE INDEX IF NOT EXISTS idx_field_options_display_order ON field_options(display_order);
INSERT INTO field_options (field_key, code, label, display_order, status) VALUES
('education_level', 'NO_FORMAL', 'No formal education', 1, 'ACTIVE'),
('education_level', 'PRIMARY', 'Primary school', 2, 'ACTIVE'),
('education_level', 'SECONDARY', 'Secondary school', 3, 'ACTIVE'),
('education_level', 'HIGH_SCHOOL', 'High school', 4, 'ACTIVE'),
('education_level', 'VOCATIONAL', 'Vocational / technical', 5, 'ACTIVE'),
('education_level', 'BACHELOR', 'Bachelor''s degree', 6, 'ACTIVE'),
('education_level', 'MASTER', 'Master''s degree', 7, 'ACTIVE'),
('education_level', 'DOCTORATE', 'Doctorate', 8, 'ACTIVE'),
('education_level', 'OTHER', 'Other', 99, 'ACTIVE'),
('occupation', 'STUDENTS', 'Students (High school & University)', 1, 'ACTIVE'),
('occupation', 'JOB_SEEKERS', 'Job Seekers / Fresh Graduates', 2, 'ACTIVE'),
('occupation', 'WORKING_PROFESSIONALS', 'Working Professionals (Corporate/Office)', 3, 'ACTIVE'),
('occupation', 'GOVERNMENT_NGO', 'Government & NGO Workers', 4, 'ACTIVE'),
('occupation', 'ENTREPRENEURS', 'Entrepreneurs & Small Business Owners', 5, 'ACTIVE'),
('occupation', 'HOSPITALITY_TOURISM', 'Hospitality & Tourism Workers', 6, 'ACTIVE'),
('occupation', 'FREELANCERS_REMOTE', 'Freelancers / Remote Workers (Digital Economy)', 7, 'ACTIVE'),
('age_group', 'UNDER_13', 'Under 13', 1, 'ACTIVE'),
('age_group', '13_17', '13–17', 2, 'ACTIVE'),
('age_group', '18_24', '18–24', 3, 'ACTIVE'),
('age_group', '25_34', '25–34', 4, 'ACTIVE'),
('age_group', '35_44', '35–44', 5, 'ACTIVE'),
('age_group', '45_54', '45–54', 6, 'ACTIVE'),
('age_group', '55_PLUS', '55+', 7, 'ACTIVE'),
('learning_goal', 'EVERYDAY_CONVERSATION', 'Everyday conversation', 1, 'ACTIVE'),
('learning_goal', 'WORK_CAREER', 'Work and career', 2, 'ACTIVE'),
('learning_goal', 'ACADEMIC_STUDY', 'Academic study', 3, 'ACTIVE'),
('learning_goal', 'TRAVEL', 'Travel', 4, 'ACTIVE'),
('learning_goal', 'EXAM_PREP', 'Exam preparation', 5, 'ACTIVE'),
('learning_goal', 'PERSONAL_GROWTH', 'Personal growth', 6, 'ACTIVE'),
('learning_goal', 'OTHER', 'Other', 99, 'ACTIVE'),
('language_challange', 'PRONUNCIATION', 'Pronunciation', 1, 'ACTIVE'),
('language_challange', 'WORDS_GRAMMAR', 'Finding words or grammar quickly', 2, 'ACTIVE'),
('language_challange', 'CONFIDENCE', 'Feeling nervous or lacking confidence', 3, 'ACTIVE'),
('language_challange', 'ACCENTS_FAST_SPEECH', 'Understanding accents or fast speech', 4, 'ACTIVE'),
('language_challange', 'OTHER', 'Other', 99, 'ACTIVE'),
('language_goal', 'LEARN_TO_SPEAK_ENGLISH', 'Learn to Speak English', 1, 'ACTIVE'),
('language_goal', 'PRACTICE_TO_SPEAK_ENGLISH', 'Practice Speaking English', 2, 'ACTIVE'),
('language_goal', 'SKILL_BASED_COURSES', 'Skill-based Courses', 3, 'ACTIVE'),
-- ('language_goal', 'GENERAL_SKILLS', 'General skills expansion', 4, 'ACTIVE'),
-- ('language_goal', 'OTHER', 'Other', 99, 'ACTIVE'),
('favourite_topic', 'FOOD_COOKING', 'Food & Cooking', 1, 'ACTIVE'),
('favourite_topic', 'HOBBIES_SPORTS_MUSIC', 'Hobbies, Sports, Music', 2, 'ACTIVE'),
('favourite_topic', 'TECH_NEWS_BUSINESS', 'Tech, News, Business', 3, 'ACTIVE'),
('favourite_topic', 'TRAVEL_PLACES_CULTURE', 'Travel, Places, Culture', 4, 'ACTIVE'),
('favourite_topic', 'OTHER', 'Other', 99, 'ACTIVE'),
('country', 'AF', 'Afghanistan', 1, 'ACTIVE'),
('country', 'AL', 'Albania', 2, 'ACTIVE'),
('country', 'DZ', 'Algeria', 3, 'ACTIVE'),
('country', 'AD', 'Andorra', 4, 'ACTIVE'),
('country', 'AO', 'Angola', 5, 'ACTIVE'),
('country', 'AR', 'Argentina', 6, 'ACTIVE'),
('country', 'AM', 'Armenia', 7, 'ACTIVE'),
('country', 'AU', 'Australia', 8, 'ACTIVE'),
('country', 'AT', 'Austria', 9, 'ACTIVE'),
('country', 'AZ', 'Azerbaijan', 10, 'ACTIVE'),
('country', 'BH', 'Bahrain', 11, 'ACTIVE'),
('country', 'BD', 'Bangladesh', 12, 'ACTIVE'),
('country', 'BY', 'Belarus', 13, 'ACTIVE'),
('country', 'BE', 'Belgium', 14, 'ACTIVE'),
('country', 'BZ', 'Belize', 15, 'ACTIVE'),
('country', 'BJ', 'Benin', 16, 'ACTIVE'),
('country', 'BT', 'Bhutan', 17, 'ACTIVE'),
('country', 'BO', 'Bolivia', 18, 'ACTIVE'),
('country', 'BA', 'Bosnia and Herzegovina', 19, 'ACTIVE'),
('country', 'BW', 'Botswana', 20, 'ACTIVE'),
('country', 'BR', 'Brazil', 21, 'ACTIVE'),
('country', 'BN', 'Brunei', 22, 'ACTIVE'),
('country', 'BG', 'Bulgaria', 23, 'ACTIVE'),
('country', 'BF', 'Burkina Faso', 24, 'ACTIVE'),
('country', 'BI', 'Burundi', 25, 'ACTIVE'),
('country', 'KH', 'Cambodia', 26, 'ACTIVE'),
('country', 'CM', 'Cameroon', 27, 'ACTIVE'),
('country', 'CA', 'Canada', 28, 'ACTIVE'),
('country', 'TD', 'Chad', 29, 'ACTIVE'),
('country', 'CL', 'Chile', 30, 'ACTIVE'),
('country', 'CN', 'China', 31, 'ACTIVE'),
('country', 'CO', 'Colombia', 32, 'ACTIVE'),
('country', 'KM', 'Comoros', 33, 'ACTIVE'),
('country', 'CG', 'Congo', 34, 'ACTIVE'),
('country', 'CR', 'Costa Rica', 35, 'ACTIVE'),
('country', 'HR', 'Croatia', 36, 'ACTIVE'),
('country', 'CU', 'Cuba', 37, 'ACTIVE'),
('country', 'CY', 'Cyprus', 38, 'ACTIVE'),
('country', 'CZ', 'Czech Republic', 39, 'ACTIVE'),
('country', 'DK', 'Denmark', 40, 'ACTIVE'),
('country', 'DJ', 'Djibouti', 41, 'ACTIVE'),
('country', 'DO', 'Dominican Republic', 42, 'ACTIVE'),
('country', 'EC', 'Ecuador', 43, 'ACTIVE'),
('country', 'EG', 'Egypt', 44, 'ACTIVE'),
('country', 'SV', 'El Salvador', 45, 'ACTIVE'),
('country', 'ER', 'Eritrea', 46, 'ACTIVE'),
('country', 'EE', 'Estonia', 47, 'ACTIVE'),
('country', 'SZ', 'Eswatini', 48, 'ACTIVE'),
('country', 'ET', 'Ethiopia', 49, 'ACTIVE'),
('country', 'FI', 'Finland', 50, 'ACTIVE'),
('country', 'FR', 'France', 51, 'ACTIVE'),
('country', 'GA', 'Gabon', 52, 'ACTIVE'),
('country', 'GM', 'Gambia', 53, 'ACTIVE'),
('country', 'GE', 'Georgia', 54, 'ACTIVE'),
('country', 'DE', 'Germany', 55, 'ACTIVE'),
('country', 'GH', 'Ghana', 56, 'ACTIVE'),
('country', 'GR', 'Greece', 57, 'ACTIVE'),
('country', 'GT', 'Guatemala', 58, 'ACTIVE'),
('country', 'GN', 'Guinea', 59, 'ACTIVE'),
('country', 'HT', 'Haiti', 60, 'ACTIVE'),
('country', 'HN', 'Honduras', 61, 'ACTIVE'),
('country', 'HU', 'Hungary', 62, 'ACTIVE'),
('country', 'IS', 'Iceland', 63, 'ACTIVE'),
('country', 'IN', 'India', 64, 'ACTIVE'),
('country', 'ID', 'Indonesia', 65, 'ACTIVE'),
('country', 'IR', 'Iran', 66, 'ACTIVE'),
('country', 'IQ', 'Iraq', 67, 'ACTIVE'),
('country', 'IE', 'Ireland', 68, 'ACTIVE'),
('country', 'IL', 'Israel', 69, 'ACTIVE'),
('country', 'IT', 'Italy', 70, 'ACTIVE'),
('country', 'JM', 'Jamaica', 71, 'ACTIVE'),
('country', 'JP', 'Japan', 72, 'ACTIVE'),
('country', 'JO', 'Jordan', 73, 'ACTIVE'),
('country', 'KZ', 'Kazakhstan', 74, 'ACTIVE'),
('country', 'KE', 'Kenya', 75, 'ACTIVE'),
('country', 'KW', 'Kuwait', 76, 'ACTIVE'),
('country', 'KG', 'Kyrgyzstan', 77, 'ACTIVE'),
('country', 'LA', 'Laos', 78, 'ACTIVE'),
('country', 'LV', 'Latvia', 79, 'ACTIVE'),
('country', 'LB', 'Lebanon', 80, 'ACTIVE'),
('country', 'LR', 'Liberia', 81, 'ACTIVE'),
('country', 'LY', 'Libya', 82, 'ACTIVE'),
('country', 'LT', 'Lithuania', 83, 'ACTIVE'),
('country', 'LU', 'Luxembourg', 84, 'ACTIVE'),
('country', 'MG', 'Madagascar', 85, 'ACTIVE'),
('country', 'MW', 'Malawi', 86, 'ACTIVE'),
('country', 'MY', 'Malaysia', 87, 'ACTIVE'),
('country', 'MV', 'Maldives', 88, 'ACTIVE'),
('country', 'ML', 'Mali', 89, 'ACTIVE'),
('country', 'MT', 'Malta', 90, 'ACTIVE'),
('country', 'MX', 'Mexico', 91, 'ACTIVE'),
('country', 'MD', 'Moldova', 92, 'ACTIVE'),
('country', 'MC', 'Monaco', 93, 'ACTIVE'),
('country', 'MN', 'Mongolia', 94, 'ACTIVE'),
('country', 'MA', 'Morocco', 95, 'ACTIVE'),
('country', 'MZ', 'Mozambique', 96, 'ACTIVE'),
('country', 'MM', 'Myanmar', 97, 'ACTIVE'),
('country', 'NA', 'Namibia', 98, 'ACTIVE'),
('country', 'NP', 'Nepal', 99, 'ACTIVE'),
('country', 'NL', 'Netherlands', 100, 'ACTIVE'),
('country', 'NZ', 'New Zealand', 101, 'ACTIVE'),
('country', 'NI', 'Nicaragua', 102, 'ACTIVE'),
('country', 'NE', 'Niger', 103, 'ACTIVE'),
('country', 'NG', 'Nigeria', 104, 'ACTIVE'),
('country', 'KP', 'North Korea', 105, 'ACTIVE'),
('country', 'NO', 'Norway', 106, 'ACTIVE'),
('country', 'OM', 'Oman', 107, 'ACTIVE'),
('country', 'PK', 'Pakistan', 108, 'ACTIVE'),
('country', 'PA', 'Panama', 109, 'ACTIVE'),
('country', 'PY', 'Paraguay', 110, 'ACTIVE'),
('country', 'PE', 'Peru', 111, 'ACTIVE'),
('country', 'PH', 'Philippines', 112, 'ACTIVE'),
('country', 'PL', 'Poland', 113, 'ACTIVE'),
('country', 'PT', 'Portugal', 114, 'ACTIVE'),
('country', 'QA', 'Qatar', 115, 'ACTIVE'),
('country', 'RO', 'Romania', 116, 'ACTIVE'),
('country', 'RU', 'Russia', 117, 'ACTIVE'),
('country', 'RW', 'Rwanda', 118, 'ACTIVE'),
('country', 'SA', 'Saudi Arabia', 119, 'ACTIVE'),
('country', 'SN', 'Senegal', 120, 'ACTIVE'),
('country', 'RS', 'Serbia', 121, 'ACTIVE'),
('country', 'SG', 'Singapore', 122, 'ACTIVE'),
('country', 'SK', 'Slovakia', 123, 'ACTIVE'),
('country', 'SI', 'Slovenia', 124, 'ACTIVE'),
('country', 'SO', 'Somalia', 125, 'ACTIVE'),
('country', 'ZA', 'South Africa', 126, 'ACTIVE'),
('country', 'KR', 'South Korea', 127, 'ACTIVE'),
('country', 'ES', 'Spain', 128, 'ACTIVE'),
('country', 'LK', 'Sri Lanka', 129, 'ACTIVE'),
('country', 'SD', 'Sudan', 130, 'ACTIVE'),
('country', 'SE', 'Sweden', 131, 'ACTIVE'),
('country', 'CH', 'Switzerland', 132, 'ACTIVE'),
('country', 'SY', 'Syria', 133, 'ACTIVE'),
('country', 'TW', 'Taiwan', 134, 'ACTIVE'),
('country', 'TJ', 'Tajikistan', 135, 'ACTIVE'),
('country', 'TZ', 'Tanzania', 136, 'ACTIVE'),
('country', 'TH', 'Thailand', 137, 'ACTIVE'),
('country', 'TN', 'Tunisia', 138, 'ACTIVE'),
('country', 'TR', 'Turkey', 139, 'ACTIVE'),
('country', 'UG', 'Uganda', 140, 'ACTIVE'),
('country', 'UA', 'Ukraine', 141, 'ACTIVE'),
('country', 'AE', 'United Arab Emirates', 142, 'ACTIVE'),
('country', 'GB', 'United Kingdom', 143, 'ACTIVE'),
('country', 'US', 'United States', 144, 'ACTIVE'),
('country', 'UY', 'Uruguay', 145, 'ACTIVE'),
('country', 'UZ', 'Uzbekistan', 146, 'ACTIVE'),
('country', 'VE', 'Venezuela', 147, 'ACTIVE'),
('country', 'VN', 'Vietnam', 148, 'ACTIVE'),
('country', 'YE', 'Yemen', 149, 'ACTIVE'),
('country', 'ZM', 'Zambia', 150, 'ACTIVE'),
('country', 'ZW', 'Zimbabwe', 151, 'ACTIVE'),
('ethiopia_regions', 'ADDIS_ABABA', 'Addis Ababa', 1, 'ACTIVE'),
('ethiopia_regions', 'AFAR', 'Afar', 2, 'ACTIVE'),
('ethiopia_regions', 'AMHARA', 'Amhara', 3, 'ACTIVE'),
('ethiopia_regions', 'BENISHANGUL_GUMUZ', 'Benishangul-Gumuz', 4, 'ACTIVE'),
('ethiopia_regions', 'CENTRAL_ETHIOPIA', 'Central Ethiopia', 5, 'ACTIVE'),
('ethiopia_regions', 'DIRE_DAWA', 'Dire Dawa', 6, 'ACTIVE'),
('ethiopia_regions', 'GAMBELA', 'Gambela', 7, 'ACTIVE'),
('ethiopia_regions', 'HARARI', 'Harari', 8, 'ACTIVE'),
('ethiopia_regions', 'OROMIA', 'Oromia', 9, 'ACTIVE'),
('ethiopia_regions', 'SIDAMA', 'Sidama', 10, 'ACTIVE'),
('ethiopia_regions', 'SOMALI', 'Somali', 11, 'ACTIVE'),
('ethiopia_regions', 'SOUTH_ETHIOPIA', 'South Ethiopia', 12, 'ACTIVE'),
('ethiopia_regions', 'SOUTH_WEST_ETHIOPIA_PEOPLES', 'South West Ethiopia Peoples', 13, 'ACTIVE'),
('ethiopia_regions', 'TIGRAY', 'Tigray', 14, 'ACTIVE');
-- <<< END SOURCE: 000069_profile_field_options.up.sql
-- >>> BEGIN SOURCE: 000070_rename_profile_field_options_to_field_options.up.sql
-- For databases that already applied 000069 with profile_field_options table name.
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'profile_field_options'
) AND NOT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = 'field_options'
) THEN
ALTER TABLE profile_field_options RENAME TO field_options;
ALTER TABLE field_options RENAME CONSTRAINT profile_field_options_field_key_check TO field_options_field_key_check_old;
ALTER TABLE field_options DROP CONSTRAINT IF EXISTS field_options_field_key_check_old;
ALTER TABLE field_options RENAME CONSTRAINT profile_field_options_unique_field_code TO field_options_unique_field_code;
ALTER INDEX IF EXISTS idx_profile_field_options_field_key RENAME TO idx_field_options_field_key;
ALTER INDEX IF EXISTS idx_profile_field_options_status RENAME TO idx_field_options_status;
ALTER INDEX IF EXISTS idx_profile_field_options_display_order RENAME TO idx_field_options_display_order;
ALTER TABLE field_options ADD CONSTRAINT field_options_field_key_format CHECK (field_key ~ '^[a-z][a-z0-9_]*$');
END IF;
END $$;
-- <<< END SOURCE: 000070_rename_profile_field_options_to_field_options.up.sql
-- >>> BEGIN SOURCE: 000070_subscription_content_categories.up.sql
ALTER TABLE subscription_plans
ADD COLUMN category VARCHAR(32) NOT NULL DEFAULT 'LEARN_ENGLISH',
ADD CONSTRAINT chk_subscription_plans_category
CHECK (category IN ('LEARN_ENGLISH', 'IELTS', 'DUOLINGO'));
ALTER TABLE programs
ADD COLUMN category VARCHAR(32) NOT NULL DEFAULT 'LEARN_ENGLISH',
ADD CONSTRAINT chk_programs_category
CHECK (category IN ('LEARN_ENGLISH', 'IELTS', 'DUOLINGO'));
ALTER TABLE exam_prep.catalog_courses
ADD COLUMN category VARCHAR(32);
UPDATE exam_prep.catalog_courses
SET category = CASE
WHEN upper(name) LIKE '%DUOLINGO%' OR upper(name) LIKE '%DET%' THEN 'DUOLINGO'
WHEN upper(name) LIKE '%IELTS%' THEN 'IELTS'
ELSE 'IELTS'
END
WHERE category IS NULL;
ALTER TABLE exam_prep.catalog_courses
ALTER COLUMN category SET NOT NULL,
ALTER COLUMN category SET DEFAULT 'IELTS',
ADD CONSTRAINT chk_exam_prep_catalog_courses_category
CHECK (category IN ('IELTS', 'DUOLINGO'));
CREATE INDEX idx_subscription_plans_category ON subscription_plans(category);
CREATE INDEX idx_programs_category ON programs(category);
CREATE INDEX idx_exam_prep_catalog_courses_category ON exam_prep.catalog_courses(category);
-- <<< END SOURCE: 000070_subscription_content_categories.up.sql
-- >>> BEGIN SOURCE: 000071_seed_country_field_options.up.sql
INSERT INTO field_options (field_key, code, label, display_order, status) VALUES
('country', 'ET', 'Ethiopia', 1, 'ACTIVE'),
('country', 'ER', 'Eritrea', 2, 'ACTIVE'),
('country', 'DJ', 'Djibouti', 3, 'ACTIVE'),
('country', 'SO', 'Somalia', 4, 'ACTIVE'),
('country', 'KE', 'Kenya', 5, 'ACTIVE'),
('country', 'SD', 'Sudan', 6, 'ACTIVE'),
('country', 'SS', 'South Sudan', 7, 'ACTIVE'),
('country', 'UG', 'Uganda', 8, 'ACTIVE'),
('country', 'RW', 'Rwanda', 9, 'ACTIVE'),
('country', 'TZ', 'Tanzania', 10, 'ACTIVE'),
('country', 'EG', 'Egypt', 11, 'ACTIVE'),
('country', 'NG', 'Nigeria', 12, 'ACTIVE'),
('country', 'ZA', 'South Africa', 13, 'ACTIVE'),
('country', 'US', 'United States', 20, 'ACTIVE'),
('country', 'GB', 'United Kingdom', 21, 'ACTIVE'),
('country', 'CA', 'Canada', 22, 'ACTIVE'),
('country', 'DE', 'Germany', 23, 'ACTIVE'),
('country', 'FR', 'France', 24, 'ACTIVE'),
('country', 'IN', 'India', 25, 'ACTIVE'),
('country', 'CN', 'China', 26, 'ACTIVE'),
('country', 'SA', 'Saudi Arabia', 27, 'ACTIVE'),
('country', 'AE', 'United Arab Emirates', 28, 'ACTIVE'),
('country', 'OTHER', 'Other', 99, 'ACTIVE')
ON CONFLICT (field_key, code) DO NOTHING;
-- <<< END SOURCE: 000071_seed_country_field_options.up.sql
-- >>> BEGIN SOURCE: 000072_seed_ethiopia_regions_field_options.up.sql
INSERT INTO field_options (field_key, code, label, display_order, status) VALUES
('ethiopia_regions', 'ADDIS_ABABA', 'Addis Ababa', 1, 'ACTIVE'),
('ethiopia_regions', 'AFAR', 'Afar', 2, 'ACTIVE'),
('ethiopia_regions', 'AMHARA', 'Amhara', 3, 'ACTIVE'),
('ethiopia_regions', 'BENISHANGUL_GUMUZ', 'Benishangul-Gumuz', 4, 'ACTIVE'),
('ethiopia_regions', 'CENTRAL_ETHIOPIA', 'Central Ethiopia', 5, 'ACTIVE'),
('ethiopia_regions', 'DIRE_DAWA', 'Dire Dawa', 6, 'ACTIVE'),
('ethiopia_regions', 'GAMBELA', 'Gambela', 7, 'ACTIVE'),
('ethiopia_regions', 'HARARI', 'Harari', 8, 'ACTIVE'),
('ethiopia_regions', 'OROMIA', 'Oromia', 9, 'ACTIVE'),
('ethiopia_regions', 'SIDAMA', 'Sidama', 10, 'ACTIVE'),
('ethiopia_regions', 'SOMALI', 'Somali', 11, 'ACTIVE'),
('ethiopia_regions', 'SOUTH_ETHIOPIA', 'South Ethiopia', 12, 'ACTIVE'),
('ethiopia_regions', 'SOUTH_WEST_ETHIOPIA_PEOPLES', 'South West Ethiopia Peoples', 13, 'ACTIVE'),
('ethiopia_regions', 'TIGRAY', 'Tigray', 14, 'ACTIVE')
ON CONFLICT (field_key, code) DO UPDATE SET
label = EXCLUDED.label,
display_order = EXCLUDED.display_order,
status = EXCLUDED.status;
-- <<< END SOURCE: 000072_seed_ethiopia_regions_field_options.up.sql
-- >>> BEGIN SOURCE: 000073_user_video_watch_sessions.up.sql
CREATE TABLE user_video_watch_sessions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
content_kind VARCHAR(32) NOT NULL CHECK (content_kind IN ('lms_lesson', 'exam_prep_lesson')),
content_id BIGINT NOT NULL,
session_number INT NOT NULL CHECK (session_number > 0),
video_duration_sec INT,
max_position_sec INT NOT NULL DEFAULT 0 CHECK (max_position_sec >= 0),
started_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_heartbeat_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
ended_at TIMESTAMPTZ,
completed_at TIMESTAMPTZ,
UNIQUE (user_id, content_kind, content_id, session_number)
);
CREATE INDEX idx_user_video_watch_sessions_user ON user_video_watch_sessions (user_id);
CREATE INDEX idx_user_video_watch_sessions_content ON user_video_watch_sessions (content_kind, content_id);
CREATE INDEX idx_user_video_watch_sessions_started_at ON user_video_watch_sessions (started_at);
-- <<< END SOURCE: 000073_user_video_watch_sessions.up.sql
-- >>> BEGIN SOURCE: 000074_mobile_app_versions.up.sql
CREATE TABLE IF NOT EXISTS mobile_app_versions (
id BIGSERIAL PRIMARY KEY,
platform VARCHAR(20) NOT NULL CHECK (platform IN ('ANDROID', 'IOS')),
version_name VARCHAR(50) NOT NULL,
version_code INT NOT NULL CHECK (version_code > 0),
update_type VARCHAR(20) NOT NULL DEFAULT 'OPTIONAL' CHECK (update_type IN ('FORCE', 'OPTIONAL')),
release_notes TEXT,
store_url TEXT,
min_supported_version_code INT CHECK (min_supported_version_code IS NULL OR min_supported_version_code > 0),
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'INACTIVE')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ,
CONSTRAINT mobile_app_versions_platform_version_code UNIQUE (platform, version_code),
CONSTRAINT mobile_app_versions_platform_version_name UNIQUE (platform, version_name)
);
CREATE INDEX IF NOT EXISTS idx_mobile_app_versions_platform ON mobile_app_versions (platform);
CREATE INDEX IF NOT EXISTS idx_mobile_app_versions_status ON mobile_app_versions (status);
CREATE INDEX IF NOT EXISTS idx_mobile_app_versions_platform_code ON mobile_app_versions (platform, version_code DESC);
-- <<< END SOURCE: 000074_mobile_app_versions.up.sql
-- >>> BEGIN SOURCE: 000075_publish_question_sets_default.up.sql
-- Publish existing non-archived question sets and default future ones to PUBLISHED.
UPDATE question_sets
SET status = 'PUBLISHED',
updated_at = CURRENT_TIMESTAMP
WHERE status IN ('DRAFT', 'INACTIVE');
ALTER TABLE question_sets
ALTER COLUMN status SET DEFAULT 'PUBLISHED';
-- <<< END SOURCE: 000075_publish_question_sets_default.up.sql
-- >>> BEGIN SOURCE: 000076_apple_sign_in.up.sql
ALTER TABLE users
ADD COLUMN IF NOT EXISTS apple_id VARCHAR(255),
ADD COLUMN IF NOT EXISTS apple_email_verified BOOLEAN DEFAULT FALSE;
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_apple_id
ON users (apple_id)
WHERE apple_id IS NOT NULL;
-- <<< END SOURCE: 000076_apple_sign_in.up.sql
-- >>> BEGIN SOURCE: 000077_lms_one_practice_per_parent.up.sql
-- Learn English: at most one lms_practice per course, module, or lesson parent.
-- Remove duplicate rows (keep the earliest practice per parent) before adding constraints.
DELETE FROM lms_practices a
USING lms_practices b
WHERE a.course_id IS NOT NULL
AND a.course_id = b.course_id
AND a.id > b.id;
DELETE FROM lms_practices a
USING lms_practices b
WHERE a.module_id IS NOT NULL
AND a.module_id = b.module_id
AND a.id > b.id;
DELETE FROM lms_practices a
USING lms_practices b
WHERE a.lesson_id IS NOT NULL
AND a.lesson_id = b.lesson_id
AND a.id > b.id;
CREATE UNIQUE INDEX idx_lms_practices_one_per_course
ON lms_practices (course_id)
WHERE course_id IS NOT NULL;
CREATE UNIQUE INDEX idx_lms_practices_one_per_module
ON lms_practices (module_id)
WHERE module_id IS NOT NULL;
CREATE UNIQUE INDEX idx_lms_practices_one_per_lesson
ON lms_practices (lesson_id)
WHERE lesson_id IS NOT NULL;
-- <<< END SOURCE: 000077_lms_one_practice_per_parent.up.sql
-- >>> BEGIN SOURCE: 000078_hierarchy_publish_status.up.sql
-- Draft vs published visibility for the remaining LMS and exam-prep hierarchy levels
-- (mirrors lessons.publish_status from 000062 and practice publish_status from 000060).
-- Existing rows stay PUBLISHED; new inserts default to DRAFT unless the API sends PUBLISHED.
-- LMS hierarchy
ALTER TABLE programs
ADD COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'PUBLISHED'
CONSTRAINT chk_programs_publish_status CHECK (publish_status IN ('DRAFT', 'PUBLISHED'));
ALTER TABLE programs
ALTER COLUMN publish_status SET DEFAULT 'DRAFT';
ALTER TABLE courses
ADD COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'PUBLISHED'
CONSTRAINT chk_courses_publish_status CHECK (publish_status IN ('DRAFT', 'PUBLISHED'));
ALTER TABLE courses
ALTER COLUMN publish_status SET DEFAULT 'DRAFT';
ALTER TABLE modules
ADD COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'PUBLISHED'
CONSTRAINT chk_modules_publish_status CHECK (publish_status IN ('DRAFT', 'PUBLISHED'));
ALTER TABLE modules
ALTER COLUMN publish_status SET DEFAULT 'DRAFT';
-- Exam-prep hierarchy
ALTER TABLE exam_prep.catalog_courses
ADD COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'PUBLISHED'
CONSTRAINT chk_exam_prep_catalog_courses_publish_status CHECK (publish_status IN ('DRAFT', 'PUBLISHED'));
ALTER TABLE exam_prep.catalog_courses
ALTER COLUMN publish_status SET DEFAULT 'DRAFT';
ALTER TABLE exam_prep.units
ADD COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'PUBLISHED'
CONSTRAINT chk_exam_prep_units_publish_status CHECK (publish_status IN ('DRAFT', 'PUBLISHED'));
ALTER TABLE exam_prep.units
ALTER COLUMN publish_status SET DEFAULT 'DRAFT';
ALTER TABLE exam_prep.unit_modules
ADD COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'PUBLISHED'
CONSTRAINT chk_exam_prep_unit_modules_publish_status CHECK (publish_status IN ('DRAFT', 'PUBLISHED'));
ALTER TABLE exam_prep.unit_modules
ALTER COLUMN publish_status SET DEFAULT 'DRAFT';
ALTER TABLE exam_prep.unit_module_lessons
ADD COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'PUBLISHED'
CONSTRAINT chk_exam_prep_unit_module_lessons_publish_status CHECK (publish_status IN ('DRAFT', 'PUBLISHED'));
ALTER TABLE exam_prep.unit_module_lessons
ALTER COLUMN publish_status SET DEFAULT 'DRAFT';
-- <<< END SOURCE: 000078_hierarchy_publish_status.up.sql
-- >>> BEGIN SOURCE: 000079_duolingo_lifetime_subscriptions.up.sql
-- DUOLINGO subscriptions are one-time purchases with no real expiry.
UPDATE user_subscriptions us
SET
expires_at = TIMESTAMPTZ '9999-12-31 23:59:59+00',
updated_at = CURRENT_TIMESTAMP
FROM subscription_plans sp
WHERE us.plan_id = sp.id
AND sp.category = 'DUOLINGO'
AND us.expires_at < TIMESTAMPTZ '9999-01-01 00:00:00+00';
-- <<< END SOURCE: 000079_duolingo_lifetime_subscriptions.up.sql
-- >>> BEGIN SOURCE: 000080_lms_programs_learn_english_only.up.sql
-- LMS programs are Learn English content only; exam prep uses exam_prep.catalog_courses.
UPDATE programs
SET
category = 'LEARN_ENGLISH',
updated_at = CURRENT_TIMESTAMP
WHERE category <> 'LEARN_ENGLISH';
ALTER TABLE programs
DROP CONSTRAINT IF EXISTS chk_programs_category;
ALTER TABLE programs
ADD CONSTRAINT chk_programs_category
CHECK (category = 'LEARN_ENGLISH');
-- <<< END SOURCE: 000080_lms_programs_learn_english_only.up.sql
-- >>> BEGIN SOURCE: 000081_content_access_tier.up.sql
-- FREE content is accessible without a subscription; PREMIUM requires one.
-- Effective tier cascades at read time: any PREMIUM ancestor makes descendants PREMIUM.
ALTER TABLE programs
ADD COLUMN access_tier VARCHAR(16) NOT NULL DEFAULT 'PREMIUM'
CONSTRAINT chk_programs_access_tier CHECK (access_tier IN ('FREE', 'PREMIUM'));
ALTER TABLE courses
ADD COLUMN access_tier VARCHAR(16) NOT NULL DEFAULT 'PREMIUM'
CONSTRAINT chk_courses_access_tier CHECK (access_tier IN ('FREE', 'PREMIUM'));
ALTER TABLE modules
ADD COLUMN access_tier VARCHAR(16) NOT NULL DEFAULT 'PREMIUM'
CONSTRAINT chk_modules_access_tier CHECK (access_tier IN ('FREE', 'PREMIUM'));
ALTER TABLE lessons
ADD COLUMN access_tier VARCHAR(16) NOT NULL DEFAULT 'PREMIUM'
CONSTRAINT chk_lessons_access_tier CHECK (access_tier IN ('FREE', 'PREMIUM'));
ALTER TABLE exam_prep.catalog_courses
ADD COLUMN access_tier VARCHAR(16) NOT NULL DEFAULT 'PREMIUM'
CONSTRAINT chk_exam_prep_catalog_courses_access_tier CHECK (access_tier IN ('FREE', 'PREMIUM'));
ALTER TABLE exam_prep.units
ADD COLUMN access_tier VARCHAR(16) NOT NULL DEFAULT 'PREMIUM'
CONSTRAINT chk_exam_prep_units_access_tier CHECK (access_tier IN ('FREE', 'PREMIUM'));
ALTER TABLE exam_prep.unit_modules
ADD COLUMN access_tier VARCHAR(16) NOT NULL DEFAULT 'PREMIUM'
CONSTRAINT chk_exam_prep_unit_modules_access_tier CHECK (access_tier IN ('FREE', 'PREMIUM'));
ALTER TABLE exam_prep.unit_module_lessons
ADD COLUMN access_tier VARCHAR(16) NOT NULL DEFAULT 'PREMIUM'
CONSTRAINT chk_exam_prep_unit_module_lessons_access_tier CHECK (access_tier IN ('FREE', 'PREMIUM'));
-- <<< END SOURCE: 000081_content_access_tier.up.sql
-- >>> BEGIN SOURCE: 000082_fixup_legacy_audio_question_type_definition.up.sql
-- Legacy AUDIO questions (voice_prompt / sample_answer fields, no dynamic_payload) were linked to
-- unrelated dynamic definitions (e.g. ielts_speaking_cue_card_part1). Ensure the canonical
-- audio_conversation_type definition exists and relink affected rows.
INSERT INTO question_type_definitions (
key,
display_name,
description,
stimulus_component_kinds,
response_component_kinds,
stimulus_schema,
response_schema,
is_system,
status
)
VALUES (
'audio_conversation_type',
'Audio Conversation',
'Listen to a voice prompt and respond with a spoken answer. Maps to legacy AUDIO questions (voice_prompt, sample_answer_voice_prompt, audio_correct_answer_text).',
ARRAY['QUESTION_TEXT', 'AUDIO_PROMPT']::TEXT[],
ARRAY['AUDIO_RESPONSE']::TEXT[],
'[
{"id": "question_text_1", "kind": "QUESTION_TEXT", "label": "Question text", "required": false},
{"id": "voice_prompt_1", "kind": "AUDIO_PROMPT", "label": "Voice prompt", "required": true},
{"id": "sample_answer_voice_prompt_1", "kind": "AUDIO_PROMPT", "label": "Sample answer voice prompt", "required": false}
]'::jsonb,
'[
{"id": "audio_response_1", "kind": "AUDIO_RESPONSE", "label": "Learner audio response", "required": true}
]'::jsonb,
TRUE,
'ACTIVE'
)
ON CONFLICT (key) DO NOTHING;
UPDATE questions q
SET
question_type_definition_id = audio_def.id,
updated_at = CURRENT_TIMESTAMP
FROM question_type_definitions audio_def
WHERE audio_def.key = 'audio_conversation_type'
AND q.question_type = 'AUDIO'
AND q.dynamic_payload IS NULL
AND (
q.question_type_definition_id IS NULL
OR q.question_type_definition_id IS DISTINCT FROM audio_def.id
);
-- <<< END SOURCE: 000082_fixup_legacy_audio_question_type_definition.up.sql
-- >>> BEGIN SOURCE: 000083_scheduled_in_app_notifications.up.sql
-- Allow in_app as a scheduled notification channel.
ALTER TABLE scheduled_notifications
DROP CONSTRAINT IF EXISTS scheduled_notifications_channel_check;
ALTER TABLE scheduled_notifications
ADD CONSTRAINT scheduled_notifications_channel_check
CHECK (channel IN ('email', 'sms', 'push', 'in_app'));
-- <<< END SOURCE: 000083_scheduled_in_app_notifications.up.sql
-- >>> BEGIN SOURCE: 000084_faq_rbac_permissions.up.sql
-- Ensure FAQ admin permissions exist and are assigned to staff roles that manage content.
INSERT INTO permissions (key, name, description, group_name) VALUES
('faqs.create', 'Create FAQ', 'Create a FAQ item', 'FAQs'),
('faqs.list', 'List FAQs (Admin)', 'List FAQs for admin management', 'FAQs'),
('faqs.get', 'Get FAQ (Admin)', 'Get FAQ by ID for admin management', 'FAQs'),
('faqs.update', 'Update FAQ', 'Update a FAQ item', 'FAQs'),
('faqs.delete', 'Delete FAQ', 'Delete a FAQ item', 'FAQs')
ON CONFLICT (key) DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
group_name = EXCLUDED.group_name;
INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
CROSS JOIN permissions p
WHERE r.name IN ('ADMIN', 'INSTRUCTOR')
AND p.key IN ('faqs.create', 'faqs.list', 'faqs.get', 'faqs.update', 'faqs.delete')
ON CONFLICT DO NOTHING;
-- <<< END SOURCE: 000084_faq_rbac_permissions.up.sql
-- >>> BEGIN SOURCE: 000085_team_profile_update_mine.up.sql
INSERT INTO permissions (key, name, description, group_name) VALUES
('team.profile.update_mine', 'Update My Team Profile', 'Update own team profile', 'Team')
ON CONFLICT (key) DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
group_name = EXCLUDED.group_name;
INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
CROSS JOIN permissions p
WHERE r.name IN ('ADMIN', 'INSTRUCTOR', 'SUPPORT')
AND p.key IN ('team.profile.get_mine', 'team.profile.update_mine', 'team.members.change_password')
ON CONFLICT DO NOTHING;
-- <<< END SOURCE: 000085_team_profile_update_mine.up.sql
-- >>> BEGIN SOURCE: 000086_subscriptions_get_by_user.up.sql
INSERT INTO permissions (key, name, description, group_name) VALUES
('subscriptions.get_by_user', 'Get User Subscriptions (Admin)', 'Get full subscription details for a user', 'Subscriptions')
ON CONFLICT (key) DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
group_name = EXCLUDED.group_name;
INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
CROSS JOIN permissions p
WHERE r.name = 'ADMIN'
AND p.key = 'subscriptions.get_by_user'
ON CONFLICT DO NOTHING;
-- <<< END SOURCE: 000086_subscriptions_get_by_user.up.sql
-- >>> BEGIN SOURCE: 000087_scheduled_email_templates.up.sql
ALTER TABLE scheduled_notifications
ADD COLUMN IF NOT EXISTS email_template_slug VARCHAR(100),
ADD COLUMN IF NOT EXISTS email_template_variables JSONB;
-- <<< END SOURCE: 000087_scheduled_email_templates.up.sql
-- >>> BEGIN SOURCE: 000088_question_set_item_associations.up.sql
ALTER TABLE question_set_items
ADD COLUMN associated_question_id BIGINT REFERENCES questions(id) ON DELETE SET NULL;
CREATE INDEX idx_question_set_items_associated_question_id
ON question_set_items(associated_question_id);
-- <<< END SOURCE: 000088_question_set_item_associations.up.sql
-- >>> BEGIN SOURCE: 000089_lms_practice_parents.up.sql
-- Practices can be linked to multiple courses, modules, and/or lessons via lms_practice_parents.
CREATE TABLE lms_practice_parents (
id BIGSERIAL PRIMARY KEY,
practice_id BIGINT NOT NULL REFERENCES lms_practices (id) ON DELETE CASCADE,
parent_kind VARCHAR(30) NOT NULL CHECK (parent_kind IN ('COURSE', 'MODULE', 'LESSON')),
parent_id BIGINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (practice_id, parent_kind, parent_id),
UNIQUE (parent_kind, parent_id)
);
INSERT INTO lms_practice_parents (practice_id, parent_kind, parent_id)
SELECT id, 'COURSE', course_id
FROM lms_practices
WHERE course_id IS NOT NULL;
INSERT INTO lms_practice_parents (practice_id, parent_kind, parent_id)
SELECT id, 'MODULE', module_id
FROM lms_practices
WHERE module_id IS NOT NULL;
INSERT INTO lms_practice_parents (practice_id, parent_kind, parent_id)
SELECT id, 'LESSON', lesson_id
FROM lms_practices
WHERE lesson_id IS NOT NULL;
DROP INDEX IF EXISTS idx_lms_practices_one_per_course;
DROP INDEX IF EXISTS idx_lms_practices_one_per_module;
DROP INDEX IF EXISTS idx_lms_practices_one_per_lesson;
DROP INDEX IF EXISTS idx_lms_practices_course_id;
DROP INDEX IF EXISTS idx_lms_practices_module_id;
DROP INDEX IF EXISTS idx_lms_practices_lesson_id;
DROP INDEX IF EXISTS idx_lms_practices_course_created;
DROP INDEX IF EXISTS idx_lms_practices_module_created;
DROP INDEX IF EXISTS idx_lms_practices_lesson_created;
ALTER TABLE lms_practices
DROP CONSTRAINT lms_practices_one_parent;
ALTER TABLE lms_practices
DROP COLUMN course_id,
DROP COLUMN module_id,
DROP COLUMN lesson_id;
CREATE INDEX idx_lms_practice_parents_practice_id ON lms_practice_parents (practice_id);
CREATE INDEX idx_lms_practice_parents_lookup ON lms_practice_parents (parent_kind, parent_id);
-- <<< END SOURCE: 000089_lms_practice_parents.up.sql
-- >>> BEGIN SOURCE: 000090_question_type_definition_groups.up.sql
CREATE TABLE IF NOT EXISTS question_type_definition_groups (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(120) NOT NULL,
description TEXT,
display_order INT NOT NULL DEFAULT 0,
status VARCHAR(20) NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE', 'INACTIVE')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_question_type_definition_groups_status
ON question_type_definition_groups(status);
ALTER TABLE question_type_definitions
ADD COLUMN IF NOT EXISTS group_id BIGINT NULL
REFERENCES question_type_definition_groups(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_question_type_definitions_group_id
ON question_type_definitions(group_id);
-- <<< END SOURCE: 000090_question_type_definition_groups.up.sql
-- >>> BEGIN SOURCE: 000091_question_type_definition_group_members.up.sql
CREATE TABLE IF NOT EXISTS question_type_definition_group_members (
definition_id BIGINT NOT NULL
REFERENCES question_type_definitions(id) ON DELETE CASCADE,
group_id BIGINT NOT NULL
REFERENCES question_type_definition_groups(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (definition_id, group_id)
);
CREATE INDEX IF NOT EXISTS idx_question_type_definition_group_members_group_id
ON question_type_definition_group_members(group_id);
INSERT INTO question_type_definition_group_members (definition_id, group_id)
SELECT id, group_id
FROM question_type_definitions
WHERE group_id IS NOT NULL
ON CONFLICT DO NOTHING;
DROP INDEX IF EXISTS idx_question_type_definitions_group_id;
ALTER TABLE question_type_definitions
DROP COLUMN IF EXISTS group_id;
-- <<< END SOURCE: 000091_question_type_definition_group_members.up.sql
-- >>> BEGIN SOURCE: 000092_users_email_phone_unique.up.sql
-- Normalize empty contact fields before enforcing uniqueness.
UPDATE users SET email = NULL WHERE email IS NOT NULL AND TRIM(email) = '';
UPDATE users SET phone_number = NULL WHERE phone_number IS NOT NULL AND TRIM(phone_number) = '';
UPDATE users SET email = LOWER(TRIM(email)) WHERE email IS NOT NULL;
-- Resolve duplicate emails: keep the best account per address, clear or archive the rest.
WITH email_ranked AS (
SELECT
id,
ROW_NUMBER() OVER (
PARTITION BY LOWER(TRIM(email))
ORDER BY
CASE status
WHEN 'ACTIVE' THEN 0
WHEN 'PENDING' THEN 1
WHEN 'SUSPENDED' THEN 2
ELSE 3
END,
(google_id IS NOT NULL OR apple_id IS NOT NULL) DESC,
profile_completion_percentage DESC,
COALESCE(last_login, created_at) DESC,
id ASC
) AS rn
FROM users
WHERE email IS NOT NULL AND TRIM(email) <> ''
)
UPDATE users u
SET
email = NULL,
updated_at = CURRENT_TIMESTAMP
FROM email_ranked r
WHERE u.id = r.id
AND r.rn > 1
AND u.phone_number IS NOT NULL
AND TRIM(u.phone_number) <> '';
WITH email_ranked AS (
SELECT
id,
ROW_NUMBER() OVER (
PARTITION BY LOWER(TRIM(email))
ORDER BY
CASE status
WHEN 'ACTIVE' THEN 0
WHEN 'PENDING' THEN 1
WHEN 'SUSPENDED' THEN 2
ELSE 3
END,
(google_id IS NOT NULL OR apple_id IS NOT NULL) DESC,
profile_completion_percentage DESC,
COALESCE(last_login, created_at) DESC,
id ASC
) AS rn
FROM users
WHERE email IS NOT NULL AND TRIM(email) <> ''
)
UPDATE users u
SET
email = 'dedup-' || u.id || '@invalid.rezina.local',
status = CASE WHEN u.status = 'ACTIVE' THEN 'DEACTIVATED' ELSE u.status END,
updated_at = CURRENT_TIMESTAMP
FROM email_ranked r
WHERE u.id = r.id
AND r.rn > 1
AND u.email IS NOT NULL;
-- Resolve duplicate phone numbers: keep the best account per number, clear or archive the rest.
WITH phone_ranked AS (
SELECT
id,
ROW_NUMBER() OVER (
PARTITION BY TRIM(phone_number)
ORDER BY
CASE status
WHEN 'ACTIVE' THEN 0
WHEN 'PENDING' THEN 1
WHEN 'SUSPENDED' THEN 2
ELSE 3
END,
(google_id IS NOT NULL OR apple_id IS NOT NULL) DESC,
profile_completion_percentage DESC,
COALESCE(last_login, created_at) DESC,
id ASC
) AS rn
FROM users
WHERE phone_number IS NOT NULL AND TRIM(phone_number) <> ''
)
UPDATE users u
SET
phone_number = NULL,
updated_at = CURRENT_TIMESTAMP
FROM phone_ranked r
WHERE u.id = r.id
AND r.rn > 1
AND u.email IS NOT NULL
AND TRIM(u.email) <> '';
WITH phone_ranked AS (
SELECT
id,
ROW_NUMBER() OVER (
PARTITION BY TRIM(phone_number)
ORDER BY
CASE status
WHEN 'ACTIVE' THEN 0
WHEN 'PENDING' THEN 1
WHEN 'SUSPENDED' THEN 2
ELSE 3
END,
(google_id IS NOT NULL OR apple_id IS NOT NULL) DESC,
profile_completion_percentage DESC,
COALESCE(last_login, created_at) DESC,
id ASC
) AS rn
FROM users
WHERE phone_number IS NOT NULL AND TRIM(phone_number) <> ''
)
UPDATE users u
SET
phone_number = NULL,
email = COALESCE(
NULLIF(TRIM(u.email), ''),
'dedup-' || u.id || '@invalid.rezina.local'
),
status = CASE WHEN u.status = 'ACTIVE' THEN 'DEACTIVATED' ELSE u.status END,
updated_at = CURRENT_TIMESTAMP
FROM phone_ranked r
WHERE u.id = r.id
AND r.rn > 1
AND u.phone_number IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email_lower_unique
ON users (LOWER(email))
WHERE email IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_phone_unique
ON users (phone_number)
WHERE phone_number IS NOT NULL;
-- <<< END SOURCE: 000092_users_email_phone_unique.up.sql
-- >>> BEGIN SOURCE: 000093_exam_prep_practice_parents.up.sql
-- Exam-prep practices can attach to catalog courses, units, or lessons (one parent per practice).
CREATE TABLE exam_prep.practice_parents (
id BIGSERIAL PRIMARY KEY,
practice_id BIGINT NOT NULL REFERENCES exam_prep.lesson_practices (id) ON DELETE CASCADE,
parent_kind VARCHAR(30) NOT NULL CHECK (parent_kind IN ('CATALOG_COURSE', 'UNIT', 'LESSON')),
parent_id BIGINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (practice_id, parent_kind, parent_id),
UNIQUE (parent_kind, parent_id)
);
INSERT INTO exam_prep.practice_parents (practice_id, parent_kind, parent_id)
SELECT
id,
'LESSON',
unit_module_lesson_id
FROM exam_prep.lesson_practices;
DROP INDEX IF EXISTS idx_exam_prep_lesson_practices_lesson_id;
DROP INDEX IF EXISTS idx_exam_prep_lesson_practices_lesson_created;
ALTER TABLE exam_prep.lesson_practices
DROP COLUMN unit_module_lesson_id;
CREATE INDEX idx_exam_prep_practice_parents_practice_id ON exam_prep.practice_parents (practice_id);
CREATE INDEX idx_exam_prep_practice_parents_lookup ON exam_prep.practice_parents (parent_kind, parent_id);
-- <<< END SOURCE: 000093_exam_prep_practice_parents.up.sql
-- >>> BEGIN SOURCE: 000094_exam_prep_multiple_practices_per_parent.up.sql
-- Exam-prep: allow multiple practices per catalog course, unit, or lesson.
ALTER TABLE exam_prep.practice_parents
DROP CONSTRAINT practice_parents_parent_kind_parent_id_key;
-- <<< END SOURCE: 000094_exam_prep_multiple_practices_per_parent.up.sql
-- >>> BEGIN SOURCE: 000095_practice_stimulus_blocks.up.sql
CREATE TABLE practice_stimulus_blocks (
id BIGSERIAL PRIMARY KEY,
practice_kind VARCHAR(20) NOT NULL CHECK (practice_kind IN ('LMS', 'EXAM_PREP')),
practice_id BIGINT NOT NULL,
block_key VARCHAR(64) NOT NULL,
stimulus JSONB NOT NULL DEFAULT '[]'::jsonb,
display_order INT NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ,
UNIQUE (practice_kind, practice_id, block_key)
);
CREATE INDEX idx_practice_stimulus_blocks_practice
ON practice_stimulus_blocks (practice_kind, practice_id);
ALTER TABLE lms_practices
ADD COLUMN authoring_profile VARCHAR(40) NOT NULL DEFAULT 'STANDALONE'
CHECK (authoring_profile IN ('STANDALONE', 'IELTS_SHARED_STIMULUS'));
ALTER TABLE exam_prep.lesson_practices
ADD COLUMN authoring_profile VARCHAR(40) NOT NULL DEFAULT 'STANDALONE'
CHECK (authoring_profile IN ('STANDALONE', 'IELTS_SHARED_STIMULUS'));
ALTER TABLE question_set_items
ADD COLUMN stimulus_block_key VARCHAR(64);
-- <<< END SOURCE: 000095_practice_stimulus_blocks.up.sql
-- >>> BEGIN SOURCE: 000096_subscription_activated_email_template.up.sql
INSERT INTO email_templates (slug, name, subject, body_text, body_html, variables, is_system, status)
VALUES (
'subscription_activated',
'Subscription Activated',
'Your Rezina subscription is active',
'Hi{{if .FirstName}} {{.FirstName}}{{end}},
Your "{{.PlanName}}" {{.PackageLabel}} subscription is now active{{if .ExpiresLabel}} until {{.ExpiresLabel}}{{else if .IsLifetime}} with lifetime access{{end}}.
Sign in to start learning: {{.LoginURL}}',
$subscription_html$<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>Rezina</title></head>
<body style="margin:0;padding:0;background-color:#f4f6fb;font-family:Inter,Roboto,Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6fb;padding:32px 16px;">
<tr><td align="center">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(157,42,131,0.14);">
<tr><td style="background:linear-gradient(135deg,#7b1f6e 0%,#9d2a83 52%,#c43a9a 100%);padding:28px 32px;text-align:center;">
<p style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">Rezina</p>
<p style="margin:8px 0 0;color:rgba(255,255,255,0.88);font-size:11px;font-weight:600;letter-spacing:0.1em;text-transform:uppercase;">Online Learning Platform</p>
</td></tr>
<tr><td style="padding:32px;">
<h1 style="margin:0 0 8px;color:#333333;font-size:24px;font-weight:700;">Subscription active</h1>
<p style="margin:0 0 20px;color:#666666;font-size:15px;line-height:1.6;">{{if .FirstName}}Hi <strong style="color:#333333;">{{.FirstName}}</strong>, {{end}}your <strong style="color:#9d2a83;">{{.PlanName}}</strong> {{.PackageLabel}} package is now active.{{if .IsLifetime}} You have lifetime access.{{else if .ExpiresLabel}} It is valid until <strong style="color:#333333;">{{.ExpiresLabel}}</strong>.{{end}}</p>
<p style="margin:0 0 24px;text-align:center;"><a href="{{.LoginURL}}" style="display:inline-block;background-color:#9d2a83;color:#ffffff !important;text-decoration:none;padding:14px 28px;border-radius:8px;font-weight:600;font-size:15px;">Start learning</a></p>
<p style="margin:24px 0 0;color:#666666;font-size:14px;line-height:1.6;">Thank you for subscribing to Rezina.</p>
</td></tr>
<tr><td style="padding:20px 32px;background-color:#fafafa;border-top:1px solid #eeeeee;text-align:center;">
<p style="margin:0;color:#999999;font-size:12px;">&copy; 2026 Rezina &middot; All rights reserved</p>
</td></tr>
</table></td></tr></table></body></html>$subscription_html$,
'["FirstName", "PlanName", "PackageLabel", "LoginURL", "ExpiresLabel", "IsLifetime"]'::jsonb,
TRUE,
'ACTIVE'
)
ON CONFLICT (slug) DO NOTHING;
-- <<< END SOURCE: 000096_subscription_activated_email_template.up.sql
-- >>> BEGIN SOURCE: 000097_team_custom_rbac_roles.up.sql
-- Allow custom RBAC role names on team_members.team_role (not only the built-in eight).
ALTER TABLE team_members
DROP CONSTRAINT IF EXISTS team_members_team_role_check;
-- <<< END SOURCE: 000097_team_custom_rbac_roles.up.sql
-- >>> BEGIN SOURCE: 000098_team_otps.up.sql
CREATE TABLE IF NOT EXISTS team_otps (
id BIGSERIAL PRIMARY KEY,
team_member_id BIGINT NOT NULL REFERENCES team_members(id) ON DELETE CASCADE,
sent_to VARCHAR(255) NOT NULL,
medium VARCHAR(50) NOT NULL DEFAULT 'email',
otp_for VARCHAR(50) NOT NULL DEFAULT 'reset',
otp VARCHAR(10) NOT NULL,
used BOOLEAN NOT NULL DEFAULT FALSE,
used_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_team_otps_member_id ON team_otps(team_member_id);
CREATE INDEX IF NOT EXISTS idx_team_otps_member_created ON team_otps(team_member_id, created_at DESC);
-- <<< END SOURCE: 000098_team_otps.up.sql
-- >>> BEGIN SOURCE: 000099_ielts_lifetime_subscriptions.up.sql
-- IELTS subscriptions are one-time purchases with no real expiry.
UPDATE user_subscriptions us
SET
expires_at = TIMESTAMPTZ '9999-12-31 23:59:59+00',
updated_at = CURRENT_TIMESTAMP
FROM subscription_plans sp
WHERE us.plan_id = sp.id
AND sp.category = 'IELTS'
AND us.expires_at < TIMESTAMPTZ '9999-01-01 00:00:00+00';
-- <<< END SOURCE: 000099_ielts_lifetime_subscriptions.up.sql
-- >>> BEGIN SOURCE: 000100_subscription_plan_is_lifetime.up.sql
-- Per-plan lifetime (one-time) billing flag, independent of content category.
ALTER TABLE subscription_plans
ADD COLUMN IF NOT EXISTS is_lifetime BOOLEAN NOT NULL DEFAULT FALSE;
-- Preserve existing product behavior: IELTS and DUOLINGO plans remain one-time.
UPDATE subscription_plans
SET is_lifetime = TRUE
WHERE UPPER(TRIM(category)) IN ('IELTS', 'DUOLINGO')
AND is_lifetime = FALSE;
-- <<< END SOURCE: 000100_subscription_plan_is_lifetime.up.sql
-- >>> BEGIN SOURCE: 000101_initial_assessment_placement.up.sql
CREATE TABLE IF NOT EXISTS initial_assessment_level_thresholds (
level VARCHAR(8) PRIMARY KEY,
min_percent INT NOT NULL CHECK (min_percent >= 0 AND min_percent <= 100),
display_order INT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
INSERT INTO initial_assessment_level_thresholds (level, min_percent, display_order)
VALUES
('A1', 0, 1),
('A2', 17, 2),
('B1', 34, 3),
('B2', 51, 4),
('C1', 68, 5),
('C2', 85, 6)
ON CONFLICT (level) DO NOTHING;
-- <<< END SOURCE: 000101_initial_assessment_placement.up.sql
-- >>> BEGIN SOURCE: 000102_initial_assessment_per_level.up.sql
-- Progressive placement: one INITIAL_ASSESSMENT question set per CEFR level (description = A1–C2).
-- Threshold min_percent becomes the pass mark for that level's set.
-- Normalize legacy single "PLACEMENT" / empty sets onto A1, keep at most one published A1.
WITH ranked AS (
SELECT
id,
ROW_NUMBER() OVER (
ORDER BY
CASE WHEN UPPER(TRIM(status)) = 'PUBLISHED' THEN 0 ELSE 1 END,
created_at DESC
) AS rn
FROM question_sets
WHERE set_type = 'INITIAL_ASSESSMENT'
)
UPDATE question_sets qs
SET
description = 'A1',
status = CASE
WHEN ranked.rn = 1 THEN qs.status
WHEN UPPER(TRIM(qs.status)) = 'PUBLISHED' THEN 'DRAFT'
ELSE qs.status
END,
updated_at = NOW()
FROM ranked
WHERE qs.id = ranked.id
AND (
qs.description IS NULL
OR TRIM(qs.description) = ''
OR UPPER(TRIM(qs.description)) = 'PLACEMENT'
OR UPPER(TRIM(qs.description)) NOT IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')
);
WITH pubs AS (
SELECT
id,
UPPER(TRIM(description)) AS level,
ROW_NUMBER() OVER (
PARTITION BY UPPER(TRIM(description))
ORDER BY created_at DESC
) AS rn
FROM question_sets
WHERE set_type = 'INITIAL_ASSESSMENT'
AND UPPER(TRIM(status)) = 'PUBLISHED'
AND UPPER(TRIM(description)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')
)
UPDATE question_sets qs
SET status = 'DRAFT', updated_at = NOW()
FROM pubs
WHERE qs.id = pubs.id
AND pubs.rn > 1;
CREATE UNIQUE INDEX IF NOT EXISTS idx_initial_assessment_one_published_per_level
ON question_sets ((UPPER(TRIM(description))))
WHERE set_type = 'INITIAL_ASSESSMENT'
AND UPPER(TRIM(status)) = 'PUBLISHED'
AND UPPER(TRIM(description)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2');
-- Pass marks for each level set (replaces single-test score banding defaults).
UPDATE initial_assessment_level_thresholds
SET min_percent = 70, updated_at = NOW();
CREATE TABLE IF NOT EXISTS user_initial_assessment_progress (
user_id BIGINT PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,
next_level VARCHAR(8) NOT NULL DEFAULT 'A1',
highest_passed_level VARCHAR(8),
completed BOOLEAN NOT NULL DEFAULT FALSE,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT user_initial_assessment_progress_next_level_check
CHECK (UPPER(TRIM(next_level)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')),
CONSTRAINT user_initial_assessment_progress_highest_passed_check
CHECK (
highest_passed_level IS NULL
OR UPPER(TRIM(highest_passed_level)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2')
)
);
-- <<< END SOURCE: 000102_initial_assessment_per_level.up.sql
-- >>> BEGIN SOURCE: 000103_content_manager_staff_role.up.sql
-- Staff team roles: Super Admin, Admin, Content Manager only.
INSERT INTO roles (name, description, is_system)
VALUES ('CONTENT_MANAGER', 'Content manager — admin panel content section only', true)
ON CONFLICT (name) DO NOTHING;
UPDATE team_members
SET team_role = 'ADMIN'
WHERE team_role NOT IN ('SUPER_ADMIN', 'ADMIN', 'CONTENT_MANAGER');
ALTER TABLE team_members
ADD CONSTRAINT team_members_team_role_check
CHECK (team_role IN ('SUPER_ADMIN', 'ADMIN', 'CONTENT_MANAGER'));
-- <<< END SOURCE: 000103_content_manager_staff_role.up.sql
-- >>> BEGIN SOURCE: 000104_admin_revoke_team_invite.up.sql
-- Team invite/resend are Super Admin only; revoke if previously granted to ADMIN.
DELETE FROM role_permissions
WHERE role_id = (SELECT id FROM roles WHERE name = 'ADMIN')
AND permission_id IN (
SELECT id FROM permissions
WHERE key IN ('team.members.invite', 'team.invitations.resend')
);
-- <<< END SOURCE: 000104_admin_revoke_team_invite.up.sql
-- >>> BEGIN SOURCE: 000105_lms_multiple_practices_per_parent.up.sql
-- Learn English: allow multiple practices per course, module, or lesson
-- (matches exam-prep 000094). Duplicate links on the same practice remain unique.
ALTER TABLE lms_practice_parents
DROP CONSTRAINT IF EXISTS lms_practice_parents_parent_kind_parent_id_key;
-- <<< END SOURCE: 000105_lms_multiple_practices_per_parent.up.sql
-- >>> BEGIN SOURCE: 000106_lms_drop_one_practice_per_parent.up.sql
-- 000105 dropped this unique by a single constraint name. Re-drop by definition so
-- Learn English can store multiple practices per course, module, or lesson even if
-- the unique was created under a different name or as an index.
DO $$
DECLARE
r record;
BEGIN
FOR r IN
SELECT c.conname
FROM pg_constraint c
JOIN pg_class t ON t.oid = c.conrelid
JOIN pg_namespace n ON n.oid = t.relnamespace
WHERE n.nspname = 'public'
AND t.relname = 'lms_practice_parents'
AND c.contype = 'u'
AND pg_get_constraintdef(c.oid) ~* 'UNIQUE\s*\(\s*parent_kind\s*,\s*parent_id\s*\)'
LOOP
EXECUTE format('ALTER TABLE public.lms_practice_parents DROP CONSTRAINT IF EXISTS %I', r.conname);
END LOOP;
END $$;
DO $$
DECLARE
r record;
BEGIN
FOR r IN
SELECT i.relname AS idxname
FROM pg_index x
JOIN pg_class i ON i.oid = x.indexrelid
JOIN pg_class t ON t.oid = x.indrelid
JOIN pg_namespace n ON n.oid = t.relnamespace
WHERE n.nspname = 'public'
AND t.relname = 'lms_practice_parents'
AND x.indisunique
AND NOT x.indisprimary
AND pg_get_indexdef(i.oid) LIKE '%(parent_kind, parent_id)%'
AND pg_get_indexdef(i.oid) NOT LIKE '%(practice_id, parent_kind, parent_id)%'
LOOP
EXECUTE format('DROP INDEX IF EXISTS public.%I', r.idxname);
END LOOP;
END $$;
DROP INDEX IF EXISTS lms_practice_parents_parent_kind_parent_id_key;
DROP INDEX IF EXISTS idx_lms_practices_one_per_course;
DROP INDEX IF EXISTS idx_lms_practices_one_per_module;
DROP INDEX IF EXISTS idx_lms_practices_one_per_lesson;
-- <<< END SOURCE: 000106_lms_drop_one_practice_per_parent.up.sql
-- >>> BEGIN SOURCE: 000107_scheduled_notifications_created_by_team_member.up.sql
-- scheduled_notifications.created_by is the admin actor who scheduled the job.
-- Admin panel auth (POST /team/login) JWT user_id is team_members.id, not users.id.
ALTER TABLE scheduled_notifications
DROP CONSTRAINT IF EXISTS scheduled_notifications_created_by_fkey;
-- Remap legacy rows that stored platform users.id to a valid team member when possible.
UPDATE scheduled_notifications sn
SET created_by = tm.id
FROM users u
JOIN team_members tm ON LOWER(TRIM(tm.email)) = LOWER(TRIM(u.email))
WHERE sn.created_by = u.id
AND NOT EXISTS (SELECT 1 FROM team_members existing WHERE existing.id = sn.created_by);
-- Fallback: assign orphaned created_by values to the earliest team member.
UPDATE scheduled_notifications sn
SET created_by = (SELECT id FROM team_members ORDER BY id LIMIT 1)
WHERE NOT EXISTS (SELECT 1 FROM team_members tm WHERE tm.id = sn.created_by);
ALTER TABLE scheduled_notifications
ADD CONSTRAINT scheduled_notifications_created_by_fkey
FOREIGN KEY (created_by) REFERENCES team_members(id);
-- <<< END SOURCE: 000107_scheduled_notifications_created_by_team_member.up.sql
-- >>> BEGIN SOURCE: 000108_lms_restore_one_practice_per_parent.up.sql
-- Learn English: at most one practice per course, module, or lesson parent.
-- Remove duplicate parent links (keep the earliest row per parent) before adding the constraint.
DELETE FROM lms_practice_parents a
USING lms_practice_parents b
WHERE a.parent_kind = b.parent_kind
AND a.parent_id = b.parent_id
AND a.id > b.id;
ALTER TABLE lms_practice_parents
ADD CONSTRAINT lms_practice_parents_parent_kind_parent_id_key UNIQUE (parent_kind, parent_id);
-- <<< END SOURCE: 000108_lms_restore_one_practice_per_parent.up.sql
-- >>> BEGIN SOURCE: 000109_user_practice_progress_parent_scope.up.sql
BEGIN;
ALTER TABLE user_practice_progress
ADD COLUMN IF NOT EXISTS content_domain VARCHAR(20),
ADD COLUMN IF NOT EXISTS parent_kind VARCHAR(30),
ADD COLUMN IF NOT EXISTS parent_id BIGINT;
-- Allow multiple rows per (user_id, question_set_id) while backfilling parent scope.
ALTER TABLE user_practice_progress
DROP CONSTRAINT IF EXISTS user_practice_progress_user_id_question_set_id_key;
-- Expand legacy global completions to each LMS parent link.
INSERT INTO user_practice_progress (
user_id,
question_set_id,
completed_at,
created_at,
updated_at,
content_domain,
parent_kind,
parent_id
)
SELECT DISTINCT
upp.user_id,
upp.question_set_id,
upp.completed_at,
upp.created_at,
upp.updated_at,
'LMS',
lpp.parent_kind,
lpp.parent_id
FROM user_practice_progress upp
INNER JOIN lms_practices lp ON lp.question_set_id = upp.question_set_id
INNER JOIN lms_practice_parents lpp ON lpp.practice_id = lp.id
WHERE upp.content_domain IS NULL;
-- Expand legacy global completions to each exam-prep parent link.
INSERT INTO user_practice_progress (
user_id,
question_set_id,
completed_at,
created_at,
updated_at,
content_domain,
parent_kind,
parent_id
)
SELECT DISTINCT
upp.user_id,
upp.question_set_id,
upp.completed_at,
upp.created_at,
upp.updated_at,
'EXAM_PREP',
pp.parent_kind,
pp.parent_id
FROM user_practice_progress upp
INNER JOIN exam_prep.lesson_practices p ON p.question_set_id = upp.question_set_id
INNER JOIN exam_prep.practice_parents pp ON pp.practice_id = p.id
WHERE upp.content_domain IS NULL;
DELETE FROM user_practice_progress
WHERE content_domain IS NULL;
ALTER TABLE user_practice_progress
ALTER COLUMN content_domain SET NOT NULL,
ALTER COLUMN parent_kind SET NOT NULL,
ALTER COLUMN parent_id SET NOT NULL;
ALTER TABLE user_practice_progress
DROP CONSTRAINT IF EXISTS user_practice_progress_content_domain_check;
ALTER TABLE user_practice_progress
ADD CONSTRAINT user_practice_progress_content_domain_check
CHECK (content_domain IN ('LMS', 'EXAM_PREP'));
ALTER TABLE user_practice_progress
DROP CONSTRAINT IF EXISTS user_practice_progress_user_question_set_parent_key;
ALTER TABLE user_practice_progress
ADD CONSTRAINT user_practice_progress_user_question_set_parent_key
UNIQUE (user_id, question_set_id, content_domain, parent_kind, parent_id);
CREATE INDEX IF NOT EXISTS idx_user_practice_progress_parent_scope
ON user_practice_progress (user_id, content_domain, parent_kind, parent_id);
COMMIT;
-- <<< END SOURCE: 000109_user_practice_progress_parent_scope.up.sql
-- >>> BEGIN SOURCE: 000110_subscription_plan_unique_category_period.up.sql
-- One catalog row per category + billing period (free vs paid is not part of the key).
CREATE UNIQUE INDEX IF NOT EXISTS idx_subscription_plans_category_period
ON subscription_plans (category, is_lifetime, duration_value, duration_unit);
-- <<< END SOURCE: 000110_subscription_plan_unique_category_period.up.sql
-- >>> BEGIN SOURCE: 000111_subscription_plan_is_free.up.sql
ALTER TABLE subscription_plans
ADD COLUMN IF NOT EXISTS is_free BOOLEAN NOT NULL DEFAULT FALSE;
-- Legacy zero-price rows become explicitly free before the price constraint is enforced.
UPDATE subscription_plans
SET is_free = TRUE
WHERE price = 0
AND is_free = FALSE;
ALTER TABLE subscription_plans
ADD CONSTRAINT chk_subscription_plans_free_price
CHECK (
(is_free = TRUE AND price = 0)
OR (is_free = FALSE AND price > 0)
);
-- <<< END SOURCE: 000111_subscription_plan_is_free.up.sql
-- >>> BEGIN SOURCE: 000112_rezina_email_brand.up.sql
-- Update system email templates to the Rezina brand for existing installations.
UPDATE email_templates
SET name = REPLACE(name, 'Yimaru Academy', 'Rezina'),
subject = REPLACE(subject, 'Yimaru Academy', 'Rezina'),
body_text = REPLACE(body_text, 'Yimaru Academy', 'Rezina'),
body_html = REPLACE(body_html, 'Yimaru Academy', 'Rezina'),
updated_at = NOW()
WHERE name ILIKE '%Yimaru Academy%'
OR subject ILIKE '%Yimaru Academy%'
OR body_text ILIKE '%Yimaru Academy%'
OR body_html ILIKE '%Yimaru Academy%';
-- <<< END SOURCE: 000112_rezina_email_brand.up.sql
-- >>> BEGIN SOURCE: 000113_generic_assessment_levels.up.sql
-- Replace CEFR defaults with curriculum-defined remediation bands while retaining
-- existing assessment data and allowing longer administrator-defined labels.
ALTER TABLE initial_assessment_level_thresholds ALTER COLUMN level TYPE VARCHAR(64);
UPDATE initial_assessment_level_thresholds
SET level = CASE UPPER(TRIM(level))
WHEN 'A1' THEN 'FOUNDATION'
WHEN 'A2' THEN 'DEVELOPING'
WHEN 'B1' THEN 'SECURE'
WHEN 'B2' THEN 'EXTENSION'
WHEN 'C1' THEN 'ADVANCED'
WHEN 'C2' THEN 'MASTERY'
ELSE UPPER(TRIM(level)) END;
ALTER TABLE user_initial_assessment_progress ALTER COLUMN next_level TYPE VARCHAR(64);
ALTER TABLE user_initial_assessment_progress ALTER COLUMN highest_passed_level TYPE VARCHAR(64);
ALTER TABLE user_initial_assessment_progress DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_next_level_check;
ALTER TABLE user_initial_assessment_progress DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_highest_passed_check;
UPDATE user_initial_assessment_progress
SET next_level = CASE UPPER(TRIM(next_level))
WHEN 'A1' THEN 'FOUNDATION' WHEN 'A2' THEN 'DEVELOPING' WHEN 'B1' THEN 'SECURE'
WHEN 'B2' THEN 'EXTENSION' WHEN 'C1' THEN 'ADVANCED' WHEN 'C2' THEN 'MASTERY'
ELSE UPPER(TRIM(next_level)) END,
highest_passed_level = CASE UPPER(TRIM(highest_passed_level))
WHEN 'A1' THEN 'FOUNDATION' WHEN 'A2' THEN 'DEVELOPING' WHEN 'B1' THEN 'SECURE'
WHEN 'B2' THEN 'EXTENSION' WHEN 'C1' THEN 'ADVANCED' WHEN 'C2' THEN 'MASTERY'
ELSE UPPER(TRIM(highest_passed_level)) END;
UPDATE question_sets
SET description = CASE UPPER(TRIM(description))
WHEN 'A1' THEN 'FOUNDATION' WHEN 'A2' THEN 'DEVELOPING' WHEN 'B1' THEN 'SECURE'
WHEN 'B2' THEN 'EXTENSION' WHEN 'C1' THEN 'ADVANCED' WHEN 'C2' THEN 'MASTERY'
ELSE description END,
updated_at = NOW()
WHERE set_type = 'INITIAL_ASSESSMENT'
AND UPPER(TRIM(description)) IN ('A1', 'A2', 'B1', 'B2', 'C1', 'C2');
DROP INDEX IF EXISTS idx_initial_assessment_one_published_per_level;
CREATE UNIQUE INDEX idx_initial_assessment_one_published_per_level
ON question_sets ((UPPER(TRIM(description))), (COALESCE(UPPER(TRIM(owner_type)), 'STANDALONE')), (COALESCE(owner_id, 0)))
WHERE set_type = 'INITIAL_ASSESSMENT'
AND UPPER(TRIM(status)) = 'PUBLISHED'
AND NULLIF(TRIM(description), '') IS NOT NULL;
-- <<< END SOURCE: 000113_generic_assessment_levels.up.sql
-- >>> BEGIN SOURCE: 000114_subject_assessment_progress.up.sql
-- Persist placement independently for each subject (subject_id is the subject/course identifier).
ALTER TABLE user_initial_assessment_progress
ADD COLUMN subject_id BIGINT NOT NULL DEFAULT 0;
ALTER TABLE user_initial_assessment_progress
DROP CONSTRAINT IF EXISTS user_initial_assessment_progress_pkey;
ALTER TABLE user_initial_assessment_progress
ADD CONSTRAINT user_initial_assessment_progress_pkey PRIMARY KEY (user_id, subject_id);
-- <<< END SOURCE: 000114_subject_assessment_progress.up.sql
-- >>> BEGIN SOURCE: 000115_education_subscription_category.up.sql
-- Generalize the active LMS subscription product. Keep inactive legacy plan rows
-- available for historical billing and reporting records.
ALTER TABLE subscription_plans DROP CONSTRAINT IF EXISTS chk_subscription_plans_category;
ALTER TABLE subscription_plans
ADD CONSTRAINT chk_subscription_plans_category
CHECK (category IN ('EDUCATION', 'LEARN_ENGLISH', 'IELTS', 'DUOLINGO'));
UPDATE subscription_plans
SET category = 'EDUCATION', updated_at = NOW()
WHERE category = 'LEARN_ENGLISH';
UPDATE subscription_plans
SET is_active = FALSE, updated_at = NOW()
WHERE category IN ('IELTS', 'DUOLINGO');
ALTER TABLE programs DROP CONSTRAINT IF EXISTS chk_programs_category;
UPDATE programs SET category = 'EDUCATION', updated_at = NOW();
ALTER TABLE programs
ADD CONSTRAINT chk_programs_category CHECK (category = 'EDUCATION');
-- <<< END SOURCE: 000115_education_subscription_category.up.sql
-- >>> BEGIN SOURCE: 000116_remove_initial_assessment.up.sql
-- Preserve existing assessment questions as ordinary practice and archive learner/configuration
-- metadata so a rollback can restore the previous feature without losing its records.
CREATE TABLE retired_initial_assessment_question_sets (
question_set_id BIGINT PRIMARY KEY,
set_type VARCHAR(30) NOT NULL
);
INSERT INTO retired_initial_assessment_question_sets (question_set_id, set_type)
SELECT id, set_type FROM question_sets WHERE set_type = 'INITIAL_ASSESSMENT';
UPDATE question_sets SET set_type = 'PRACTICE' WHERE set_type = 'INITIAL_ASSESSMENT';
ALTER TABLE question_sets DROP CONSTRAINT IF EXISTS question_sets_set_type_check;
ALTER TABLE question_sets ADD CONSTRAINT question_sets_set_type_check
CHECK (set_type IN ('PRACTICE', 'QUIZ', 'EXAM', 'SURVEY', 'CAPSTONE'));
ALTER TABLE initial_assessment_level_thresholds RENAME TO retired_initial_assessment_level_thresholds;
ALTER TABLE user_initial_assessment_progress RENAME TO retired_user_initial_assessment_progress;
CREATE TABLE retired_initial_assessment_completion (
user_id BIGINT PRIMARY KEY,
completed BOOLEAN NOT NULL
);
INSERT INTO retired_initial_assessment_completion (user_id, completed)
SELECT id, initial_assessment_completed FROM users;
ALTER TABLE users DROP COLUMN initial_assessment_completed;
-- <<< END SOURCE: 000116_remove_initial_assessment.up.sql
-- >>> BEGIN SOURCE: 000117_unified_exam_prep_hierarchy.up.sql
BEGIN;
-- Assessment question sets remain distinct from practice content and can be
-- attached at any level of the canonical hierarchy.
CREATE TABLE exam_prep.assessment_parents (
question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
parent_kind VARCHAR(24) NOT NULL CHECK (parent_kind IN ('CATALOG_COURSE', 'UNIT', 'MODULE', 'LESSON')),
parent_id BIGINT NOT NULL CHECK (parent_id > 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (question_set_id, parent_kind, parent_id)
);
CREATE INDEX idx_exam_prep_assessment_parents_parent
ON exam_prep.assessment_parents (parent_kind, parent_id);
CREATE FUNCTION exam_prep.require_exam_question_set() RETURNS trigger AS $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM question_sets WHERE id = NEW.question_set_id AND UPPER(set_type) = 'EXAM'
) THEN
RAISE EXCEPTION 'assessment parent links require an EXAM question set';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_exam_prep_assessment_question_set_type
BEFORE INSERT OR UPDATE OF question_set_id ON exam_prep.assessment_parents
FOR EACH ROW EXECUTE FUNCTION exam_prep.require_exam_question_set();
-- The exam-prep hierarchy is now the canonical learning-content tree. EDUCATION
-- keeps rebuilt Learn English material distinct from IELTS and Duolingo products.
ALTER TABLE exam_prep.catalog_courses
DROP CONSTRAINT chk_exam_prep_catalog_courses_category;
ALTER TABLE exam_prep.catalog_courses
ADD CONSTRAINT chk_exam_prep_catalog_courses_category
CHECK (category IN ('EDUCATION', 'IELTS', 'DUOLINGO'));
-- Keep an ID map so content, practice links, progress, and video history can be
-- migrated without assuming IDs from separate sequences are equal.
CREATE TABLE lms_exam_prep_migration_map (
entity_kind VARCHAR(24) NOT NULL,
legacy_id BIGINT NOT NULL,
migrated_id BIGINT NOT NULL,
PRIMARY KEY (entity_kind, legacy_id),
UNIQUE (entity_kind, migrated_id)
);
INSERT INTO lms_exam_prep_migration_map (entity_kind, legacy_id, migrated_id)
SELECT 'CATALOG_COURSE', p.id, COALESCE((SELECT MAX(id) FROM exam_prep.catalog_courses), 0) + p.id
FROM programs p;
INSERT INTO exam_prep.catalog_courses (
id, name, description, thumbnail, category, sort_order, publish_status,
access_tier, created_at, updated_at
)
SELECT m.migrated_id, p.name, p.description, p.thumbnail, 'EDUCATION', p.sort_order,
p.publish_status, p.access_tier, p.created_at, p.updated_at
FROM programs p
JOIN lms_exam_prep_migration_map m ON m.entity_kind = 'CATALOG_COURSE' AND m.legacy_id = p.id;
INSERT INTO lms_exam_prep_migration_map (entity_kind, legacy_id, migrated_id)
SELECT 'UNIT', c.id, COALESCE((SELECT MAX(id) FROM exam_prep.units), 0) + c.id
FROM courses c;
INSERT INTO exam_prep.units (
id, catalog_course_id, name, description, thumbnail, sort_order, publish_status,
access_tier, created_at, updated_at
)
SELECT m.migrated_id, cm.migrated_id, c.name, c.description, c.thumbnail, c.sort_order,
c.publish_status, c.access_tier, c.created_at, c.updated_at
FROM courses c
JOIN lms_exam_prep_migration_map m ON m.entity_kind = 'UNIT' AND m.legacy_id = c.id
JOIN lms_exam_prep_migration_map cm ON cm.entity_kind = 'CATALOG_COURSE' AND cm.legacy_id = c.program_id;
INSERT INTO lms_exam_prep_migration_map (entity_kind, legacy_id, migrated_id)
SELECT 'MODULE', m.id, COALESCE((SELECT MAX(id) FROM exam_prep.unit_modules), 0) + m.id
FROM modules m;
INSERT INTO exam_prep.unit_modules (
id, unit_id, name, description, thumbnail, icon, sort_order, publish_status,
access_tier, created_at, updated_at
)
SELECT mm.migrated_id, um.migrated_id, m.name, m.description, m.thumbnail, m.icon,
m.sort_order, m.publish_status, m.access_tier, m.created_at, m.updated_at
FROM modules m
JOIN lms_exam_prep_migration_map mm ON mm.entity_kind = 'MODULE' AND mm.legacy_id = m.id
JOIN lms_exam_prep_migration_map um ON um.entity_kind = 'UNIT' AND um.legacy_id = m.course_id;
INSERT INTO lms_exam_prep_migration_map (entity_kind, legacy_id, migrated_id)
SELECT 'LESSON', l.id, COALESCE((SELECT MAX(id) FROM exam_prep.unit_module_lessons), 0) + l.id
FROM lessons l;
INSERT INTO exam_prep.unit_module_lessons (
id, unit_module_id, title, video_url, thumbnail, description, sort_order,
publish_status, access_tier, created_at, updated_at
)
SELECT lm.migrated_id, mm.migrated_id, l.title, l.video_url, l.thumbnail, l.description,
l.sort_order, l.publish_status, l.access_tier, l.created_at, l.updated_at
FROM lessons l
JOIN lms_exam_prep_migration_map lm ON lm.entity_kind = 'LESSON' AND lm.legacy_id = l.id
JOIN lms_exam_prep_migration_map mm ON mm.entity_kind = 'MODULE' AND mm.legacy_id = l.module_id;
INSERT INTO lms_exam_prep_migration_map (entity_kind, legacy_id, migrated_id)
SELECT 'PRACTICE', p.id, COALESCE((SELECT MAX(id) FROM exam_prep.lesson_practices), 0) + p.id
FROM lms_practices p;
INSERT INTO exam_prep.lesson_practices (
id, title, story_description, story_image, persona_id, question_set_id,
quick_tips, authoring_profile, publish_status, created_at, updated_at
)
SELECT pm.migrated_id, p.title, p.story_description, p.story_image, p.persona_id,
p.question_set_id, p.quick_tips, p.authoring_profile, p.publish_status,
p.created_at, p.updated_at
FROM lms_practices p
JOIN lms_exam_prep_migration_map pm ON pm.entity_kind = 'PRACTICE' AND pm.legacy_id = p.id;
-- Old course and module practices become unit practices; lesson practices keep
-- their lesson parent. Multiple practices per parent are supported by exam_prep.
INSERT INTO exam_prep.practice_parents (practice_id, parent_kind, parent_id, created_at)
SELECT DISTINCT pm.migrated_id, 'UNIT', um.migrated_id, pp.created_at
FROM lms_practice_parents pp
JOIN lms_exam_prep_migration_map pm ON pm.entity_kind = 'PRACTICE' AND pm.legacy_id = pp.practice_id
JOIN lms_exam_prep_migration_map um ON um.entity_kind = 'UNIT' AND um.legacy_id = pp.parent_id
WHERE pp.parent_kind = 'COURSE'
ON CONFLICT (practice_id, parent_kind, parent_id) DO NOTHING;
INSERT INTO exam_prep.practice_parents (practice_id, parent_kind, parent_id, created_at)
SELECT DISTINCT pm.migrated_id, 'UNIT', um.migrated_id, pp.created_at
FROM lms_practice_parents pp
JOIN modules m ON pp.parent_id = m.id
JOIN lms_exam_prep_migration_map pm ON pm.entity_kind = 'PRACTICE' AND pm.legacy_id = pp.practice_id
JOIN lms_exam_prep_migration_map um ON um.entity_kind = 'UNIT' AND um.legacy_id = m.course_id
WHERE pp.parent_kind = 'MODULE'
ON CONFLICT (practice_id, parent_kind, parent_id) DO NOTHING;
INSERT INTO exam_prep.practice_parents (practice_id, parent_kind, parent_id, created_at)
SELECT DISTINCT pm.migrated_id, 'LESSON', lm.migrated_id, pp.created_at
FROM lms_practice_parents pp
JOIN lms_exam_prep_migration_map pm ON pm.entity_kind = 'PRACTICE' AND pm.legacy_id = pp.practice_id
JOIN lms_exam_prep_migration_map lm ON lm.entity_kind = 'LESSON' AND lm.legacy_id = pp.parent_id
WHERE pp.parent_kind = 'LESSON'
ON CONFLICT (practice_id, parent_kind, parent_id) DO NOTHING;
INSERT INTO practice_stimulus_blocks (
practice_kind, practice_id, block_key, stimulus, display_order, created_at, updated_at
)
SELECT 'EXAM_PREP', pm.migrated_id, b.block_key, b.stimulus, b.display_order, b.created_at, b.updated_at
FROM practice_stimulus_blocks b
JOIN lms_exam_prep_migration_map pm ON pm.entity_kind = 'PRACTICE' AND pm.legacy_id = b.practice_id
WHERE b.practice_kind = 'LMS'
ON CONFLICT (practice_kind, practice_id, block_key) DO NOTHING;
-- Carry practice completion records onto their migrated parent IDs. Lesson and
-- course/module scopes are normalized to the new exam-prep parent vocabulary.
INSERT INTO user_practice_progress (
user_id, question_set_id, completed_at, created_at, updated_at,
content_domain, parent_kind, parent_id
)
SELECT DISTINCT upp.user_id, upp.question_set_id, upp.completed_at, upp.created_at,
upp.updated_at, 'EXAM_PREP',
CASE WHEN upp.parent_kind = 'LESSON' THEN 'LESSON' ELSE 'UNIT' END,
CASE WHEN upp.parent_kind = 'LESSON' THEN lm.migrated_id ELSE um.migrated_id END
FROM user_practice_progress upp
JOIN lms_practices p ON p.question_set_id = upp.question_set_id
JOIN lms_exam_prep_migration_map pm ON pm.entity_kind = 'PRACTICE' AND pm.legacy_id = p.id
LEFT JOIN lms_exam_prep_migration_map lm ON lm.entity_kind = 'LESSON' AND lm.legacy_id = upp.parent_id AND upp.parent_kind = 'LESSON'
LEFT JOIN modules m ON m.id = upp.parent_id AND upp.parent_kind = 'MODULE'
LEFT JOIN lms_exam_prep_migration_map um ON um.entity_kind = 'UNIT' AND um.legacy_id = COALESCE(m.course_id, upp.parent_id)
WHERE upp.content_domain = 'LMS'
AND (upp.parent_kind = 'LESSON' AND lm.migrated_id IS NOT NULL
OR upp.parent_kind IN ('COURSE', 'MODULE') AND um.migrated_id IS NOT NULL)
ON CONFLICT (user_id, question_set_id, content_domain, parent_kind, parent_id) DO NOTHING;
INSERT INTO user_video_watch_sessions (
user_id, content_kind, content_id, session_number, video_duration_sec,
max_position_sec, started_at, last_heartbeat_at, ended_at, completed_at
)
SELECT s.user_id, 'exam_prep_lesson', lm.migrated_id, s.session_number,
s.video_duration_sec, s.max_position_sec, s.started_at, s.last_heartbeat_at,
s.ended_at, s.completed_at
FROM user_video_watch_sessions s
JOIN lms_exam_prep_migration_map lm ON lm.entity_kind = 'LESSON' AND lm.legacy_id = s.content_id
WHERE s.content_kind = 'lms_lesson'
ON CONFLICT (user_id, content_kind, content_id, session_number) DO NOTHING;
SELECT setval(pg_get_serial_sequence('exam_prep.catalog_courses', 'id'), COALESCE((SELECT MAX(id) FROM exam_prep.catalog_courses), 1));
SELECT setval(pg_get_serial_sequence('exam_prep.units', 'id'), COALESCE((SELECT MAX(id) FROM exam_prep.units), 1));
SELECT setval(pg_get_serial_sequence('exam_prep.unit_modules', 'id'), COALESCE((SELECT MAX(id) FROM exam_prep.unit_modules), 1));
SELECT setval(pg_get_serial_sequence('exam_prep.unit_module_lessons', 'id'), COALESCE((SELECT MAX(id) FROM exam_prep.unit_module_lessons), 1));
SELECT setval(pg_get_serial_sequence('exam_prep.lesson_practices', 'id'), COALESCE((SELECT MAX(id) FROM exam_prep.lesson_practices), 1));
COMMIT;
-- <<< END SOURCE: 000117_unified_exam_prep_hierarchy.up.sql