fix: drop the recipe cook_time column and use perform_time (#9011)

This commit is contained in:
Hayden authored and GitHub committed 2026-11-05 15:35:20 +00:00
1 parent d064343388
commit 0afeeb34fc
13 files changed
+165 -16

No files matched your search

-1
View File
@@ -30,7 +30,6 @@ def recipe_data(name: str, slug: str, id: str, userId: str, groupId: str) -> dic
"recipeYield": "9 servings",
"totalTime": "33 Minutes",
"prepTime": "20 Minutes",
"cookTime": None,
"performTime": "13 Minutes",
"description": "These Levain Bakery-Style Peanut Butter Cookies are the ULTIMATE for serious PB lovers! Supremely thick and chewy with gooey centers and a soft texture, they're packed with peanut butter flavor and Reese's Pieces for the most amazing cookie ever!",
"recipeCategory": [],
-2
View File
@@ -435,7 +435,6 @@ export interface Recipe {
recipeYield?: string | null;
totalTime?: string | null;
prepTime?: string | null;
cookTime?: string | null;
performTime?: string | null;
totalTimeSeconds?: number | null;
prepTimeSeconds?: number | null;
@@ -739,7 +738,6 @@ export interface RecipeSummary {
recipeYield?: string | null;
totalTime?: string | null;
prepTime?: string | null;
cookTime?: string | null;
performTime?: string | null;
totalTimeSeconds?: number | null;
prepTimeSeconds?: number | null;
+1 -1
View File
@@ -82,6 +82,7 @@ export interface ReadPlanEntry {
userId: string;
householdId: string;
recipe?: RecipeSummary | null;
updatedAt?: string | null;
}
export interface RecipeSummary {
id?: string | null;
@@ -96,7 +97,6 @@ export interface RecipeSummary {
recipeYield?: string | null;
totalTime?: string | null;
prepTime?: string | null;
cookTime?: string | null;
performTime?: string | null;
totalTimeSeconds?: number | null;
prepTimeSeconds?: number | null;
-3
View File
@@ -270,7 +270,6 @@ export interface Recipe {
recipeYield?: string | null;
totalTime?: string | null;
prepTime?: string | null;
cookTime?: string | null;
performTime?: string | null;
totalTimeSeconds?: number | null;
prepTimeSeconds?: number | null;
@@ -370,7 +369,6 @@ export interface RecipeSummary {
recipeYield?: string | null;
totalTime?: string | null;
prepTime?: string | null;
cookTime?: string | null;
performTime?: string | null;
totalTimeSeconds?: number | null;
prepTimeSeconds?: number | null;
@@ -415,7 +413,6 @@ export interface RecipeIn {
recipeYield?: string | null;
totalTime?: string | null;
prepTime?: string | null;
cookTime?: string | null;
performTime?: string | null;
totalTimeSeconds?: number | null;
prepTimeSeconds?: number | null;
@@ -0,0 +1,52 @@
"""drop recipe cook_time
Revision ID: 127804c19431
Revises: 071e03b4f851
Create Date: 2026-11-05 08:59:52.000000
`perform_time` is the recipe's cook time everywhere: the UI labels it "Cook Time" and every importer
maps schema.org `cookTime` into it. `cook_time` was a leftover column that nothing wrote, so exports
and the iCal feed showed an empty cook time (#7938).
Old rows can still hold a value only in `cook_time`. It moves into `perform_time` as text when the
recipe has no cook time of its own, then the column goes away.
"""
import sqlalchemy as sa
from sqlalchemy import text
from alembic import op
from mealie.core.root_logger import get_logger
# revision identifiers, used by Alembic.
revision = "127804c19431"
down_revision: str | None = "071e03b4f851"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# "none" is what old scrapers wrote for a zero-length time; it isn't worth keeping
result = op.get_bind().execute(
text(
"""
UPDATE recipes SET perform_time = cook_time
WHERE (perform_time IS NULL OR TRIM(perform_time) = '')
AND perform_time_seconds IS NULL
AND cook_time IS NOT NULL
AND TRIM(cook_time) != ''
AND LOWER(TRIM(cook_time)) != 'none'
"""
)
)
get_logger().info("Moved %s legacy recipe cook times into perform_time", result.rowcount)
with op.batch_alter_table("recipes", schema=None) as batch_op:
batch_op.drop_column("cook_time")
def downgrade():
# The moved values stay in perform_time, which is where older versions read the cook time from
with op.batch_alter_table("recipes", schema=None) as batch_op:
batch_op.add_column(sa.Column("cook_time", sa.String(), nullable=True))
-1
View File
@@ -180,7 +180,6 @@ class RecipeModel(SqlAlchemyBase, BaseMixins):
)
# Deprecated
cook_time: Mapped[str | None] = mapped_column(sa.String)
# Kept as a query-filter anchor until aliases can be defined without a model column.
last_made: FilterableColumn[datetime | None] = mapped_column(NaiveDateTime)
recipeCuisine: Mapped[str | None] = mapped_column(sa.String)
+17 -3
View File
@@ -6,7 +6,7 @@ from pathlib import Path
from typing import Annotated, Any, ClassVar
from uuid import uuid4
from pydantic import UUID4, BaseModel, ConfigDict, Field, field_validator
from pydantic import UUID4, BaseModel, ConfigDict, Field, field_validator, model_validator
from pydantic_core.core_schema import ValidationInfo
from slugify import slugify
from sqlalchemy import Select, desc, func, or_, select, text, union
@@ -187,7 +187,6 @@ class RecipeSummary(MealieModel):
total_time: str | None = None
prep_time: str | None = None
cook_time: str | None = None
perform_time: str | None = None
total_time_seconds: DurationSeconds | None = None
prep_time_seconds: DurationSeconds | None = None
@@ -207,11 +206,26 @@ class RecipeSummary(MealieModel):
updated_at: datetime.datetime | None = UpdatedAtField(None)
model_config = ConfigDict(from_attributes=True)
@model_validator(mode="before")
@classmethod
def accept_legacy_cook_time(cls, data: Any) -> Any:
"""Reads `cookTime` from older clients and exports as `performTime`, which replaced it."""
if not isinstance(data, dict):
return data
cook_time = data.get("cookTime") or data.get("cook_time")
has_perform_time = any(
data.get(key) for key in ("performTime", "perform_time", "performTimeSeconds", "perform_time_seconds")
)
if cook_time and not has_perform_time:
data = {**data, "performTime": cook_time}
return data
@field_validator("recipe_servings", "recipe_yield_quantity", mode="before")
def clean_numbers(val: Any):
return val or 0
@field_validator("recipe_yield", "total_time", "prep_time", "cook_time", "perform_time", mode="before")
@field_validator("recipe_yield", "total_time", "prep_time", "perform_time", mode="before")
def clean_strings(val: Any):
if val is None:
return val
@@ -219,7 +219,7 @@ class MealPlanICalService(BaseService):
"description": recipe.description or "",
"totalTime": recipe.total_time or "",
"prepTime": recipe.prep_time or "",
"cookTime": recipe.cook_time or "",
"cookTime": recipe.perform_time or "",
"tags": ", ".join(tag.name for tag in recipe.tags or []),
"categories": ", ".join(category.name for category in recipe.recipe_category or []),
"tools": ", ".join(tool.name for tool in recipe.tools),
-1
View File
@@ -145,7 +145,6 @@ def test_spa_recipe_json_times(unique_user: TestUser):
perform_time_seconds=3600,
# Free text isn't a valid schema.org duration, so it's left out
prep_time="a while",
cook_time="PT10M",
)
response = spa.content_with_meta(unique_user.group_id, recipe)
@@ -473,7 +473,6 @@ def test_create_recipe_from_zip_reimport_preserves_contents(api_client: TestClie
"recipeCategory": [category],
"tags": [tag],
"tools": [tool],
"cookTime": "PT15M",
"rating": 4,
"nutrition": {"calories": "350", "proteinContent": "25"},
"notes": [{"title": "Tip", "text": "Rest before serving.", "referenceId": note_reference_id}],
@@ -531,7 +530,6 @@ def test_create_recipe_from_zip_reimport_preserves_contents(api_client: TestClie
"totalTime",
"prepTime",
"performTime",
"cookTime",
"rating",
"orgURL",
"extras",
+18 -1
View File
@@ -99,7 +99,7 @@ def test_recipe_duration_bounds(field: str, val: Any, expected: Any):
assert getattr(recipe, field) == expected
@pytest.mark.parametrize("field", ["recipe_yield", "total_time", "prep_time", "cook_time", "perform_time"])
@pytest.mark.parametrize("field", ["recipe_yield", "total_time", "prep_time", "perform_time"])
@pytest.mark.parametrize(
["val", "expected"],
[
@@ -172,3 +172,20 @@ def test_recipe_preserves_existing_slug():
)
assert recipe.slug == "nourish-bowls-zuppa-copycat"
@pytest.mark.parametrize(
["payload", "expected"],
[
({"cookTime": "20 minutes"}, "20 minutes"),
({"cook_time": "20 minutes"}, "20 minutes"),
({"cookTime": "1 hour", "performTime": "20 minutes"}, "20 minutes"),
({"cookTime": "1 hour", "performTimeSeconds": 1200}, None),
({"cookTime": None}, None),
],
)
def test_recipe_legacy_cook_time_input(payload: dict[str, Any], expected: str | None):
recipe = Recipe.model_validate({"name": "Soup", **payload})
assert recipe.perform_time == expected
assert "cookTime" not in recipe.model_dump(by_alias=True)
@@ -83,3 +83,20 @@ def test_last_modified_uses_latest_of_entry_and_recipe():
entry.updated_at = datetime(2026, 1, 4, 12, 0, tzinfo=UTC)
feed = service.build_calendar([entry], MealPlanICalQuery(), tzlocal(), "Mealie", "group")
assert "LAST-MODIFIED:20260104T120000Z\r\n" in feed
def test_merge_fields_cook_time_comes_from_perform_time():
recipe = RecipeSummary(name="Soup", slug="soup", perform_time="20 minutes")
entry = ReadPlanEntry(
id=1,
date=date(2026, 1, 3),
entry_type="dinner",
recipe_id=uuid4(),
group_id=uuid4(),
user_id=uuid4(),
household_id=uuid4(),
recipe=recipe,
)
service = MealPlanICalService(None, StubTranslator()) # type: ignore[arg-type]
assert service._merge_fields(entry, None)["cookTime"] == "20 minutes"
@@ -0,0 +1,59 @@
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
from tests.utils.alembic_reader import ALEMBIC_MIGRATIONS, import_file
def _migration():
path = next(ALEMBIC_MIGRATIONS.glob("*127804c19431*.py"))
return import_file("drop_recipe_cook_time", path)
ROWS = [
# id, perform_time, perform_time_seconds, cook_time
("only-cook-time", None, None, "20 minutes"),
("blank-perform-time", " ", None, "PT15M"),
("has-perform-time", "10 minutes", None, "1 hour"),
("has-perform-seconds", None, 600, "1 hour"),
("cook-time-none", None, None, " None "),
("cook-time-blank", None, None, " "),
("nothing", None, None, None),
]
def test_migration_moves_legacy_cook_time_and_drops_column() -> None:
engine = sa.create_engine("sqlite://")
try:
with engine.connect() as connection:
connection.execute(
sa.text(
"CREATE TABLE recipes (id VARCHAR PRIMARY KEY, perform_time VARCHAR, "
"perform_time_seconds INTEGER, cook_time VARCHAR)"
)
)
for row in ROWS:
connection.execute(
sa.text("INSERT INTO recipes VALUES (:a, :b, :c, :d)"), dict(zip("abcd", row, strict=True))
)
with Operations.context(MigrationContext.configure(connection)):
_migration().upgrade()
columns = {column["name"] for column in sa.inspect(connection).get_columns("recipes")}
perform_times = {
row.id: row.perform_time for row in connection.execute(sa.text("SELECT id, perform_time FROM recipes"))
}
finally:
engine.dispose()
assert "cook_time" not in columns
assert perform_times == {
"only-cook-time": "20 minutes",
"blank-perform-time": "PT15M",
"has-perform-time": "10 minutes",
"has-perform-seconds": None,
"cook-time-none": None,
"cook-time-blank": None,
"nothing": None,
}