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.")