munch-ease-backend/ingredients/db.py

161 lines
4.9 KiB
Python
Raw Normal View History

2025-10-18 03:26:42 +00:00
from typing import Any, AsyncIterator, ClassVar, List, Optional
from pydantic import BaseModel, field_validator
2024-01-17 07:21:16 +00:00
from products import Product
class Ingredient(BaseModel):
2025-10-18 03:26:42 +00:00
KEYS: ClassVar[List[str]] = [
"id",
"name",
"line",
"preparation",
"unit",
"quantity",
"product_id",
"recipe_id",
"meal_id",
]
2024-05-20 10:09:57 +00:00
id: int = -1
2024-01-17 07:21:16 +00:00
name: str
line: str
unit: str
2025-10-18 03:26:42 +00:00
quantity: float | str
2024-01-17 07:21:16 +00:00
preparation: str
product_id: Optional[int] = None
recipe_id: Optional[int] = None
meal_id: Optional[int] = None
product: Optional[Product] = None
2024-01-17 07:21:16 +00:00
2025-10-18 03:26:42 +00:00
# Ensure quantity is stored as a float even if provided as a string in tests
@field_validator("quantity", mode="before")
@classmethod
def _coerce_quantity(cls, v: Any) -> Any:
if isinstance(v, str):
try:
return float(v)
except ValueError:
return v
return v
2024-01-17 07:21:16 +00:00
async def create(conn):
2025-10-18 03:26:42 +00:00
await conn.execute(
"""
2024-01-17 07:21:16 +00:00
CREATE TABLE IF NOT EXISTS Ingredient (
id INTEGER PRIMARY KEY,
name TEXT,
line TEXT,
preparation TEXT,
unit TEXT,
quantity REAL,
product_id INTEGER,
recipe_id INTEGER,
meal_id INTEGER,
FOREIGN KEY (product_id) REFERENCES Product(id),
FOREIGN KEY (recipe_id) REFERENCES Recipe(id),
FOREIGN KEY (meal_id) REFERENCES Meal(id)
2025-10-18 03:26:42 +00:00
);"""
)
2024-01-17 07:21:16 +00:00
async def insert_ingredient(conn, ingredient: Ingredient):
2024-05-20 10:09:57 +00:00
if ingredient.product:
2024-04-25 04:57:39 +00:00
ingredient.product_id = ingredient.product.id
2025-07-30 08:19:20 +00:00
if ingredient.product_id is None or ingredient.product_id < 0:
ingredient.product_id = None
2024-04-25 04:57:39 +00:00
2025-10-18 03:26:42 +00:00
async with conn.execute(
"""
2024-01-17 07:21:16 +00:00
INSERT INTO Ingredient (name, line, preparation, unit, quantity, product_id, recipe_id, meal_id)
2024-01-17 08:36:54 +00:00
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
2025-10-18 03:26:42 +00:00
""",
(
ingredient.name,
ingredient.line,
ingredient.preparation,
ingredient.unit,
ingredient.quantity,
ingredient.product_id,
ingredient.recipe_id,
ingredient.meal_id,
),
) as cursor:
2024-01-17 07:21:16 +00:00
ingredient.id = cursor.lastrowid
2025-10-18 03:26:42 +00:00
2025-07-30 08:19:20 +00:00
async def find_ingredient_by_id(conn, ingredient_id: int) -> Optional[Ingredient]:
2025-10-18 03:26:42 +00:00
ingredient_cols = [f"ingredient.{key}" for key in Ingredient.KEYS]
product_cols = [f"product.{key}" for key in Product.KEYS]
2025-07-30 08:19:20 +00:00
2025-10-18 03:26:42 +00:00
async with conn.execute(
f"""
SELECT {','.join(ingredient_cols + product_cols)} FROM Ingredient
2025-07-30 08:19:20 +00:00
LEFT JOIN Product ON Ingredient.product_id = Product.id
2025-07-30 08:55:51 +00:00
WHERE Ingredient.id = ?
2025-10-18 03:26:42 +00:00
""",
(ingredient_id,),
) as cursor:
2025-07-30 08:19:20 +00:00
async for row in cursor:
2025-10-18 03:26:42 +00:00
product_map = {k: v for k, v in zip(Product.KEYS, row[len(Ingredient.KEYS) :])}
product = Product(**product_map) if product_map["id"] else None
return Ingredient(
**{k: v for k, v in zip(Ingredient.KEYS, row[: len(Ingredient.KEYS)])},
product=product,
)
2025-07-30 08:19:20 +00:00
return None
2025-10-18 03:26:42 +00:00
2024-05-13 03:59:46 +00:00
async def find_ingredients_by_recipe_id(conn, recipe_id: int) -> AsyncIterator[Ingredient]:
2025-10-18 03:26:42 +00:00
ingredient_cols = [f"ingredient.{key}" for key in Ingredient.KEYS]
product_cols = [f"product.{key}" for key in Product.KEYS]
2025-10-18 03:26:42 +00:00
async with conn.execute(
f"""
SELECT {','.join(ingredient_cols + product_cols)} FROM Ingredient
LEFT JOIN Product ON Ingredient.product_id = Product.id
2024-01-17 07:21:16 +00:00
WHERE recipe_id = ?
2025-10-18 03:26:42 +00:00
""",
(recipe_id,),
) as cursor:
2024-01-17 07:21:16 +00:00
async for row in cursor:
2025-10-18 03:26:42 +00:00
product_map = {k: v for k, v in zip(Product.KEYS, row[len(Ingredient.KEYS) :])}
product = Product(**product_map) if product_map["id"] else None
yield Ingredient(
**{k: v for k, v in zip(Ingredient.KEYS, row[: len(Ingredient.KEYS)])},
product=product,
)
2024-01-17 07:21:16 +00:00
2024-05-13 03:59:46 +00:00
async def find_ingredients_by_meal_id(conn, meal_id: int) -> AsyncIterator[Ingredient]:
2025-10-18 03:26:42 +00:00
ingredient_cols = [f"ingredient.{key}" for key in Ingredient.KEYS]
product_cols = [f"product.{key}" for key in Product.KEYS]
2025-10-18 03:26:42 +00:00
async with conn.execute(
f"""
SELECT {','.join(ingredient_cols + product_cols)} FROM Ingredient
LEFT JOIN Product ON Ingredient.product_id = Product.id
2024-01-17 07:21:16 +00:00
WHERE meal_id = ?
2025-10-18 03:26:42 +00:00
""",
(meal_id,),
) as cursor:
2024-01-17 07:21:16 +00:00
async for row in cursor:
2025-10-18 03:26:42 +00:00
product_map = {k: v for k, v in zip(Product.KEYS, row[len(Ingredient.KEYS) :])}
product = Product(**product_map) if product_map["id"] else None
yield Ingredient(
**{k: v for k, v in zip(Ingredient.KEYS, row[: len(Ingredient.KEYS)])},
product=product,
)
2024-05-02 11:20:52 +00:00
async def delete_ingredients_by_meal_id(conn, meal_id: int):
2025-10-18 03:26:42 +00:00
await conn.execute(
"""
2024-05-02 11:20:52 +00:00
DELETE FROM Ingredient
WHERE meal_id = ?
2025-10-18 03:26:42 +00:00
""",
(meal_id,),
)