[Eva] B5.3: database.py — UNIQUE(sentence_number) + перенумерация

This commit is contained in:
2026-10-16 11:58:59 +00:00
parent 5810eccde1
commit 3c9548540c
+16 -5
View File
@@ -258,20 +258,31 @@ async def init_db():
) )
""") """)
# ============ Убираем старый UNIQUE constraint с sentences.sentence_number ============ # ============ Убираем составной UNIQUE (level, sentence_number) ============
await conn.execute(""" await conn.execute("""
ALTER TABLE sentences DROP CONSTRAINT IF EXISTS sentences_sentence_number_key ALTER TABLE sentences DROP CONSTRAINT IF EXISTS sentences_sentence_number_unique
""") """)
# ============ Добавляем составной UNIQUE (level, sentence_number) ============ # ============ Пересчёт номеров: единый пул 1..N ============
await conn.execute("""
UPDATE sentences s
SET sentence_number = sub.rn
FROM (
SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS rn
FROM sentences
) sub
WHERE s.id = sub.id
""")
# ============ Добавляем UNIQUE (sentence_number) ============
await conn.execute(""" await conn.execute("""
DO $$ DO $$
BEGIN BEGIN
IF NOT EXISTS ( IF NOT EXISTS (
SELECT 1 FROM pg_constraint SELECT 1 FROM pg_constraint
WHERE conname = 'sentences_sentence_number_unique' WHERE conname = 'sentences_sentence_number_key'
) THEN ) THEN
ALTER TABLE sentences ADD CONSTRAINT sentences_sentence_number_unique UNIQUE (level, sentence_number); ALTER TABLE sentences ADD CONSTRAINT sentences_sentence_number_key UNIQUE (sentence_number);
END IF; END IF;
END $$; END $$;
""") """)