Fix popular task failing silently when table doesn't exist

The outer try had no except — any exception (e.g. table missing) killed
the whole background task with no error visible to the user. Now:
- CREATE TABLE IF NOT EXISTS inline so the task works even if the
  startup migration hasn't run (no server restart required)
- Wrap DELETE in its own try/except
- Catch and print outer exceptions so failures appear in server logs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-26 22:52:30 +02:00
parent c3b83ba1d3
commit 3e699d61b6

View File

@@ -719,11 +719,28 @@ def _fetch_popular_task(channel_id: int, youtube_channel_id: str):
# Phase 1: store with basic info and write popular ranks immediately
db = SessionLocal()
try:
# Ensure table exists regardless of whether startup migration ran
db.execute(text("""
CREATE TABLE IF NOT EXISTS channel_popular_videos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id INTEGER NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
rank INTEGER NOT NULL,
fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(channel_id, video_id)
)
"""))
db.commit()
channel = db.query(Channel).filter_by(id=channel_id).first()
if not channel:
return
try:
db.execute(text("DELETE FROM channel_popular_videos WHERE channel_id = :cid"), {"cid": channel_id})
db.commit()
except Exception:
db.rollback()
for rank, entry in enumerate(entries, start=1):
yt_id = entry["id"]
@@ -754,6 +771,9 @@ def _fetch_popular_task(channel_id: int, youtube_channel_id: str):
db.commit()
except Exception:
db.rollback()
except Exception as e:
print(f"[popular] task error: {e}", flush=True)
db.rollback()
finally:
db.close()