druvx13 commited on
Commit
cdf6435
·
verified ·
1 Parent(s): df0cffd

Create database.py

Browse files
Files changed (1) hide show
  1. database.py +57 -0
database.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # database.py — SQLite helpers for the Gradio music player
2
+ import sqlite3
3
+ from pathlib import Path
4
+
5
+ DB_PATH = Path(__file__).parent / "music_player.db"
6
+
7
+
8
+ def init_db() -> None:
9
+ """Create the songs table if it doesn't exist."""
10
+ with sqlite3.connect(DB_PATH) as conn:
11
+ conn.execute("""
12
+ CREATE TABLE IF NOT EXISTS songs (
13
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
14
+ title TEXT NOT NULL,
15
+ artist TEXT NOT NULL DEFAULT 'Unknown Artist',
16
+ file TEXT NOT NULL,
17
+ cover TEXT,
18
+ lyrics TEXT,
19
+ uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
20
+ )
21
+ """)
22
+ conn.commit()
23
+
24
+
25
+ def fetch_songs() -> list[dict]:
26
+ """Return all songs ordered by upload date (newest first)."""
27
+ with sqlite3.connect(DB_PATH) as conn:
28
+ conn.row_factory = sqlite3.Row
29
+ rows = conn.execute(
30
+ "SELECT id, title, artist, file, cover, lyrics "
31
+ "FROM songs ORDER BY uploaded_at DESC"
32
+ ).fetchall()
33
+ return [dict(r) for r in rows]
34
+
35
+
36
+ def insert_song(
37
+ title: str,
38
+ artist: str,
39
+ file_path: str,
40
+ cover_path: str | None,
41
+ lyrics: str,
42
+ ) -> dict:
43
+ """Insert a new song row and return the full inserted record."""
44
+ with sqlite3.connect(DB_PATH) as conn:
45
+ cur = conn.execute(
46
+ "INSERT INTO songs (title, artist, file, cover, lyrics) "
47
+ "VALUES (?, ?, ?, ?, ?)",
48
+ (title, artist, file_path, cover_path, lyrics),
49
+ )
50
+ new_id = cur.lastrowid
51
+ conn.commit()
52
+ row = conn.execute(
53
+ "SELECT id, title, artist, file, cover, lyrics "
54
+ "FROM songs WHERE id = ?",
55
+ (new_id,),
56
+ ).fetchone()
57
+ return dict(row) if row else {}