Guest User

recipes

a guest
Jul 14th, 2025
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.79 KB | None | 0 0
  1. import sqlite3
  2.  
  3. # Connect to DB with autocommit mode
  4. conn = sqlite3.connect("meal_ingredients.db", isolation_level=None)
  5.  
  6. # Ensure tables exist
  7. conn.execute("PRAGMA foreign_keys = ON")
  8. conn.execute("CREATE TABLE IF NOT EXISTS meals (name TEXT) STRICT")
  9. conn.execute(
  10. """
  11. CREATE TABLE IF NOT EXISTS ingredients (
  12. name TEXT,
  13. meal_id INTEGER,
  14. FOREIGN KEY(meal_id) REFERENCES meals(rowid)
  15. ) STRICT
  16. """
  17. )
  18. res = conn.execute("SELECT * FROM sqlite_schema WHERE name = 'meals'").fetchone()
  19. print(res)
  20.  
  21. # Main loop
  22. while True:
  23. try:
  24. user_input = input("> ").strip()
  25.  
  26. # Exit
  27. if user_input.lower() == "quit":
  28. break
  29.  
  30. # Add new meal
  31. elif ":" in user_input:
  32. meal_name, ingredients_list = map(str.strip, user_input.split(":", 1))
  33. ingredients = [i.strip() for i in ingredients_list.split(",") if i.strip()]
  34.  
  35. if not meal_name or not ingredients:
  36. print("Invalid format. Use: meal:ingredient1,ingredient2,...")
  37. continue
  38.  
  39. # Insert meal
  40. conn.execute("INSERT INTO meals (name) VALUES (?)", (meal_name,))
  41. meal_id = conn.execute(
  42. "SELECT rowid FROM meals WHERE name = ?", (meal_name,)
  43. ).fetchone()[0]
  44.  
  45. # Insert ingredients
  46. for ingredient in ingredients:
  47. conn.execute(
  48. "INSERT INTO ingredients (name, meal_id) VALUES (?, ?)",
  49. (ingredient, meal_id),
  50. )
  51.  
  52. print(f"Meal added: {meal_name}")
  53.  
  54. else:
  55. # Try to treat input as a meal name
  56. ingredients = conn.execute(
  57. """
  58. SELECT ingredients.name
  59. FROM meals
  60. INNER JOIN ingredients ON meals.rowid = ingredients.meal_id
  61. WHERE meals.name = ?
  62. """,
  63. (user_input,),
  64. ).fetchall()
  65.  
  66. if ingredients:
  67. print(f"Ingredients of {user_input}:")
  68. for ing in ingredients:
  69. print(f" {ing[0]}")
  70. continue
  71.  
  72. # Try to treat input as an ingredient
  73. meals = conn.execute(
  74. """
  75. SELECT meals.name
  76. FROM meals
  77. INNER JOIN ingredients ON meals.rowid = ingredients.meal_id
  78. WHERE ingredients.name = ?
  79. """,
  80. (user_input,),
  81. ).fetchall()
  82.  
  83. if meals:
  84. print(f"Meals that use {user_input}:")
  85. for meal in meals:
  86. print(f" {meal[0]}")
  87. else:
  88. print("Not found.")
  89.  
  90. except Exception as e:
  91. print(f"Error: {e}")
  92.  
Advertisement
Add Comment
Please, Sign In to add comment