63 lines
1.8 KiB
Python
63 lines
1.8 KiB
Python
|
|
from typing import List, ClassVar
|
||
|
|
from pydantic import BaseModel
|
||
|
|
from person import Person
|
||
|
|
|
||
|
|
import datetime
|
||
|
|
|
||
|
|
class Meal(BaseModel):
|
||
|
|
KEYS: ClassVar[List[str]] = ['id', 'date']
|
||
|
|
id: int
|
||
|
|
date: datetime.datetime
|
||
|
|
chef: List[Person] = []
|
||
|
|
cleanup: List[Person] = []
|
||
|
|
consumers: List[Person] = []
|
||
|
|
recipes: List[Person] = []
|
||
|
|
|
||
|
|
async def create(conn):
|
||
|
|
await conn.execute('''
|
||
|
|
CREATE TABLE IF NOT EXISTS Meal (
|
||
|
|
id INTEGER PRIMARY KEY,
|
||
|
|
date TEXT UNIQUE
|
||
|
|
);''')
|
||
|
|
|
||
|
|
await conn.execute('''
|
||
|
|
CREATE TABLE IF NOT EXISTS MealParticipant (
|
||
|
|
meal_id INTEGER,
|
||
|
|
person_id INTEGER,
|
||
|
|
role TEXT,
|
||
|
|
FOREIGN KEY(meal_id) REFERENCES Meal(id),
|
||
|
|
FOREIGN KEY(person_id) REFERENCES Person(id)
|
||
|
|
);''')
|
||
|
|
|
||
|
|
await conn.execute('''
|
||
|
|
CREATE TABLE IF NOT EXISTS MealRecipe (
|
||
|
|
meal_id INTEGER,
|
||
|
|
recipe_id INTEGER,
|
||
|
|
FOREIGN KEY(meal_id) REFERENCES Meal(id),
|
||
|
|
FOREIGN KEY(recipe_id) REFERENCES Recipe(id)
|
||
|
|
);''')
|
||
|
|
|
||
|
|
async def insert_meal(conn, meal: Meal):
|
||
|
|
async with conn.execute('''
|
||
|
|
INSERT INTO Meal (date)
|
||
|
|
VALUES (?)
|
||
|
|
''', (meal.date,)) as cursor:
|
||
|
|
return cursor.lastrowid
|
||
|
|
|
||
|
|
async def find_meal_by_id(conn, meal_id: int) -> Meal:
|
||
|
|
async with conn.execute(f'''
|
||
|
|
SELECT {','.join(Meal.KEYS)} FROM Meal
|
||
|
|
WHERE id = ?
|
||
|
|
LIMIT 1
|
||
|
|
''', (meal_id,)) as cursor:
|
||
|
|
async for row in cursor:
|
||
|
|
return Meal(**{k:v for k,v in zip(Meal.KEYS, row)})
|
||
|
|
|
||
|
|
async def find_meal_by_date(conn, date: datetime) -> Meal:
|
||
|
|
async with conn.execute(f'''
|
||
|
|
SELECT {','.join(Meal.KEYS)} FROM Meal
|
||
|
|
WHERE date = ?
|
||
|
|
LIMIT 1
|
||
|
|
''', (date,)) as cursor:
|
||
|
|
async for row in cursor:
|
||
|
|
return Meal(**{k:v for k,v in zip(Meal.KEYS, row)})
|