team-1/backend/src/song.py
2025-08-01 23:07:00 +02:00

56 lines
1.4 KiB
Python

from dataclasses import dataclass
from sqlite3 import Cursor
from .connect import get_connection
def init_db(db: Cursor):
db.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
);
""")
@dataclass(frozen=True)
class Song:
mbid: str
title: str
artist: str
tags: list[str]
image_id: str
youtube_id: str
def get_song_by_mbid(mbid: str) -> Song | None:
conn = get_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM songs WHERE mbid = ?", (mbid,))
row = cursor.fetchone()
conn.close()
if row is None:
return None
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
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()