|
|
@@ -94,8 +94,32 @@ def create_tables():
|
|
|
)
|
|
|
''')
|
|
|
|
|
|
+ # Create user-named meals table for Sprint 8
|
|
|
+ cursor.execute('''
|
|
|
+ CREATE TABLE IF NOT EXISTS saved_meals (
|
|
|
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
+ user_id INTEGER NOT NULL,
|
|
|
+ name TEXT NOT NULL,
|
|
|
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
|
+ FOREIGN KEY (user_id) REFERENCES users (id)
|
|
|
+ )
|
|
|
+ ''')
|
|
|
+
|
|
|
+ # Create meal items table to link multiple foods to a single saved meal
|
|
|
+ cursor.execute('''
|
|
|
+ CREATE TABLE IF NOT EXISTS meal_items (
|
|
|
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
+ meal_id INTEGER NOT NULL,
|
|
|
+ food_id INTEGER NOT NULL,
|
|
|
+ amount_g REAL NOT NULL,
|
|
|
+ FOREIGN KEY (meal_id) REFERENCES saved_meals (id) ON DELETE CASCADE,
|
|
|
+ FOREIGN KEY (food_id) REFERENCES foods (id)
|
|
|
+ )
|
|
|
+ ''')
|
|
|
+
|
|
|
# Create index for rapid fuzzy search compatibility
|
|
|
cursor.execute('CREATE INDEX IF NOT EXISTS idx_food_name ON foods(name COLLATE NOCASE)')
|
|
|
+ cursor.execute('CREATE INDEX IF NOT EXISTS idx_saved_meals_user ON saved_meals(user_id)')
|
|
|
|
|
|
conn.commit()
|
|
|
logger.info("Database and tables initialized successfully.")
|
|
|
@@ -105,6 +129,36 @@ def create_tables():
|
|
|
finally:
|
|
|
if conn:
|
|
|
conn.close()
|
|
|
+def save_user_meal(user_id: int, name: str, items: List[Dict[str, Any]]) -> Optional[int]:
|
|
|
+ """Persist a collection of food items as a named meal list for a user"""
|
|
|
+ conn = None
|
|
|
+ try:
|
|
|
+ conn = get_db_connection()
|
|
|
+ cursor = conn.cursor()
|
|
|
+
|
|
|
+ # 1. Create the meal header
|
|
|
+ cursor.execute(
|
|
|
+ "INSERT INTO saved_meals (user_id, name) VALUES (?, ?)",
|
|
|
+ (user_id, name)
|
|
|
+ )
|
|
|
+ meal_id = cursor.lastrowid
|
|
|
+
|
|
|
+ # 2. Add each item linked to this meal
|
|
|
+ for item in items:
|
|
|
+ cursor.execute(
|
|
|
+ "INSERT INTO meal_items (meal_id, food_id, amount_g) VALUES (?, ?, ?)",
|
|
|
+ (meal_id, item['food_id'], item['amount_g'])
|
|
|
+ )
|
|
|
+
|
|
|
+ conn.commit()
|
|
|
+ return meal_id
|
|
|
+ except Exception as e:
|
|
|
+ logger.error(f"Error saving user meal: {e}")
|
|
|
+ if conn: conn.rollback()
|
|
|
+ return None
|
|
|
+ finally:
|
|
|
+ if conn: conn.close()
|
|
|
+
|
|
|
|
|
|
def get_user_by_username(username: str) -> Optional[Dict[str, Any]]:
|
|
|
"""Retrieve user dictionary if they exist"""
|