BEGIN; DROP INDEX IF EXISTS idx_user_practice_progress_parent_scope; ALTER TABLE user_practice_progress DROP CONSTRAINT IF EXISTS user_practice_progress_user_question_set_parent_key; ALTER TABLE user_practice_progress DROP CONSTRAINT IF EXISTS user_practice_progress_content_domain_check; -- Collapse scoped rows back to one row per user + question set (earliest completion wins). CREATE TEMP TABLE user_practice_progress_legacy AS SELECT DISTINCT ON (user_id, question_set_id) user_id, question_set_id, completed_at, created_at, updated_at FROM user_practice_progress ORDER BY user_id, question_set_id, completed_at ASC NULLS LAST, id ASC; TRUNCATE user_practice_progress; INSERT INTO user_practice_progress (user_id, question_set_id, completed_at, created_at, updated_at) SELECT user_id, question_set_id, completed_at, created_at, updated_at FROM user_practice_progress_legacy; ALTER TABLE user_practice_progress DROP COLUMN IF EXISTS content_domain, DROP COLUMN IF EXISTS parent_kind, DROP COLUMN IF EXISTS parent_id; ALTER TABLE user_practice_progress ADD CONSTRAINT user_practice_progress_user_id_question_set_id_key UNIQUE (user_id, question_set_id); COMMIT;