BEGIN; ALTER TABLE user_practice_progress ADD COLUMN content_domain VARCHAR(20), ADD COLUMN parent_kind VARCHAR(30), ADD COLUMN parent_id BIGINT; -- 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 ADD CONSTRAINT user_practice_progress_content_domain_check CHECK (content_domain IN ('LMS', 'EXAM_PREP')); ALTER TABLE user_practice_progress DROP CONSTRAINT user_practice_progress_user_id_question_set_id_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 idx_user_practice_progress_parent_scope ON user_practice_progress (user_id, content_domain, parent_kind, parent_id); COMMIT;