team-1/backend/src/song.py

59 lines
1.5 KiB
Python
Raw Normal View History

2025-08-01 18:46:38 +02:00
from dataclasses import dataclass
2025-08-01 19:16:20 +02:00
from .connect import get_connection
2025-08-01 19:02:50 +02:00
def init_db():
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS songs (
mbid TEXT PRIMARY KEY,
title TEXT NOT NULL,
artist TEXT NOT NULL,
tags TEXT NOT NULL,
lastfm_image_id TEXT NOT NULL,
youtube_id TEXT NOT NULL
);
""")
conn.commit()
conn.close()
2025-08-01 18:46:38 +02:00
@dataclass
class Song:
mbid: str
title: str
artist: str
tags: list[str]
image_id: str
youtube_id: str
2025-08-01 21:21:28 +02:00
def get_song_by_mbid(mbid: str) -> Song:
conn = get_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM songs WHERE mbid = ?", (mbid,))
row = cursor.fetchone()
conn.close()
if row is None:
raise ValueError(f"Song with MBID {mbid} not found")
song = Song(mbid=row["mbid"], title=row["title"], artist=row["artist"], tags=row["tags"].split(","), image_id=row["lastfm_image_id"], youtube_id=row["youtube_id"])
return song
2025-08-01 21:31:53 +02:00
def add_song(song: Song):
conn = get_connection()
cursor = conn.cursor()
cursor.execute(
"""
INSERT OR REPLACE INTO songs (mbid, title, artist, tags, lastfm_image_id, youtube_id)
VALUES (?, ?, ?, ?, ?, ?)
""",
(song.mbid, song.title, song.artist, ",".join(song.tags), song.image_id, song.youtube_id),
) # Updates song info if it already exists
conn.commit()
conn.close()