Add song listing endpoints
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
from duckdb import connect
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
DB_PATH = Path("./data/data.duckdb").absolute()
|
||||
SQL_PATH = Path("./lib/database.sql").absolute()
|
||||
SEED_JSON_PATH = Path("./lib/seed_data.json").absolute()
|
||||
COUNTRYCODES_JSON_PATH = Path("./lib/countrycodes.json").absolute()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_connection():
|
||||
conn = connect(DB_PATH)
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def seed_db() -> None:
|
||||
with open(SEED_JSON_PATH, "r") as f:
|
||||
data = json.load(f)
|
||||
|
||||
if not data:
|
||||
return
|
||||
|
||||
for idx, item in enumerate(data):
|
||||
item["running_order"] = idx + 1
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO Song (year, artist, country, title, lyrics_url, artist_url, flag_url, running_order, lyrics_original, lyrics_translation_fi, tags, confidence, language) VALUES (2025, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(
|
||||
item["artist"],
|
||||
item["country"],
|
||||
item["title"],
|
||||
item["lyrics_url"],
|
||||
item["artist_url"],
|
||||
item["flag_url"],
|
||||
item["running_order"],
|
||||
item["lyrics_original"],
|
||||
item["lyrics_translation_fi"],
|
||||
item["tags"],
|
||||
item["confidence"],
|
||||
item["language"],
|
||||
),
|
||||
)
|
||||
|
||||
with open(COUNTRYCODES_JSON_PATH, "r") as f:
|
||||
data = json.load(f)
|
||||
|
||||
if not data:
|
||||
return
|
||||
|
||||
for item in data:
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO CountryCodes (code, name_en, name_fi) VALUES (?, ?, ?)",
|
||||
(
|
||||
item["code"],
|
||||
item["name_en"],
|
||||
item["name_fi"],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def init_db():
|
||||
with open(SQL_PATH, "r") as f:
|
||||
sql = f.read()
|
||||
with get_connection() as conn:
|
||||
conn.execute(sql)
|
||||
seed_db()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
init_db()
|
||||
Reference in New Issue
Block a user