fix: handle unique constraint violation in manual fetch endpoint

When a duplicate timestamp occurs (rare but possible), return the
existing record instead of failing with a 500 error. This matches
the worker's ON CONFLICT DO NOTHING behavior.

Added test for duplicate timestamp handling.
This commit is contained in:
counterweight 2025-12-22 16:09:05 +01:00
parent 1c9761e559
commit a5488fd20b
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C
2 changed files with 48 additions and 2 deletions

View file

@ -6,6 +6,7 @@ from typing import TypeVar
from fastapi import APIRouter, Depends, Query
from pydantic import BaseModel
from sqlalchemy import desc, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from auth import require_permission
@ -200,8 +201,20 @@ async def fetch_price_now(
timestamp=timestamp,
)
db.add(record)
await db.commit()
await db.refresh(record)
try:
await db.commit()
await db.refresh(record)
except IntegrityError:
# Duplicate timestamp - return the existing record
await db.rollback()
query = select(PriceHistory).where(
PriceHistory.source == SOURCE_BITFINEX,
PriceHistory.pair == PAIR_BTC_EUR,
PriceHistory.timestamp == timestamp,
)
result = await db.execute(query)
record = result.scalar_one()
return PriceHistoryResponse(
id=record.id,