From 1d15b5f0c10361066e6b33f24bdce5191ff02bd0 Mon Sep 17 00:00:00 2001 From: Aaron Roberts Date: Tue, 9 Jun 2026 18:19:54 +0100 Subject: [PATCH] Add unique constraint to prevent duplicate (author, chapter, page) submissions Adds a PostgreSQL partial unique index on (author, chapter, page) where all three fields are non-null, and returns HTTP 409 when a duplicate is detected. Co-Authored-By: Claude Sonnet 4.6 --- backend/database.py | 7 +++++++ backend/main.py | 6 ++++++ 2 files changed, 13 insertions(+) diff --git a/backend/database.py b/backend/database.py index e04068b..6720b5c 100644 --- a/backend/database.py +++ b/backend/database.py @@ -45,6 +45,13 @@ def init_db(): cur.execute(""" CREATE INDEX IF NOT EXISTS ocr_jobs_submitted_at_idx ON ocr_jobs(submitted_at DESC) """) + # Unique constraint: prevent duplicate (author, chapter, page) submissions. + # Applies only when all three fields are non-null. + cur.execute(""" + CREATE UNIQUE INDEX IF NOT EXISTS ocr_jobs_author_chapter_page_unique + ON ocr_jobs (author, chapter, page) + WHERE author IS NOT NULL AND chapter IS NOT NULL AND page IS NOT NULL + """) conn.commit() print("Database initialized.") except Exception as exc: diff --git a/backend/main.py b/backend/main.py index b86ba20..48b4566 100644 --- a/backend/main.py +++ b/backend/main.py @@ -675,6 +675,12 @@ async def commit_job( os.remove(image_path) except Exception: pass + # Unique constraint violation (author + chapter + page already exists) + if getattr(exc, 'pgcode', None) == '23505': + raise HTTPException( + status_code=409, + detail="A job with this Author, Chapter, and Page already exists." + ) print(f"Job commit DB error: {exc}") raise HTTPException(status_code=500, detail="Failed to save job to database.")