-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.py
More file actions
402 lines (355 loc) · 13.4 KB
/
Copy pathdb.py
File metadata and controls
402 lines (355 loc) · 13.4 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
"""SQLite database for scale measurements."""
import sqlite3
from contextlib import contextmanager
from datetime import datetime, timedelta
from typing import Iterator
from config import DATABASE_PATH
@contextmanager
def get_connection() -> Iterator[sqlite3.Connection]:
"""Context manager for database connections."""
conn = sqlite3.connect(DATABASE_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL") # Non-blocking reads
try:
yield conn
finally:
conn.close()
def init_db() -> None:
"""Initialize database with schema."""
with get_connection() as conn:
conn.executescript("""
CREATE TABLE IF NOT EXISTS raw_packets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
packet_hex TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS profiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
min_weight_kg REAL,
max_weight_kg REAL,
height_cm INTEGER,
age INTEGER,
gender TEXT
);
CREATE TABLE IF NOT EXISTS measurements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
profile_id INTEGER,
weight_kg REAL NOT NULL,
impedance_raw INTEGER,
impedance_ohm REAL,
body_fat_pct REAL,
fat_mass_kg REAL,
lean_mass_kg REAL,
body_water_pct REAL,
muscle_mass_kg REAL,
bone_mass_kg REAL,
bmr_kcal INTEGER,
bmi REAL,
FOREIGN KEY (profile_id) REFERENCES profiles(id)
);
CREATE INDEX IF NOT EXISTS idx_measurements_timestamp
ON measurements(timestamp);
CREATE INDEX IF NOT EXISTS idx_measurements_profile_id
ON measurements(profile_id);
""")
conn.commit()
def migrate_db() -> None:
"""Run database migrations for existing databases."""
with get_connection() as conn:
# Check if profiles table exists
cursor = conn.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name='profiles'"
)
if not cursor.fetchone():
conn.execute("""
CREATE TABLE profiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
min_weight_kg REAL,
max_weight_kg REAL,
height_cm INTEGER,
age INTEGER,
gender TEXT
)
""")
# Check for weight columns in profiles (migration from scale_user_id)
cursor = conn.execute("PRAGMA table_info(profiles)")
columns = {row[1] for row in cursor.fetchall()}
if "min_weight_kg" not in columns:
conn.execute("ALTER TABLE profiles ADD COLUMN min_weight_kg REAL")
if "max_weight_kg" not in columns:
conn.execute("ALTER TABLE profiles ADD COLUMN max_weight_kg REAL")
# Check if profile_id column exists in measurements
cursor = conn.execute("PRAGMA table_info(measurements)")
columns = {row[1] for row in cursor.fetchall()}
if "profile_id" not in columns:
conn.execute("ALTER TABLE measurements ADD COLUMN profile_id INTEGER")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_measurements_profile_id ON measurements(profile_id)"
)
conn.commit()
# Profile CRUD functions
def get_profiles() -> list[dict]:
"""Get all profiles."""
with get_connection() as conn:
rows = conn.execute(
"SELECT * FROM profiles ORDER BY id"
).fetchall()
return [dict(row) for row in rows]
def get_profile(profile_id: int) -> dict | None:
"""Get a single profile by ID."""
with get_connection() as conn:
row = conn.execute(
"SELECT * FROM profiles WHERE id = ?", (profile_id,)
).fetchone()
return dict(row) if row else None
def save_profile(
name: str,
min_weight_kg: float | None = None,
max_weight_kg: float | None = None,
height_cm: int | None = None,
age: int | None = None,
gender: str | None = None,
profile_id: int | None = None,
) -> int:
"""Create or update a profile. Returns the profile ID."""
with get_connection() as conn:
if profile_id:
conn.execute(
"""
UPDATE profiles SET name = ?, min_weight_kg = ?, max_weight_kg = ?,
height_cm = ?, age = ?, gender = ?
WHERE id = ?
""",
(name, min_weight_kg, max_weight_kg, height_cm, age, gender, profile_id),
)
conn.commit()
return profile_id
else:
cursor = conn.execute(
"""
INSERT INTO profiles (name, min_weight_kg, max_weight_kg, height_cm, age, gender)
VALUES (?, ?, ?, ?, ?, ?)
""",
(name, min_weight_kg, max_weight_kg, height_cm, age, gender),
)
conn.commit()
return cursor.lastrowid or 0
def delete_profile(profile_id: int) -> None:
"""Delete a profile."""
with get_connection() as conn:
conn.execute("DELETE FROM profiles WHERE id = ?", (profile_id,))
conn.commit()
def save_raw_packet(packet_hex: str) -> int:
"""Save raw packet data and return the row ID."""
with get_connection() as conn:
cursor = conn.execute(
"INSERT INTO raw_packets (packet_hex) VALUES (?)",
(packet_hex,),
)
conn.commit()
return cursor.lastrowid or 0
def save_measurement(
weight_kg: float,
impedance_raw: int | None = None,
impedance_ohm: float | None = None,
body_fat_pct: float | None = None,
fat_mass_kg: float | None = None,
lean_mass_kg: float | None = None,
body_water_pct: float | None = None,
muscle_mass_kg: float | None = None,
bone_mass_kg: float | None = None,
bmr_kcal: int | None = None,
bmi: float | None = None,
) -> int:
"""Save a measurement and return the row ID."""
with get_connection() as conn:
cursor = conn.execute(
"""
INSERT INTO measurements (
weight_kg, impedance_raw, impedance_ohm, body_fat_pct,
fat_mass_kg, lean_mass_kg, body_water_pct, muscle_mass_kg,
bone_mass_kg, bmr_kcal, bmi
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
weight_kg,
impedance_raw,
impedance_ohm,
body_fat_pct,
fat_mass_kg,
lean_mass_kg,
body_water_pct,
muscle_mass_kg,
bone_mass_kg,
bmr_kcal,
bmi,
),
)
conn.commit()
return cursor.lastrowid or 0
def get_latest_measurement(profile_id: int | None = None) -> dict | None:
"""Get the most recent measurement, optionally filtered by profile."""
with get_connection() as conn:
if profile_id is not None:
row = conn.execute(
"""
SELECT m.*, p.name as profile_name
FROM measurements m
LEFT JOIN profiles p ON m.profile_id = p.id
WHERE m.profile_id = ?
ORDER BY m.timestamp DESC LIMIT 1
""",
(profile_id,),
).fetchone()
else:
row = conn.execute(
"""
SELECT m.*, p.name as profile_name
FROM measurements m
LEFT JOIN profiles p ON m.profile_id = p.id
ORDER BY m.timestamp DESC LIMIT 1
"""
).fetchone()
return dict(row) if row else None
def get_measurements(limit: int = 10, profile_id: int | None = None) -> list[dict]:
"""Get recent measurements, newest first, optionally filtered by profile."""
with get_connection() as conn:
if profile_id is not None:
rows = conn.execute(
"""
SELECT m.*, p.name as profile_name
FROM measurements m
LEFT JOIN profiles p ON m.profile_id = p.id
WHERE m.profile_id = ?
ORDER BY m.timestamp DESC LIMIT ?
""",
(profile_id, limit),
).fetchall()
else:
rows = conn.execute(
"""
SELECT m.*, p.name as profile_name
FROM measurements m
LEFT JOIN profiles p ON m.profile_id = p.id
ORDER BY m.timestamp DESC LIMIT ?
""",
(limit,),
).fetchall()
return [dict(row) for row in rows]
def get_measurements_since(days: int = 30, profile_id: int | None = None) -> list[dict]:
"""Get measurements from the last N days, oldest first (for charting)."""
cutoff = datetime.now() - timedelta(days=days)
with get_connection() as conn:
if profile_id is not None:
rows = conn.execute(
"""
SELECT m.*, p.name as profile_name
FROM measurements m
LEFT JOIN profiles p ON m.profile_id = p.id
WHERE m.timestamp >= ? AND m.profile_id = ?
ORDER BY m.timestamp ASC
""",
(cutoff.isoformat(), profile_id),
).fetchall()
else:
rows = conn.execute(
"""
SELECT m.*, p.name as profile_name
FROM measurements m
LEFT JOIN profiles p ON m.profile_id = p.id
WHERE m.timestamp >= ?
ORDER BY m.timestamp ASC
""",
(cutoff.isoformat(),),
).fetchall()
return [dict(row) for row in rows]
def get_measurements_between(
start_date: str | None = None,
end_date: str | None = None,
profile_id: int | None = None,
) -> list[dict]:
"""Get measurements between two dates, oldest first (for charting).
Dates should be ISO format strings (YYYY-MM-DD). If start_date is None,
no lower bound is applied. If end_date is None, no upper bound is applied.
"""
conditions = []
params: list = []
if profile_id is not None:
conditions.append("m.profile_id = ?")
params.append(profile_id)
if start_date:
conditions.append("m.timestamp >= ?")
params.append(start_date)
if end_date:
# Include the full end day by comparing with the next day
conditions.append("m.timestamp < ?")
params.append(end_date + "T23:59:59")
where = "WHERE " + " AND ".join(conditions) if conditions else ""
with get_connection() as conn:
rows = conn.execute(
f"""
SELECT m.*, p.name as profile_name
FROM measurements m
LEFT JOIN profiles p ON m.profile_id = p.id
{where}
ORDER BY m.timestamp ASC
""",
params,
).fetchall()
return [dict(row) for row in rows]
def get_last_measurement_time() -> datetime | None:
"""Get timestamp of the most recent measurement (for debouncing)."""
with get_connection() as conn:
row = conn.execute(
"SELECT timestamp FROM measurements ORDER BY timestamp DESC LIMIT 1"
).fetchone()
if row:
return datetime.fromisoformat(row["timestamp"])
return None
def recalculate_profile_measurements(profile_id: int) -> int:
"""Recalculate body composition for all measurements of a profile.
Call this when profile height/age/gender changes.
Returns count of updated measurements.
"""
from decode import calculate_body_composition
profile = get_profile(profile_id)
if not profile:
return 0
if not all([profile.get("height_cm"), profile.get("age"), profile.get("gender")]):
return 0
with get_connection() as conn:
rows = conn.execute(
"SELECT id, weight_kg, impedance_ohm FROM measurements "
"WHERE profile_id = ? AND impedance_ohm IS NOT NULL",
(profile_id,),
).fetchall()
for row in rows:
comp = calculate_body_composition(
weight_kg=row["weight_kg"],
impedance_ohm=row["impedance_ohm"],
height_cm=profile["height_cm"],
age=profile["age"],
gender=profile["gender"],
)
conn.execute(
"""UPDATE measurements SET
body_fat_pct=?, fat_mass_kg=?, lean_mass_kg=?, body_water_pct=?,
muscle_mass_kg=?, bone_mass_kg=?, bmr_kcal=?, bmi=?
WHERE id=?""",
(
comp.body_fat_pct,
comp.fat_mass_kg,
comp.lean_mass_kg,
comp.body_water_pct,
comp.muscle_mass_kg,
comp.bone_mass_kg,
comp.bmr_kcal,
comp.bmi,
row["id"],
),
)
conn.commit()
return len(rows)