database.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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_by_username(username: str) -> Optional[Dict[str, Any]]:
  187. """Retrieve user dictionary if they exist"""
  188. conn = None
  189. try:
  190. conn = get_db_connection()
  191. cursor = conn.cursor()
  192. cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
  193. row = cursor.fetchone()
  194. return dict(row) if row else None
  195. except Exception as e:
  196. logger.error(f"Database error fetching user: {e}")
  197. return None
  198. finally:
  199. if conn: conn.close()
  200. def create_user(username: str, password_hash: str) -> Optional[int]:
  201. """Creates a user securely. Returns user_id if successful, None if username exists."""
  202. conn = None
  203. try:
  204. conn = get_db_connection()
  205. cursor = conn.cursor()
  206. cursor.execute(
  207. "INSERT INTO users (username, password_hash) VALUES (?, ?)",
  208. (username, password_hash)
  209. )
  210. user_id = cursor.lastrowid
  211. conn.commit()
  212. return user_id
  213. except sqlite3.IntegrityError:
  214. return None
  215. except Exception as e:
  216. logger.error(f"Database error during user creation: {e}")
  217. raise
  218. finally:
  219. if conn: conn.close()
  220. def create_session(user_id: int) -> str:
  221. """Create a secure 32-character session token in the DB valid for 7 days"""
  222. token = secrets.token_urlsafe(32)
  223. expires_at = datetime.now() + timedelta(days=7)
  224. conn = None
  225. try:
  226. conn = get_db_connection()
  227. cursor = conn.cursor()
  228. cursor.execute(
  229. "INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)",
  230. (token, user_id, expires_at)
  231. )
  232. conn.commit()
  233. return token
  234. except Exception as e:
  235. logger.error(f"Error creating session: {e}")
  236. raise
  237. finally:
  238. if conn: conn.close()
  239. def get_user_from_token(token: str) -> Optional[Dict[str, Any]]:
  240. """Verify a session token and return the associated user data if valid and not expired"""
  241. conn = None
  242. try:
  243. conn = get_db_connection()
  244. cursor = conn.cursor()
  245. # Find user if token exists and hasn't expired
  246. cursor.execute('''
  247. SELECT users.* FROM users
  248. JOIN sessions ON users.id = sessions.user_id
  249. WHERE sessions.token = ? AND sessions.expires_at > ?
  250. ''', (token, datetime.now()))
  251. row = cursor.fetchone()
  252. return dict(row) if row else None
  253. except Exception as e:
  254. logger.error(f"Database error verifying token: {e}")
  255. return None
  256. finally:
  257. if conn: conn.close()
  258. def delete_session(token: str):
  259. """Securely remove a session token when the user logs out"""
  260. conn = None
  261. try:
  262. conn = get_db_connection()
  263. cursor = conn.cursor()
  264. cursor.execute("DELETE FROM sessions WHERE token = ?", (token,))
  265. conn.commit()
  266. except Exception as e:
  267. logger.error(f"Error deleting session: {e}")
  268. finally:
  269. if conn: conn.close()
  270. def search_foods_by_name(query: str, limit: int = 15) -> list[Dict[str, Any]]:
  271. """Securely search for foods matching a string query with relevance-based ordering"""
  272. conn = None
  273. try:
  274. conn = get_db_connection()
  275. cursor = conn.cursor()
  276. # SQL Injection safe query utilizing LIKE parameterization
  277. # We prioritize:
  278. # 1. Items NOT in 'Baby Foods'
  279. # 2. Shorter names (usually more fundamental ingredients)
  280. # 3. Alphabetical order as a tie-breaker
  281. q = f"%{query}%"
  282. prefix_match = f"{query}%"
  283. cursor.execute('''
  284. SELECT * FROM foods
  285. WHERE name LIKE ?
  286. ORDER BY
  287. CASE WHEN category = 'Baby Foods' THEN 1 ELSE 0 END,
  288. CASE WHEN name LIKE ? THEN 0 ELSE 1 END,
  289. LENGTH(name) ASC,
  290. name ASC
  291. LIMIT ?
  292. ''', (q, prefix_match, limit))
  293. rows = cursor.fetchall()
  294. return [dict(row) for row in rows]
  295. except Exception as e:
  296. logger.error(f"Error searching foods: {e}")
  297. return []
  298. finally:
  299. if conn: conn.close()
  300. def save_chat_message(user_id: int, role: str, content: str):
  301. """Persist a chat message to the database"""
  302. conn = None
  303. try:
  304. conn = get_db_connection()
  305. cursor = conn.cursor()
  306. cursor.execute(
  307. "INSERT INTO chat_messages (user_id, role, content) VALUES (?, ?, ?)",
  308. (user_id, role, content)
  309. )
  310. conn.commit()
  311. except Exception as e:
  312. logger.error(f"Error saving chat message: {e}")
  313. finally:
  314. if conn: conn.close()
  315. def get_user_chat_history(user_id: int, limit: int = 50) -> list[Dict[str, Any]]:
  316. """Retrieve the most recent chat messages for a user"""
  317. conn = None
  318. try:
  319. conn = get_db_connection()
  320. cursor = conn.cursor()
  321. # Order by created_at DESC to get recent ones, then reverse for display
  322. cursor.execute('''
  323. SELECT role, content FROM chat_messages
  324. WHERE user_id = ?
  325. ORDER BY created_at ASC
  326. LIMIT ?
  327. ''', (user_id, limit))
  328. rows = cursor.fetchall()
  329. return [dict(row) for row in rows]
  330. except Exception as e:
  331. logger.error(f"Error fetching chat history: {e}")
  332. return []
  333. finally:
  334. if conn: conn.close()
  335. def get_user_profile(user_id: int) -> Optional[Dict[str, Any]]:
  336. """Fetch the user's profile containing macro targets. Inserts defaults if none exists."""
  337. conn = None
  338. try:
  339. conn = get_db_connection()
  340. cursor = conn.cursor()
  341. cursor.execute("SELECT * FROM user_profiles WHERE user_id = ?", (user_id,))
  342. row = cursor.fetchone()
  343. if not row:
  344. # Create a default profile row if one does not exist
  345. cursor.execute('''
  346. INSERT INTO user_profiles (user_id) VALUES (?)
  347. ''', (user_id,))
  348. conn.commit()
  349. cursor.execute("SELECT * FROM user_profiles WHERE user_id = ?", (user_id,))
  350. row = cursor.fetchone()
  351. return dict(row) if row else None
  352. except Exception as e:
  353. logger.error(f"Error fetching user profile: {e}")
  354. return None
  355. finally:
  356. if conn: conn.close()
  357. def get_food_by_id(food_id: int) -> Optional[Dict[str, Any]]:
  358. """Retrieve a single food item by its unique ID"""
  359. conn = None
  360. try:
  361. conn = get_db_connection()
  362. cursor = conn.cursor()
  363. cursor.execute("SELECT * FROM foods WHERE id = ?", (food_id,))
  364. row = cursor.fetchone()
  365. return dict(row) if row else None
  366. except Exception as e:
  367. logger.error(f"Error fetching food by ID {food_id}: {e}")
  368. return None
  369. finally:
  370. if conn: conn.close()
  371. def get_foods_by_ids(food_ids: List[int]) -> List[Dict[str, Any]]:
  372. """Retrieve multiple food items by their unique IDs in bulk"""
  373. if not food_ids:
  374. return []
  375. conn = None
  376. try:
  377. conn = get_db_connection()
  378. cursor = conn.cursor()
  379. # Create placeholders for the IN clause
  380. placeholders = ', '.join(['?'] * len(food_ids))
  381. query = f"SELECT * FROM foods WHERE id IN ({placeholders})"
  382. cursor.execute(query, food_ids)
  383. rows = cursor.fetchall()
  384. return [dict(row) for row in rows]
  385. except Exception as e:
  386. logger.error(f"Error fetching foods by IDs {food_ids}: {e}")
  387. return []
  388. finally:
  389. if conn: conn.close()