database.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import sqlite3
  2. import os
  3. import logging
  4. import secrets
  5. from datetime import datetime, timedelta
  6. from typing import Optional, Dict, Any, List
  7. logger = logging.getLogger(__name__)
  8. # Locate db correctly in the same directory
  9. DB_PATH = os.path.join(os.path.dirname(__file__), "localfood.db")
  10. def get_db_connection():
  11. # Enable higher timeout and disable thread checks for FastAPI async compatibility
  12. conn = sqlite3.connect(DB_PATH, timeout=30.0, check_same_thread=False)
  13. conn.row_factory = sqlite3.Row
  14. # Enable Write-Ahead Log (WAL) mode for simultaneous read/write operations
  15. conn.execute('PRAGMA journal_mode=WAL')
  16. conn.execute('PRAGMA synchronous=NORMAL')
  17. return conn
  18. def create_tables():
  19. """Initialize the SQLite database with required tables"""
  20. conn = None
  21. try:
  22. conn = get_db_connection()
  23. cursor = conn.cursor()
  24. # Create users table securely locally
  25. cursor.execute('''
  26. CREATE TABLE IF NOT EXISTS users (
  27. id INTEGER PRIMARY KEY AUTOINCREMENT,
  28. username TEXT UNIQUE NOT NULL,
  29. password_hash TEXT NOT NULL,
  30. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  31. )
  32. ''')
  33. # Create sessions table for database-backed tokens
  34. cursor.execute('''
  35. CREATE TABLE IF NOT EXISTS sessions (
  36. token TEXT PRIMARY KEY,
  37. user_id INTEGER NOT NULL,
  38. expires_at TIMESTAMP NOT NULL,
  39. FOREIGN KEY (user_id) REFERENCES users (id)
  40. )
  41. ''')
  42. # Create localized foods table based on Sprint 5 architecture
  43. cursor.execute('''
  44. CREATE TABLE IF NOT EXISTS foods (
  45. id INTEGER PRIMARY KEY AUTOINCREMENT,
  46. name TEXT NOT NULL,
  47. category TEXT,
  48. base_weight_g REAL DEFAULT 100.0,
  49. calories REAL DEFAULT 0.0,
  50. protein_g REAL DEFAULT 0.0,
  51. fat_g REAL DEFAULT 0.0,
  52. carbs_g REAL DEFAULT 0.0,
  53. fiber_g REAL DEFAULT 0.0,
  54. sugar_g REAL DEFAULT 0.0,
  55. sodium_mg REAL DEFAULT 0.0,
  56. vitamin_a_iu REAL DEFAULT 0.0,
  57. vitamin_c_mg REAL DEFAULT 0.0,
  58. calcium_mg REAL DEFAULT 0.0,
  59. iron_mg REAL DEFAULT 0.0,
  60. potassium_mg REAL DEFAULT 0.0,
  61. cholesterol_mg REAL DEFAULT 0.0,
  62. source TEXT DEFAULT 'System'
  63. )
  64. ''')
  65. # Create chat history table for Sprint 6 persistence
  66. cursor.execute('''
  67. CREATE TABLE IF NOT EXISTS chat_messages (
  68. id INTEGER PRIMARY KEY AUTOINCREMENT,
  69. user_id INTEGER NOT NULL,
  70. role TEXT NOT NULL,
  71. content TEXT NOT NULL,
  72. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  73. FOREIGN KEY (user_id) REFERENCES users (id)
  74. )
  75. ''')
  76. # Create minimal user_profiles table for macro targets (US-07)
  77. cursor.execute('''
  78. CREATE TABLE IF NOT EXISTS user_profiles (
  79. user_id INTEGER PRIMARY KEY,
  80. target_calories INTEGER DEFAULT 2000,
  81. target_protein_g INTEGER DEFAULT 150,
  82. target_carbs_g INTEGER DEFAULT 200,
  83. target_fat_g INTEGER DEFAULT 65,
  84. FOREIGN KEY (user_id) REFERENCES users (id)
  85. )
  86. ''')
  87. # Create user-named meals table for Sprint 8
  88. cursor.execute('''
  89. CREATE TABLE IF NOT EXISTS saved_meals (
  90. id INTEGER PRIMARY KEY AUTOINCREMENT,
  91. user_id INTEGER NOT NULL,
  92. name TEXT NOT NULL,
  93. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  94. FOREIGN KEY (user_id) REFERENCES users (id)
  95. )
  96. ''')
  97. # Create meal items table to link multiple foods to a single saved meal
  98. cursor.execute('''
  99. CREATE TABLE IF NOT EXISTS meal_items (
  100. id INTEGER PRIMARY KEY AUTOINCREMENT,
  101. meal_id INTEGER NOT NULL,
  102. food_id INTEGER NOT NULL,
  103. amount_g REAL NOT NULL,
  104. FOREIGN KEY (meal_id) REFERENCES saved_meals (id) ON DELETE CASCADE,
  105. FOREIGN KEY (food_id) REFERENCES foods (id)
  106. )
  107. ''')
  108. # Create index for rapid fuzzy search compatibility
  109. cursor.execute('CREATE INDEX IF NOT EXISTS idx_food_name ON foods(name COLLATE NOCASE)')
  110. cursor.execute('CREATE INDEX IF NOT EXISTS idx_saved_meals_user ON saved_meals(user_id)')
  111. conn.commit()
  112. logger.info("Database and tables initialized successfully.")
  113. except Exception as e:
  114. logger.error(f"Error initializing database: {e}")
  115. raise
  116. finally:
  117. if conn:
  118. conn.close()
  119. def save_user_meal(user_id: int, name: str, items: List[Dict[str, Any]]) -> Optional[int]:
  120. """Persist a collection of food items as a named meal list for a user"""
  121. conn = None
  122. try:
  123. conn = get_db_connection()
  124. cursor = conn.cursor()
  125. # 1. Create the meal header
  126. cursor.execute(
  127. "INSERT INTO saved_meals (user_id, name) VALUES (?, ?)",
  128. (user_id, name)
  129. )
  130. meal_id = cursor.lastrowid
  131. # 2. Add each item linked to this meal
  132. for item in items:
  133. cursor.execute(
  134. "INSERT INTO meal_items (meal_id, food_id, amount_g) VALUES (?, ?, ?)",
  135. (meal_id, item['food_id'], item['amount_g'])
  136. )
  137. conn.commit()
  138. return meal_id
  139. except Exception as e:
  140. logger.error(f"Error saving user meal: {e}")
  141. if conn: conn.rollback()
  142. return None
  143. finally:
  144. if conn: conn.close()
  145. def update_user_meal(user_id: int, meal_id: int, name: str) -> bool:
  146. """Update the name of a user's saved meal, verifying ownership."""
  147. conn = None
  148. try:
  149. conn = get_db_connection()
  150. cursor = conn.cursor()
  151. cursor.execute(
  152. "UPDATE saved_meals SET name = ? WHERE id = ? AND user_id = ?",
  153. (name, meal_id, user_id)
  154. )
  155. success = cursor.rowcount > 0
  156. conn.commit()
  157. return success
  158. except Exception as e:
  159. logger.error(f"Error updating user meal: {e}")
  160. if conn: conn.rollback()
  161. return False
  162. finally:
  163. if conn: conn.close()
  164. def delete_user_meal(user_id: int, meal_id: int) -> bool:
  165. """Delete a user's saved meal and its items, verifying ownership."""
  166. conn = None
  167. try:
  168. conn = get_db_connection()
  169. cursor = conn.cursor()
  170. # Verify ownership and get the meal ID
  171. cursor.execute("SELECT id FROM saved_meals WHERE id = ? AND user_id = ?", (meal_id, user_id))
  172. if not cursor.fetchone():
  173. return False
  174. # Manually delete items first to handle missing PRAGMA foreign_keys
  175. cursor.execute("DELETE FROM meal_items WHERE meal_id = ?", (meal_id,))
  176. cursor.execute("DELETE FROM saved_meals WHERE id = ? AND user_id = ?", (meal_id, user_id))
  177. success = cursor.rowcount > 0
  178. conn.commit()
  179. return success
  180. except Exception as e:
  181. logger.error(f"Error deleting user meal: {e}")
  182. if conn: conn.rollback()
  183. return False
  184. finally:
  185. if conn: conn.close()
  186. def get_user_meals(user_id: int) -> List[Dict[str, Any]]:
  187. """Retrieve all saved meals for a user, including total nutritional calculations"""
  188. conn = None
  189. try:
  190. conn = get_db_connection()
  191. cursor = conn.cursor()
  192. # 1. Get all meals for this user
  193. cursor.execute("SELECT id, name, created_at FROM saved_meals WHERE user_id = ? ORDER BY created_at DESC", (user_id,))
  194. meals = [dict(row) for row in cursor.fetchall()]
  195. # 2. For each meal, get the items and calculate totals
  196. for meal in meals:
  197. cursor.execute('''
  198. SELECT mi.amount_g, f.calories, f.protein_g, f.fat_g, f.carbs_g
  199. FROM meal_items mi
  200. JOIN foods f ON mi.food_id = f.id
  201. WHERE mi.meal_id = ?
  202. ''', (meal['id'],))
  203. items = cursor.fetchall()
  204. # Calculate totals based on weight (database stores per 100g)
  205. total_cals = 0.0
  206. total_protein = 0.0
  207. total_fat = 0.0
  208. total_carbs = 0.0
  209. for item in items:
  210. ratio = item['amount_g'] / 100.0
  211. total_cals += item['calories'] * ratio
  212. total_protein += item['protein_g'] * ratio
  213. total_fat += item['fat_g'] * ratio
  214. total_carbs += item['carbs_g'] * ratio
  215. meal['total_calories'] = round(total_cals, 1)
  216. meal['total_protein_g'] = round(total_protein, 1)
  217. meal['total_fat_g'] = round(total_fat, 1)
  218. meal['total_carbs_g'] = round(total_carbs, 1)
  219. return meals
  220. except Exception as e:
  221. logger.error(f"Error fetching user meals: {e}")
  222. return []
  223. finally:
  224. if conn: conn.close()
  225. def get_user_by_username(username: str) -> Optional[Dict[str, Any]]:
  226. """Retrieve user dictionary if they exist"""
  227. conn = None
  228. try:
  229. conn = get_db_connection()
  230. cursor = conn.cursor()
  231. cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
  232. row = cursor.fetchone()
  233. return dict(row) if row else None
  234. except Exception as e:
  235. logger.error(f"Database error fetching user: {e}")
  236. return None
  237. finally:
  238. if conn: conn.close()
  239. def create_user(username: str, password_hash: str) -> Optional[int]:
  240. """Creates a user securely. Returns user_id if successful, None if username exists."""
  241. conn = None
  242. try:
  243. conn = get_db_connection()
  244. cursor = conn.cursor()
  245. cursor.execute(
  246. "INSERT INTO users (username, password_hash) VALUES (?, ?)",
  247. (username, password_hash)
  248. )
  249. user_id = cursor.lastrowid
  250. conn.commit()
  251. return user_id
  252. except sqlite3.IntegrityError:
  253. return None
  254. except Exception as e:
  255. logger.error(f"Database error during user creation: {e}")
  256. raise
  257. finally:
  258. if conn: conn.close()
  259. def create_session(user_id: int) -> str:
  260. """Create a secure 32-character session token in the DB valid for 7 days"""
  261. token = secrets.token_urlsafe(32)
  262. expires_at = datetime.now() + timedelta(days=7)
  263. conn = None
  264. try:
  265. conn = get_db_connection()
  266. cursor = conn.cursor()
  267. cursor.execute(
  268. "INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)",
  269. (token, user_id, expires_at)
  270. )
  271. conn.commit()
  272. return token
  273. except Exception as e:
  274. logger.error(f"Error creating session: {e}")
  275. raise
  276. finally:
  277. if conn: conn.close()
  278. def get_user_from_token(token: str) -> Optional[Dict[str, Any]]:
  279. """Verify a session token and return the associated user data if valid and not expired"""
  280. conn = None
  281. try:
  282. conn = get_db_connection()
  283. cursor = conn.cursor()
  284. # Find user if token exists and hasn't expired
  285. cursor.execute('''
  286. SELECT users.* FROM users
  287. JOIN sessions ON users.id = sessions.user_id
  288. WHERE sessions.token = ? AND sessions.expires_at > ?
  289. ''', (token, datetime.now()))
  290. row = cursor.fetchone()
  291. return dict(row) if row else None
  292. except Exception as e:
  293. logger.error(f"Database error verifying token: {e}")
  294. return None
  295. finally:
  296. if conn: conn.close()
  297. def delete_session(token: str):
  298. """Securely remove a session token when the user logs out"""
  299. conn = None
  300. try:
  301. conn = get_db_connection()
  302. cursor = conn.cursor()
  303. cursor.execute("DELETE FROM sessions WHERE token = ?", (token,))
  304. conn.commit()
  305. except Exception as e:
  306. logger.error(f"Error deleting session: {e}")
  307. finally:
  308. if conn: conn.close()
  309. def search_foods_by_name(query: str, limit: int = 15) -> list[Dict[str, Any]]:
  310. """Securely search for foods matching a string query with relevance-based ordering"""
  311. conn = None
  312. try:
  313. conn = get_db_connection()
  314. cursor = conn.cursor()
  315. # SQL Injection safe query utilizing LIKE parameterization
  316. # We prioritize:
  317. # 1. Items NOT in 'Baby Foods'
  318. # 2. Shorter names (usually more fundamental ingredients)
  319. # 3. Alphabetical order as a tie-breaker
  320. q = f"%{query}%"
  321. prefix_match = f"{query}%"
  322. cursor.execute('''
  323. SELECT * FROM foods
  324. WHERE name LIKE ?
  325. ORDER BY
  326. CASE WHEN category = 'Baby Foods' THEN 1 ELSE 0 END,
  327. CASE WHEN name LIKE ? THEN 0 ELSE 1 END,
  328. LENGTH(name) ASC,
  329. name ASC
  330. LIMIT ?
  331. ''', (q, prefix_match, limit))
  332. rows = cursor.fetchall()
  333. return [dict(row) for row in rows]
  334. except Exception as e:
  335. logger.error(f"Error searching foods: {e}")
  336. return []
  337. finally:
  338. if conn: conn.close()
  339. def save_chat_message(user_id: int, role: str, content: str):
  340. """Persist a chat message to the database"""
  341. conn = None
  342. try:
  343. conn = get_db_connection()
  344. cursor = conn.cursor()
  345. cursor.execute(
  346. "INSERT INTO chat_messages (user_id, role, content) VALUES (?, ?, ?)",
  347. (user_id, role, content)
  348. )
  349. conn.commit()
  350. except Exception as e:
  351. logger.error(f"Error saving chat message: {e}")
  352. finally:
  353. if conn: conn.close()
  354. def get_user_chat_history(user_id: int, limit: int = 50) -> list[Dict[str, Any]]:
  355. """Retrieve the most recent chat messages for a user"""
  356. conn = None
  357. try:
  358. conn = get_db_connection()
  359. cursor = conn.cursor()
  360. # Order by created_at DESC to get recent ones, then reverse for display
  361. cursor.execute('''
  362. SELECT role, content FROM chat_messages
  363. WHERE user_id = ?
  364. ORDER BY created_at ASC
  365. LIMIT ?
  366. ''', (user_id, limit))
  367. rows = cursor.fetchall()
  368. return [dict(row) for row in rows]
  369. except Exception as e:
  370. logger.error(f"Error fetching chat history: {e}")
  371. return []
  372. finally:
  373. if conn: conn.close()
  374. def get_user_profile(user_id: int) -> Optional[Dict[str, Any]]:
  375. """Fetch the user's profile containing macro targets. Inserts defaults if none exists."""
  376. conn = None
  377. try:
  378. conn = get_db_connection()
  379. cursor = conn.cursor()
  380. cursor.execute("SELECT * FROM user_profiles WHERE user_id = ?", (user_id,))
  381. row = cursor.fetchone()
  382. if not row:
  383. # Create a default profile row if one does not exist
  384. cursor.execute('''
  385. INSERT INTO user_profiles (user_id) VALUES (?)
  386. ''', (user_id,))
  387. conn.commit()
  388. cursor.execute("SELECT * FROM user_profiles WHERE user_id = ?", (user_id,))
  389. row = cursor.fetchone()
  390. return dict(row) if row else None
  391. except Exception as e:
  392. logger.error(f"Error fetching user profile: {e}")
  393. return None
  394. finally:
  395. if conn: conn.close()
  396. def get_food_by_id(food_id: int) -> Optional[Dict[str, Any]]:
  397. """Retrieve a single food item by its unique ID"""
  398. conn = None
  399. try:
  400. conn = get_db_connection()
  401. cursor = conn.cursor()
  402. cursor.execute("SELECT * FROM foods WHERE id = ?", (food_id,))
  403. row = cursor.fetchone()
  404. return dict(row) if row else None
  405. except Exception as e:
  406. logger.error(f"Error fetching food by ID {food_id}: {e}")
  407. return None
  408. finally:
  409. if conn: conn.close()
  410. def get_foods_by_ids(food_ids: List[int]) -> List[Dict[str, Any]]:
  411. """Retrieve multiple food items by their unique IDs in bulk"""
  412. if not food_ids:
  413. return []
  414. conn = None
  415. try:
  416. conn = get_db_connection()
  417. cursor = conn.cursor()
  418. # Create placeholders for the IN clause
  419. placeholders = ', '.join(['?'] * len(food_ids))
  420. query = f"SELECT * FROM foods WHERE id IN ({placeholders})"
  421. cursor.execute(query, food_ids)
  422. rows = cursor.fetchall()
  423. return [dict(row) for row in rows]
  424. except Exception as e:
  425. logger.error(f"Error fetching foods by IDs {food_ids}: {e}")
  426. return []
  427. finally:
  428. if conn: conn.close()