-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
285 lines (244 loc) · 8.67 KB
/
Copy pathdatabase.py
File metadata and controls
285 lines (244 loc) · 8.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"""
Database module for MusicFlow application.
Supports both PostgreSQL (Supabase) and SQLite.
"""
import os
from datetime import datetime
from typing import Optional
from urllib.parse import urlparse
import config
# Determine which database to use
USE_POSTGRES = bool(config.DATABASE_URL and config.DATABASE_URL.startswith('postgresql'))
if USE_POSTGRES:
import psycopg2
from psycopg2.extras import RealDictCursor
else:
import sqlite3
def get_db_connection():
"""Get a database connection."""
if USE_POSTGRES:
conn = psycopg2.connect(config.DATABASE_URL)
return conn
else:
conn = sqlite3.connect(config.DATABASE_PATH)
conn.row_factory = sqlite3.Row
return conn
def get_cursor(conn):
"""Get a cursor with appropriate row factory."""
if USE_POSTGRES:
return conn.cursor(cursor_factory=RealDictCursor)
else:
return conn.cursor()
def placeholder():
"""Return the appropriate placeholder for the database."""
return '%s' if USE_POSTGRES else '?'
def init_database():
"""
Initialize the database schema.
Creates users, oauth_tokens, and tracks tables if they don't exist.
"""
conn = get_db_connection()
cursor = get_cursor(conn)
if USE_POSTGRES:
# PostgreSQL schema
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
email TEXT,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS oauth_tokens (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
provider TEXT NOT NULL,
access_token TEXT NOT NULL,
refresh_token TEXT,
expires_at BIGINT,
scope TEXT,
updated_at TEXT NOT NULL,
UNIQUE(user_id, provider)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS tracks (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
track_id TEXT NOT NULL,
track_name TEXT NOT NULL,
artists TEXT NOT NULL,
album TEXT,
duration_ms INTEGER NOT NULL,
played_at TEXT NOT NULL,
played_at_timestamp TEXT NOT NULL,
stored_at TEXT NOT NULL,
UNIQUE(user_id, track_id, played_at_timestamp)
)
''')
# Create indexes
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_oauth_tokens_user_provider
ON oauth_tokens(user_id, provider)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_tracks_user_id
ON tracks(user_id)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_tracks_played_at
ON tracks(played_at_timestamp)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_tracks_track_id
ON tracks(track_id)
''')
else:
# SQLite schema
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS oauth_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
provider TEXT NOT NULL,
access_token TEXT NOT NULL,
refresh_token TEXT,
expires_at INTEGER,
scope TEXT,
updated_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id),
UNIQUE(user_id, provider)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS tracks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
track_id TEXT NOT NULL,
track_name TEXT NOT NULL,
artists TEXT NOT NULL,
album TEXT,
duration_ms INTEGER NOT NULL,
played_at TEXT NOT NULL,
played_at_timestamp TEXT NOT NULL,
stored_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id),
UNIQUE(user_id, track_id, played_at_timestamp)
)
''')
# Create indexes
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_oauth_tokens_user_provider
ON oauth_tokens(user_id, provider)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_tracks_user_id
ON tracks(user_id)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_tracks_played_at
ON tracks(played_at_timestamp)
''')
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_tracks_track_id
ON tracks(track_id)
''')
# Add email column if it doesn't exist (migration for existing installs)
try:
if USE_POSTGRES:
cursor.execute('''
ALTER TABLE users ADD COLUMN IF NOT EXISTS email TEXT
''')
else:
# SQLite doesn't have IF NOT EXISTS for ALTER TABLE, check manually
cursor.execute("PRAGMA table_info(users)")
columns = [col[1] for col in cursor.fetchall()]
if 'email' not in columns:
cursor.execute('ALTER TABLE users ADD COLUMN email TEXT')
conn.commit()
except Exception as e:
print(f"Note: email column migration: {e}")
conn.commit()
cursor.close()
conn.close()
# Migrate from old spotify_tracks.db if it exists (SQLite only)
if not USE_POSTGRES:
migrate_from_old_db()
def migrate_from_old_db():
"""Migrate data from old spotify_tracks.db to the new database."""
old_db_path = 'spotify_tracks.db'
if not os.path.exists(old_db_path) or old_db_path == config.DATABASE_PATH:
return
print(f"Found old database at {old_db_path}, migrating...")
try:
old_conn = sqlite3.connect(old_db_path)
old_conn.row_factory = sqlite3.Row
old_cursor = old_conn.cursor()
old_cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='tracks'")
if not old_cursor.fetchone():
old_conn.close()
return
old_cursor.execute('SELECT * FROM tracks')
old_tracks = old_cursor.fetchall()
if not old_tracks:
old_conn.close()
return
new_conn = get_db_connection()
new_cursor = get_cursor(new_conn)
migrated_count = 0
p = placeholder()
for track in old_tracks:
try:
new_cursor.execute(f'''
INSERT INTO tracks
(track_id, track_name, artists, album, duration_ms, played_at, played_at_timestamp, stored_at)
VALUES ({p}, {p}, {p}, {p}, {p}, {p}, {p}, {p})
ON CONFLICT DO NOTHING
''', (
track['track_id'],
track['track_name'],
track['artists'],
track['album'],
track['duration_ms'],
track['played_at'],
track['played_at_timestamp'],
track['stored_at']
))
migrated_count += 1
except Exception as e:
print(f"Error migrating track: {e}")
continue
new_conn.commit()
new_cursor.close()
new_conn.close()
old_conn.close()
print(f"Migrated {migrated_count} tracks from old database.")
backup_path = old_db_path + '.backup'
os.rename(old_db_path, backup_path)
print(f"Old database backed up to {backup_path}")
except Exception as e:
print(f"Error during migration: {e}")
def assign_legacy_tracks_to_user(user_id: int):
"""Assign tracks with NULL user_id to a specific user."""
conn = get_db_connection()
cursor = get_cursor(conn)
p = placeholder()
cursor.execute(f'UPDATE tracks SET user_id = {p} WHERE user_id IS NULL', (user_id,))
if USE_POSTGRES:
updated_count = cursor.rowcount
else:
updated_count = cursor.rowcount
conn.commit()
cursor.close()
conn.close()
return updated_count