104 lines
2.8 KiB
Python
104 lines
2.8 KiB
Python
from duckdb import connect
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
import json
|
|
from dotenv import load_dotenv
|
|
import os
|
|
|
|
from lib.helpers import hash_password
|
|
|
|
load_dotenv()
|
|
|
|
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:
|
|
# Seed Songs
|
|
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"],
|
|
),
|
|
)
|
|
|
|
# Seed CountryCodes
|
|
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"],
|
|
),
|
|
)
|
|
|
|
# Seed Teams
|
|
with get_connection() as conn:
|
|
conn.execute("INSERT INTO Team (name) VALUES (?)", ("Pontus",))
|
|
|
|
# Seed Admin users
|
|
admin_username = os.getenv("ADMIN_USERNAME")
|
|
hashed_admin_password = hash_password(os.getenv("ADMIN_PASSWORD"))
|
|
with get_connection() as conn:
|
|
conn.execute(
|
|
'INSERT INTO "User" (username, hashed_password, team_id, is_active, is_admin) VALUES (?, ?, ?, ?, ?)',
|
|
(
|
|
admin_username,
|
|
hashed_admin_password,
|
|
1,
|
|
True,
|
|
True,
|
|
),
|
|
)
|
|
|
|
|
|
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()
|