RezinaLMS-BackEnd/db/migrations/000109_user_practice_progress_parent_scope.up.sql
Yared Yemane d8630c15d6 Fix migration 000109 to drop legacy unique key before parent-scope backfill.
The backfill inserts multiple rows per user and question set when a practice has several parent links, so the old (user_id, question_set_id) constraint must be removed first.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 15:37:20 +03:00

88 lines
2.6 KiB
PL/PgSQL

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;