Compare commits

..

47 Commits

Author SHA1 Message Date
Hayden
8154ee548a Chore/bump deps (#853)
* add LDAP dep

* bump extruct and scraper

* allow for disabling auto backup

* v0.5.4 changelog
2021-12-01 21:07:17 -09:00
Hayden
591bf9d98f Update v1-task.yaml 2021-11-24 11:46:43 -09:00
Hayden
f202b1f922 Update v1-task.yaml 2021-11-24 11:45:59 -09:00
Hayden
17b2e37e4e Update v1-task.yaml 2021-11-24 11:40:53 -09:00
Hayden
0ec8087ac6 Rename v1-task to v1-task.yaml 2021-11-24 11:33:59 -09:00
Hayden
e580d6f904 Create v1-tasks template 2021-11-24 11:33:26 -09:00
dvdkon
56d9cafb68 Add LDAP authentication support (v2, onto dev) (#803)
* Add LDAP authentication support

* Add test for LDAP authentication
2021-11-24 08:59:03 -09:00
Hayden
32c864c703 New Crowdin updates (#818)
* New translations en-US.json (French, Canada)

* New translations en-US.json (French, Canada)

* New translations en-US.json (French, Canada)

* New translations en-US.json (French)

* New translations en-US.json (French, Canada)

* New translations en-US.json (French, Canada)

* New translations en-US.json (French)
2021-11-23 20:38:25 -09:00
Bryce Willey
37280a3da0 Improve the SWAG Community Guide (#793)
* Freshen up the SWAG documentation

Added some extra pointers for setting up HTTPS with Mealie and SWAG, and indented the `docker-compose.yml` as it should be.

* Replaced <code> html blocks with backticks

* Better formatting and comments in example config files

* Made DuckDNS consistent with other places on the page
2021-11-23 20:34:23 -09:00
cadamswaite
7f850fba98 Use firefox UA when making requests (#780) 2021-11-23 20:34:10 -09:00
J.P. Krauss
b40f201430 Allow arrow keys to function when SearchDialog is not open (#777) 2021-11-07 10:11:07 -09:00
sephrat
a0d796551c Add support for new languages (#781)
* Add support for Slovak language

* Add support for new languages

Catalan, Danish, Norwegian and Russian
2021-11-07 10:03:37 -09:00
Hayden
fe3a4ab641 Update dockerbuild.prod.yml 2021-10-31 20:56:28 -08:00
Hayden
9a9fe66ccb Update dockerbuild.release.yml 2021-10-30 14:37:44 -08:00
Hayden
7fe4b75949 Build on release 2021-10-30 12:37:59 -08:00
Hayden
de5bea6f73 Bug/minor fixes (#762)
* Set web concurrency to 1

* bump versions

* update release notes

Co-authored-by: Hayden <hay-kot@pm.me>
2021-10-30 12:13:54 -08:00
Hayden
b6d43e8e3d New Crowdin updates (#759)
* New translations en-US.json (Chinese Simplified)

* New translations en-US.json (Chinese Simplified)
2021-10-28 19:13:10 -08:00
cadamswaite
18b099b115 Feature: Pick best image from list (#745)
* Pick largest image from list

* Add a safe value incase all requests fail

* Formatting
2021-10-19 20:30:06 -08:00
cadamswaite
3831eef508 Fix the recipe scraper debugger (#736)
* Fix recipe debugger

* Remove scrape-schema-recipe from dependencies

* Fix breaking tests
2021-10-19 16:01:35 -08:00
cadamswaite
75113cc2c7 Fix issues parsing times not in "PT.*H.*M" format (#733)
* Add more tests to the time cleaner

* Parse more time entries

* Formatting

* Refactor parse_duration

* Refactor pretty_print_timedelta

* Add some tests for pretty_print_timedelta

* Add option for cook_time from schema
2021-10-19 16:01:19 -08:00
cadamswaite
b81f88dc18 Fix issue with parsing scraped nutrition (#732)
* Fix issue with parsing scraped nutrition

* Attempt to clean nutrition info

* Allow comma separator

* Fix return type for clean_nutrition. Fail safe in case of unexpected type from scraper

* Switch to using regex parsing

* Formatting

* Cleanup - empty strings no longer a concern
2021-10-19 16:01:05 -08:00
zierbeek
756ffc8e90 Fixes #734 ios shortcut link and screenshots (#742) 2021-10-17 12:50:04 -08:00
Hayden
ec7df232ed New Crowdin updates (#730)
* New translations en-US.json (Russian)

* New translations en-US.json (Russian)

* New translations en-US.json (Russian)

* New translations en-US.json (Russian)

* New translations en-US.json (Swedish)

* New translations en-US.json (Swedish)

* New translations en-US.json (Swedish)
2021-10-17 12:49:51 -08:00
Hayden
35caef1c39 Revert "Docker/run as nonroot (#692)" (#724)
This reverts commit 19aa572bd8.
2021-10-06 09:42:37 -08:00
Hayden
9541137ef7 Update v1-bug-report.yaml 2021-10-04 15:40:49 -08:00
Hayden
756597324d Create v1-bug-report.yaml 2021-10-04 15:40:03 -08:00
Hayden
55f009ed9e Update bug-report.yaml 2021-10-04 15:35:45 -08:00
Hayden
9378c4879f update template 2021-10-04 15:35:09 -08:00
Usman Masood
19aa572bd8 Docker/run as nonroot (#692)
* changed python base image to 3.9.6

* bumped poetry version to 1.1.7

* user creation based on env variable PGID and PUID with default as PUID/PGID= 911

* App exposes APP_PORT=80 as env variable

* Removed user mod and handled it in docker image.

* moved scheduler.db to /app/temp dir

* set app default port to 80 if envvariable null

* Changed application port to env variable with default as 80

* Created sch. direcotry as part of image creation

* minor logging improvements.

* removed docker target

* cleanup

* fixed port

* fixed port

* fixed port

* removed volume specification

* fixing code quality warnings

* fixing code quality warnings

* fixing code quality warnings

* bumped versions to fix vulnerabilities

* corrected port

* bumped uvicorn version to fix vulnerabilities

* minor fix

* added sticky permissions

* adding port change info to docs

* adding port change info to docs

* adding port change info to docs

* improved formatting

* docs updated

* added docker port change warning
2021-10-02 11:35:16 -08:00
Krzysztof
66fdd6c428 feat: Add basic support for Web Share Target API (#714) 2021-10-02 10:09:17 -08:00
Hayden
3f419ad7b6 add '' around bool ENV variables 2021-09-30 17:49:03 -08:00
Hayden
f3305a9074 silence curl 2021-09-30 17:46:42 -08:00
Hayden
09e3b83933 chore/big-report-and-stalebot (#710)
* Create bug-report

* Update bug-report

* Delete bug_report.md

* Create stale.yaml
2021-09-30 17:45:33 -08:00
Hayden
b275aef04d fix(frontend): 🐛 fetch categories on load (#709)
Co-authored-by: Hayden <hay-kot@pm.me>
2021-09-30 17:14:22 -08:00
Hayden
69e226a0ed bug/fallback language fix (#708)
* add mealie-next items to gitignore

* revert lang to en-US if not found

* fix duplicate entries

Co-authored-by: Hayden <hay-kot@pm.me>
2021-09-30 17:03:11 -08:00
Hayden
aac0d5b6c6 New Crowdin updates (#703)
* New translations en-US.json (French)

* New translations en-US.json (Arabic)
2021-09-30 09:02:01 -08:00
Hayden
b47ee0557d New translations en-US.json (Chinese Simplified) (#701) 2021-09-29 10:47:30 -08:00
Bryce Willey
97e0796af2 Missing minus in Shopping List UI (#688)
* Shopping list quantity decrement button -> minus

Missed being renamed when material design icons were moved
to be global variables, still used the original md name.

* Updated poetry lock to fix rdflib-jsonld error

`extruct` depends on rdflib-jsonld, which had an error involving `use_2to3`
(https://github.com/RDFLib/rdflib-jsonld/pull/105), which prevented
building.

* update poetry CI/CD Version

Co-authored-by: Hayden <64056131+hay-kot@users.noreply.github.com>
2021-09-23 08:30:37 -08:00
Jason Chia-Hsien Ho
733bb77ddb Add traditional chinese locale (#685) 2021-09-20 14:30:37 -08:00
Hayden
eda6821288 New Crowdin updates (#684)
* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Slovak)

* New translations en-US.json (Slovak)

* New translations en-US.json (Slovak)

* New translations en-US.json (Slovak)

* New translations en-US.json (Slovak)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Chinese Traditional)

* New translations en-US.json (Portuguese, Brazilian)

* New translations en-US.json (Portuguese, Brazilian)

* New translations en-US.json (Portuguese, Brazilian)

* New translations en-US.json (Portuguese, Brazilian)

* New translations en-US.json (Portuguese, Brazilian)

* New translations en-US.json (Portuguese, Brazilian)

* New translations en-US.json (Portuguese, Brazilian)
2021-09-20 14:30:27 -08:00
Patrick
20fc2d868b makes the recipe image clickable to open full version (#678) 2021-09-12 11:06:46 -08:00
Patrick
29d78f52ca address LGTM errors and warnings (#676)
* remove assignment to itself, identified by LGTM: https://lgtm.com/rules/1800093/

* variable overwritten, identified by LGTM: https://lgtm.com/rules/1800095/

* unnecessary else, identified by LGTM: https://lgtm.com/rules/5980098/
2021-09-12 11:06:27 -08:00
Patrick
006d6a6f1d reference default login credentials per the documentation (#675) 2021-09-12 11:06:07 -08:00
Hayden
a210efd62f New Crowdin updates (#652)
* New translations en-US.json (Norwegian)

* New translations en-US.json (Norwegian)

* New translations en-US.json (Norwegian)

* New translations en-US.json (Norwegian)

* New translations en-US.json (Norwegian)

* New translations en-US.json (Norwegian)

* New translations en-US.json (Portuguese)

* New translations en-US.json (Portuguese)

* New translations en-US.json (Slovak)

* New translations en-US.json (Slovak)

* New translations en-US.json (Slovak)

* New translations en-US.json (Slovak)

* New translations en-US.json (Slovak)
2021-09-12 11:05:49 -08:00
Nathan Rennie-Waldock
3ec9b5c34d Fix logging an error on successful image scrape (#612) 2021-09-12 11:05:39 -08:00
Hayden
fd17614764 New Crowdin updates (#641)
* New translations en-US.json (German)

* New translations en-US.json (Polish)

* New translations en-US.json (Slovak)

* New translations en-US.json (Slovak)

* New translations en-US.json (Polish)

* New translations en-US.json (French)

* New translations en-US.json (Russian)

* New translations en-US.json (Russian)

* New translations en-US.json (Russian)

* New translations en-US.json (Russian)

* New translations en-US.json (Russian)

* New translations en-US.json (Russian)

* New translations en-US.json (Spanish)

* New translations en-US.json (Spanish)

* New translations en-US.json (Catalan)

* New translations en-US.json (Spanish)

* New translations en-US.json (Catalan)

* New translations en-US.json (Spanish)

* New translations en-US.json (Catalan)

* New translations en-US.json (Catalan)

* New translations en-US.json (Catalan)

* New translations en-US.json (Danish)

* New translations en-US.json (Danish)

* New translations en-US.json (Danish)

* New translations en-US.json (Danish)

* New translations en-US.json (Norwegian)

* New translations en-US.json (Norwegian)

* New translations en-US.json (Norwegian)

* New translations en-US.json (Norwegian)

* New translations en-US.json (Norwegian)

* New translations en-US.json (Russian)
2021-08-19 20:14:48 -08:00
bartfailt
98b0f8779b Add support for the Hungarian language (hu-HU) (#639) 2021-08-19 20:14:36 -08:00
1808 changed files with 80245 additions and 220235 deletions

View File

@@ -1,43 +0,0 @@
# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.224.2/containers/python-3/.devcontainer/base.Dockerfile
# [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster
ARG VARIANT="3.10-bullseye"
FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT}
# [Choice] Node.js version: none, lts/*, 16, 14, 12, 10
ARG NODE_VERSION="none"
RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi
# install poetry - respects $POETRY_VERSION & $POETRY_HOME
RUN echo "export PROMPT_COMMAND='history -a'" >> /home/vscode/.bashrc \
&& echo "export HISTFILE=~/commandhistory/.bash_history" >> /home/vscode/.bashrc \
&& chown vscode:vscode -R /home/vscode/
RUN npm install -g @go-task/cli
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_NO_CACHE_DIR=off \
PIP_DISABLE_PIP_VERSION_CHECK=on \
PIP_DEFAULT_TIMEOUT=100 \
POETRY_HOME="/opt/poetry" \
POETRY_VIRTUALENVS_IN_PROJECT=true
# prepend poetry and venv to path
ENV PATH="$POETRY_HOME/bin:$PATH"
RUN curl -sSL https://install.python-poetry.org | python3 -
# RUN poetry config virtualenvs.create false
RUN apt-get update \
&& apt-get install --no-install-recommends -y \
curl \
build-essential \
libpq-dev \
libwebp-dev \
libsasl2-dev libldap2-dev libssl-dev \
gnupg gnupg2 gnupg1
# create directory used for Docker Secrets
RUN mkdir -p /run/secrets

View File

@@ -1,59 +0,0 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.224.2/containers/python-3
{
"name": "Python 3",
"build": {
"dockerfile": "Dockerfile",
"context": "..",
"args": {
// Update 'VARIANT' to pick a Python version: 3, 3.10, 3.9, 3.8, 3.7, 3.6
// Append -bullseye or -buster to pin to an OS version.
// Use -bullseye variants on local on arm64/Apple Silicon.
"VARIANT": "3.10-bullseye",
// Options
"NODE_VERSION": "16"
}
},
"mounts": [
"source=mealie-devcontainer-workspace,target=/workspaces/mealie/frontend/node_modules,type=volume",
"source=mealie-bashhistory,target=/home/vscode/commandhistory,type=volume"
],
"customizations": {
"vscode": {
"settings": {
"python.defaultInterpreterPath": "/usr/local/bin/python",
"python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
"python.formatting.blackPath": "/usr/local/py-utils/bin/black",
"python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf",
"mypy.runUsingActiveInterpreter": true
},
"extensions": [
"charliermarsh.ruff",
"dbaeumer.vscode-eslint",
"matangover.mypy",
"ms-python.black-formatter",
"ms-python.pylint",
"ms-python.python",
"ms-python.vscode-pylance",
"Vue.volar"
]
}
},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [
3000,
9000,
9091, // used by docker production
24678 // used by nuxt when hot-reloading using polling
],
// Use 'onCreateCommand' to run commands at the end of container creation.
// Use 'postCreateCommand' to run commands after the container is created.
"onCreateCommand": "sudo chown -R vscode:vscode /workspaces/mealie/frontend/node_modules && task setup",
// Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "vscode",
"features": {
"ghcr.io/devcontainers/features/docker-in-docker:2": {
"dockerDashComposeVersion": "v2"
}
}
}

View File

@@ -1,8 +1,8 @@
.git
.github
.dockerignore
.gitattributes
.gitignore
.idea
.vscode
@@ -13,7 +13,6 @@ __pycache__/
htmlcov/
.coverage
.coverage.*
.pylintrc
.pytest_cache/
.venv
venv
@@ -26,9 +25,5 @@ venv
*/node_modules
*/dist
*/data/db
*/mealie/test
*/mealie/.temp
model.crfmodel
crowdin.yml
*/mealie/test
*/mealie/.temp

6
.flake8 Normal file
View File

@@ -0,0 +1,6 @@
[flake8]
ignore = [
E501 # Line Length - See Black Config in pyproject.toml
E402 # Import Not at Top of File
]
exclude = _all_models.py

2
.gitattributes vendored
View File

@@ -1,2 +1,2 @@
*.css linguist-detectable=false
*.html linguist-detectable=false
*.html linguist-detectable=false

View File

@@ -1,41 +0,0 @@
---
title: "YOUR TITLE"
body:
- type: checkboxes
id: checks
attributes:
label: First Check
description: |
Please confirm and check all the following prior to submission. If you do not do this, your
issue may be closed.
options:
- label: I used the GitHub search to find a similar requests and didn't find it.
required: true
- label: Checked the [tasks tagged](https://github.com/mealie-recipes/mealie/issues?q=is%3Aissue+is%3Aopen+label%3Atask+) issues and verified my feature is not covered
required: true
- type: textarea
id: problem
attributes:
label: Please provide a concise description of the problem that would be addressed by this feature.
validations:
required: true
- type: textarea
id: solution
attributes:
label: Please provide a concise description of the feature that would resolve your issue.
validations:
required: true
- type: textarea
id: considerations
attributes:
label: Please consider and list out some caveats or tradeoffs made in your design decision
validations:
required: true
- type: checkboxes
id: additional-information
attributes:
label: Additional Information
options:
- label: If this is accepted I'm willing to submit a PR to provide this feature
- label: If this is accepted I'm willing to help maintain this feature
- label: I'm willing to sponsor/pay a developer to do this work

View File

@@ -1,9 +0,0 @@
---
title: OAuth setup with <PROVIDER>
body:
- type: textarea
attributes:
label: Configuration Example
description: Add your example configuration. You can provide code blocks, screenshots, and links.
validations:
required: true

View File

@@ -1,20 +1,16 @@
---
name: Bug Report
description: "Submit a bug for the latest version of Mealie"
title: "[BUG] - YOUR DESCRIPTIVE TITLE GOES HERE"
labels: ["bug", "triage"]
description: "submit a bug report for the current release"
body:
- type: checkboxes
id: checks
attributes:
label: First Check
description: |
Please confirm and check all the following prior to submission. If you do not do this, your
issue may be closed.
description: Please confirm and check all the following options.
options:
- label: This is not a feature request.
- label: This is not a feature request
required: true
- label: I added a very descriptive title to this issue (title field is above this).
- label: I added a very descriptive title to this issue.
required: true
- label: I used the GitHub search to find a similar issue and didn't find it.
required: true
@@ -22,8 +18,6 @@ body:
required: true
- label: I already read the docs and didn't find an answer.
required: true
- label: This issue can be replicated on the demo site (https://demo.mealie.io/).
required: false
- type: textarea
id: description
attributes:
@@ -31,25 +25,6 @@ body:
placeholder: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Steps to Reproduce
placeholder: 1) ... 2) ... 3) ...
validations:
required: true
- type: textarea
id: logs
attributes:
label: Please provide relevant logs
placeholder: For example from `docker compose logs` or other system logs.
validations:
required: true
- type: textarea
id: version
attributes:
label: Mealie Version
placeholder: Docker image, as well as 'Build' tag from https://yourmealieurl/admin/site-settings, if UI is working
- type: dropdown
id: os
attributes:
@@ -61,11 +36,17 @@ body:
- Docker (Windows)
- Docker (Synology)
- Unraid
- TrueNAS
- Other (please specify below)
- Other
validations:
required: true
- type: textarea
id: other
id: os-details
attributes:
label: Additional Deployment Details
label: Deployment Details
description: You can add more details about your operating system here, in particular if you chose "Other". If you are experiencing issues with deployment, please provide your docker-compose or docker commands
- type: input
id: mealie-version
attributes:
label: Mealie Version
validations:
required: true

View File

@@ -1,4 +1,4 @@
contact_links:
- name: Feature Requests
url: https://github.com/mealie-recipes/mealie/discussions/new?category=feature-request
about: Please add any Feature Requests as a Github Discussion using the form in this issue.
url: https://github.com/hay-kot/mealie/issues/122
about: Please add any Feature Requests here.

View File

@@ -1,53 +0,0 @@
---
name: Error Scraping Recipe
description: "Submit a bug or issues related to scraping recipes"
title: "[SCRAPER] - YOUR TITLE"
labels: ["bug", "triage", "scraper"]
body:
- type: checkboxes
id: checks
attributes:
label: First Check
description: |
Please confirm and check all the following prior to submission. If you do not do this, your
issue may be closed.
options:
- label: I used the GitHub search to find a similar issue and didn't find it.
required: true
- label: |
I have verified that this issue _is not_ related to the underlying library
[hhyrsev/recipe-scrapers](https://github.com/hhursev/recipe-scrapers) by **1)** checking
the [debugger](https://demo.mealie.io/g/home/r/create/debug) and data is returned, **2)**
verifying that there _are_ errors in the log related to application level code, or
**3)** verified that the site provides recipe data, or is otherwise supported by
[hhyrsev/recipe-scrapers](https://github.com/hhursev/recipe-scrapers)
required: true
- label: This issue can be replicated on the demo site (https://demo.mealie.io/)
required: false
- type: textarea
id: urls
attributes:
label: Please provide 1-5 example URLs that are having errors
validations:
required: true
- type: textarea
id: logs
attributes:
label: |
Please provide your logs for the Mealie container `docker logs <container-id> > mealie.logs`
validations:
required: true
- type: dropdown
id: os
attributes:
label: Deployment
description: What Deployment system are you using?
multiple: true
options:
- Docker (Linux)
- Docker (Windows)
- Docker (Synology)
- Unraid
- Other
validations:
required: true

View File

@@ -0,0 +1,47 @@
---
name: v1.0.0b Bug Report
description: "submit a bug report for the v1 beta"
title: "[v1.0.0b] - YOUR TITLE"
body:
- type: checkboxes
id: checks
attributes:
label: First Check
description: Please confirm and check all the following options.
options:
- label: This is not a feature request
required: true
- label: I added a very descriptive title to this issue.
required: true
- label: I used the GitHub search to find a similar issue and didn't find it.
required: true
- label: I searched the Mealie documentation, with the integrated search.
required: true
- label: I already read the docs and didn't find an answer.
required: true
- type: textarea
id: description
attributes:
label: What is the issue you are experiencing?
placeholder: A clear and concise description of what the bug is.
validations:
required: true
- type: dropdown
id: os
attributes:
label: Deployment
description: What Deployment system are you using?
multiple: true
options:
- Docker (Linux)
- Docker (Windows)
- Docker (Synology)
- Unraid
- Other
validations:
required: true
- type: textarea
id: os-details
attributes:
label: Deployment Details
description: You can add more details about your operating system here, in particular if you chose "Other". If you are experiencing issues with deployment, please provide your docker-compose or docker commands

View File

@@ -1,27 +1,27 @@
---
name: Task
name: v1.0.0b Task
description: "CONTRIBUTORS ONLY: Submit a Task that needs to be completed"
title: "[Task] - TASK DESCRIPTION"
title: "[v1.0.0b] [Task] - TASK DESCRIPTION"
labels:
- task
- v2
- v1
body:
- type: markdown
attributes:
value: |
Thanks for your interest in Mealie! 🚀
This is a place for Mealie contributors to find tasks that need to get done around the repository. Tasks are different than issues as they are generally related to providing a new feature or improving an existing feature. They are _generally_ not related to an issue.
This is a place for Mealie contributors to find tasks that need to get done around the repository. Tasks are different than issues as they are generally related to providing a new feature or improve an existing feature. They are _generally_ not related to an issue.
**DO NOT** create a task unless
- You are a contributor who has prior approval via discord/discussions
- You are a contributors who has prior approval via discord/discussions
- You have otherwise been given approval to post the tasks
Otherwise, your post will be closed/deleted.
Otherwise, your post will be closed/deleted.
**Interested in Taking This?**
If you're interested in completing this task and it hasn't already been taken, comment below and to let others know you're working on it. As you work through the task, I ask that you submit a draft pull request as soon as possible, and tag this issue so we can all collaborate as best as possible.
If you're interested in completing this tasks and it hasn't already been taken, comment below and to let others know you're working on it. As you work through the task, I ask that you submit a draft pull request as soon as possible, and tag this issue so we can all collaborate as best as possible.
- type: textarea
id: problem
attributes:
@@ -33,6 +33,6 @@ body:
id: solution
attributes:
label: Proposed/Possible Solution(s)?
placeholder: Provide as much context around the idea as possible with potential files and roadblocks that may come up.
placeholder: Provide as much context around the idea as possible with potential files and roadblocks that may come up
validations:
required: true

View File

@@ -1,77 +0,0 @@
<!--
This template provides some ideas of things to include in your PR description.
To start, try providing a short summary of your changes in the Title above. We follow Conventional Commits syntax, please ensure your title is prefixed with one of:
- `feat: `
- `fix: `
- `docs: `
- `chore: `
- `dev:`
If a section of the PR template does not apply to this PR, then delete that section.
PLEASE READ:
-------------------------
Mealie is moving to a regular, automatic release schedule. This means that all PRs should be in a
stable state, ready for release. This includes:
- Ensuring new tests have been added to cover new features, or to prevent regressions.
- Work is fully complete and usable
-->
## What type of PR is this?
_(REQUIRED)_
<!--
Delete any of the following that do not apply:
-->
- feature
- bug
- documentation
- cleanup
- dev (Internal development)
## What this PR does / why we need it:
_(REQUIRED)_
<!--
What goal is this change working towards?
Provide a bullet pointed summary of how each file was changed.
Briefly explain any decisions you made with respect to the changes.
Include anything here that you didn't include in *Release Notes*
above, such as changes to CI or changes to internal methods.
If there is a UI component to the change, please include before/after images.
-->
## Which issue(s) this PR fixes:
_(REQUIRED)_
<!--
If this PR fixes one of more issues, list them here.
One per line, like so:
Fixes #123
Fixes #39
-->
## Special notes for your reviewer:
_(fill-in or delete this section)_
<!--
Is there any particular feedback you would / wouldn't like?
Which parts of the code should reviewers focus on?
-->
## Testing
_(fill-in or delete this section)_
<!--
Describe how you tested this change.
-->

View File

@@ -1,88 +0,0 @@
---
name-template: "v$RESOLVED_VERSION"
tag-template: "v$RESOLVED_VERSION"
change-template: "- $TITLE @$AUTHOR (#$NUMBER)"
sort-direction: ascending
categories:
- title: "🚨 Breaking changes"
labels:
- "breaking-change"
- "major"
- title: "✨ New features"
labels:
- "feature"
- "minor"
- title: "🐛 Bug fixes"
labels:
- "bugfix"
- title: "🧰 Maintenance"
collapse-after: 3
labels:
- "ci"
- "chore"
- "l10n"
- title: "📚 Documentation"
labels:
- "documentation"
- title: "🔨 Internal development"
labels:
- "dev"
- title: "⬆️ Dependency updates"
collapse-after: 3
labels:
- "dependencies"
version-resolver:
major:
labels:
- "major"
- "breaking-change"
minor:
labels:
- "minor"
- "feature"
patch:
labels:
- "bugfix"
- "chore"
- "ci"
- "dependencies"
- "documentation"
- "l10n"
- "dev"
default: patch
template: |
# 🍴🍴🍴🍴🍴🍴
## 🎉 Highlights
- Highlight 1
- Highlight 2
$CHANGES
## 🙏 New Contributors
!!! Need to source this from GitHub's auto generated release notes !!!
# 🍴🍴🍴🍴🍴🍴
autolabeler:
- label: 'feature'
title:
- '/feat/i'
- label: 'bugfix'
title:
- '/fix:/i'
- label: 'documentation'
title:
- '/docs:/i'
- label: 'chore'
title:
- '/chore:/i'
- label: 'dev'
title:
- '/dev:/i'

View File

@@ -1,5 +0,0 @@
# Always validate the PR title AND all the commits
titleAndCommits: true
# Allows use of Merge commits (eg on github: "Merge branch 'master' into feature/ride-unicorns")
# this is only relevant when using commitsOnly: true (or titleAndCommits: true)
allowMergeCommits: true

17
.github/stale.yaml vendored Normal file
View File

@@ -0,0 +1,17 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 60
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- pinned
- security
# Label to use when marking an issue as stale
staleLabel: wontfix
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

19
.github/workflows/build-docs.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
name: Publish docs via GitHub Pages
on:
release:
types: [published]
jobs:
build:
name: Deploy docs
runs-on: ubuntu-latest
steps:
- name: Checkout main
uses: actions/checkout@v2
- name: Deploy docs
uses: mhausenblas/mkdocs-deploy-gh-pages@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CONFIG_FILE: docs/mkdocs.yml
EXTRA_PACKAGES: build-base

View File

@@ -1,80 +0,0 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ "mealie-next" ]
schedule:
- cron: '36 9 * * 3'
workflow_call:
jobs:
analyze:
name: Analyze
# Runner size impacts CodeQL analysis time. To learn more, please see:
# - https://gh.io/recommended-hardware-resources-for-running-codeql
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners
# Consider using larger runners for possible analysis time improvements.
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }}
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript-typescript', 'python' ]
# CodeQL supports [ 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' ]
# Use only 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use only 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v3
# Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"

View File

@@ -0,0 +1,30 @@
name: Docker Build Dev Docs
on:
push:
branches:
- dev
jobs:
push_to_registry:
name: Push Docker image to GitHub Packages
runs-on: ubuntu-latest
permissions:
packages: write
contents: read
steps:
- name: Check out the repo
uses: actions/checkout@v2
- name: Log in to GitHub Docker Registry
uses: docker/login-action@v1
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build container image
uses: docker/build-push-action@v2
with:
context: ./docs
push: true
tags: |
ghcr.io/${{ github.repository }}/dev-docs:latest

49
.github/workflows/dockerbuild.dev.yml vendored Normal file
View File

@@ -0,0 +1,49 @@
name: Docker Build Dev
on:
push:
branches:
- dev
jobs:
build:
runs-on: ubuntu-latest
steps:
#
# Checkout
#
- name: checkout code
uses: actions/checkout@v2
#
# Setup QEMU
#
- name: Set up QEMU
id: qemu
uses: docker/setup-qemu-action@v1
with:
image: tonistiigi/binfmt:latest
platforms: all
#
# Setup Buildx
#
- name: install buildx
id: buildx
uses: docker/setup-buildx-action@v1
with:
install: true
#
# Login to Docker Hub
#
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
#
# Build
#
- name: build the image
run: |
docker build --push --no-cache \
--tag hkotel/mealie:dev \
--platform linux/amd64,linux/arm64 .

48
.github/workflows/dockerbuild.prod.yml vendored Normal file
View File

@@ -0,0 +1,48 @@
name: Docker Build Production
on:
release:
types: [published]
jobs:
build:
runs-on: ubuntu-latest
steps:
#
# Checkout
#
- name: checkout code
uses: actions/checkout@v2
#
# Setup QEMU
#
- name: Set up QEMU
id: qemu
uses: docker/setup-qemu-action@v1
with:
image: tonistiigi/binfmt:latest
platforms: all
#
# Setup Buildx
#
- name: install buildx
id: buildx
uses: docker/setup-buildx-action@v1
with:
install: true
#
# Login to Docker Hub
#
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
#
# Build
#
- name: build the image
run: |
docker build --push \
--tag hkotel/mealie:latest \
--platform linux/amd64,linux/arm64 .

View File

@@ -0,0 +1,56 @@
name: Docker Build Production
on:
release:
types: [published]
jobs:
build:
runs-on: ubuntu-latest
steps:
#
# Get Release Version
#
- uses: oprypin/find-latest-tag@v1
with:
repository: hay-kot/mealie # The repository to scan.
releases-only: true # We know that all relevant tags have a GitHub release for them.
id: mealie_version # The step ID to refer to later.
#
# Checkout
#
- name: checkout code
uses: actions/checkout@v2
#
# Setup QEMU
#
- name: Set up QEMU
id: qemu
uses: docker/setup-qemu-action@v1
with:
image: tonistiigi/binfmt:latest
platforms: all
#
# Setup Buildx
#
- name: install buildx
id: buildx
uses: docker/setup-buildx-action@v1
with:
install: true
#
# Login to Docker Hub
#
- name: Login to Docker Hub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
#
# Build
#
- name: build the image
run: |
docker build --push \
--tag hkotel/mealie:${{ steps.mealie_version.outputs.tag }} \
--platform linux/amd64,linux/arm64 .

View File

@@ -1,45 +0,0 @@
name: E2E Tests
on:
workflow_call:
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./tests/e2e
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
cache: 'yarn'
cache-dependency-path: ./tests/e2e/yarn.lock
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build Image
uses: docker/build-push-action@v5
with:
file: ./docker/Dockerfile
context: .
push: false
load: true
tags: mealie:e2e
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Deploy E2E Test Environment
run: docker compose up -d
working-directory: ./tests/e2e/docker
- name: Install dependencies
run: npm install -g yarn && yarn
- name: Install Playwright Browsers
run: yarn playwright install --with-deps
- name: Check test environment
run: docker ps
- name: Run Playwright tests
run: yarn playwright test
- name: Destroy Test Environment
if: always()
run: docker compose down --volumes
working-directory: ./tests/e2e/docker

View File

@@ -1,60 +0,0 @@
name: Docker Nightly Production
on:
push:
branches:
- mealie-next
paths-ignore:
- '*.md'
- '.devcontainer/**'
# I'm not excluding .github as changes in there might be to workflows etc
- '.vscode/**'
- 'docs/**'
concurrency:
group: nightly-${{ github.ref }}
cancel-in-progress: true
jobs:
backend-tests:
name: "Backend Server Tests"
uses: ./.github/workflows/partial-backend.yml
frontend-tests:
name: "Frontend and End-to-End Tests"
uses: ./.github/workflows/partial-frontend.yml
build-release:
permissions:
contents: read
packages: write
# The id-token write permission is needed to connect to Depot.dev
# as part of the partial-builder.yml action. It needs to be declared
# in the parent action, as noted here:
# https://github.com/orgs/community/discussions/76409#discussioncomment-8131390
id-token: write
name: Build Tagged Release
if: github.repository == 'mealie-recipes/mealie'
uses: ./.github/workflows/partial-builder.yml
needs:
- frontend-tests
- backend-tests
with:
tag: nightly
secrets:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
notify-discord:
name: Notify Discord
if: github.repository == 'mealie-recipes/mealie'
needs:
- build-release
runs-on: ubuntu-latest
steps:
- name: Discord notification
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_NIGHTLY_WEBHOOK }}
uses: Ilshidur/action-discord@0.3.2
with:
args: "🚀 New builds of ghcr.io/mealie-recipes/mealie:nightly"

View File

@@ -1,110 +0,0 @@
name: Backend Test/Lint
on:
workflow_call:
jobs:
tests:
runs-on: ubuntu-latest
env:
PRODUCTION: false
strategy:
fail-fast: true
matrix:
# Database ENV Variables as Specified by Mealie
Database: [sqlite, postgres]
# Services
services:
postgres:
image: postgres
env:
POSTGRES_USER: mealie
POSTGRES_PASSWORD: mealie
POSTGRES_DB: mealie
options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
ports:
- 5432:5432
ldap:
image: rroemhild/test-openldap
ports:
- 10389:10389
- 10636:10636
# Steps
steps:
- name: Install Task
uses: arduino/setup-task@v2
with:
version: 3.x
repo-token: ${{ secrets.GITHUB_TOKEN }}
- name: Check out repository
uses: actions/checkout@v4
- name: Set up python
uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Install Poetry
uses: snok/install-poetry@v1
with:
virtualenvs-create: true
virtualenvs-in-project: true
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v4
with:
path: .venv
key: venv-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}
- name: Check venv cache
id: cache-validate
if: steps.cached-poetry-dependencies.outputs.cache-hit == 'true'
run: |
echo "import fastapi;print('venv good?')" > test.py && poetry run python test.py && echo "cache-hit-success=true" >> $GITHUB_OUTPUT
rm test.py
continue-on-error: true
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install libsasl2-dev libldap2-dev libssl-dev
poetry install
poetry add "psycopg2-binary==2.9.9"
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true' || steps.cache-validate.outputs.cache-hit-success != 'true'
- name: Formatting (Ruff)
run: |
poetry run ruff format . --check
- name: Lint (Ruff)
run: |
task py:lint
- name: Mypy Typecheck
run: |
task py:mypy
- name: Pytest
env:
DB_ENGINE: ${{ matrix.Database }}
POSTGRES_SERVER: localhost
LDAP_AUTH_ENABLED: True
LDAP_SERVER_URL: ldap://localhost:10389
LDAP_TLS_INSECURE: true
LDAP_ENABLE_STARTTLS: false
LDAP_BASE_DN: "ou=people,dc=planetexpress,dc=com"
LDAP_QUERY_BIND: "cn=admin,dc=planetexpress,dc=com"
LDAP_QUERY_PASSWORD: "GoodNewsEveryone"
LDAP_USER_FILTER: "(&(|({id_attribute}={input})({mail_attribute}={input}))(|(memberOf=cn=ship_crew,ou=people,dc=planetexpress,dc=com)(memberOf=cn=admin_staff,ou=people,dc=planetexpress,dc=com)))"
LDAP_ADMIN_FILTER: "memberOf=cn=admin_staff,ou=people,dc=planetexpress,dc=com"
LDAP_ID_ATTRIBUTE: uid
LDAP_NAME_ATTRIBUTE: cn
LDAP_MAIL_ATTRIBUTE: mail
run: |
task py:test

View File

@@ -1,57 +0,0 @@
name: Build Containers
on:
workflow_call:
inputs:
tag:
required: true
type: string
tags:
required: false
type: string
secrets:
DOCKERHUB_USERNAME:
required: true
DOCKERHUB_TOKEN:
required: true
jobs:
publish:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Log in to the Container registry (ghcr.io)
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to the Container registry (dockerhub)
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Override __init__.py
run: |
echo "__version__ = \"${{ inputs.tag }}\"" > ./mealie/__init__.py
- uses: depot/setup-action@v1
- name: Build and push Docker image, via Depot.dev
uses: depot/build-push-action@v1
with:
project: srzjb6mhzm
file: ./docker/Dockerfile
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: |
hkotel/mealie:${{ inputs.tag }}
ghcr.io/${{ github.repository }}:${{ inputs.tag }}
${{ inputs.tags }}
build-args: |
COMMIT=${{ github.sha }}

View File

@@ -1,77 +0,0 @@
name: Frontend Build/Lin
on:
workflow_call:
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout 🛎
uses: actions/checkout@v4
- name: Setup node env 🏗
uses: actions/setup-node@v4.0.0
with:
node-version: 16
check-latest: true
- name: Get yarn cache directory path 🛠
id: yarn-cache-dir-path
run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT
- name: Cache node_modules 📦
uses: actions/cache@v4
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Install dependencies 👨🏻‍💻
run: yarn
working-directory: "frontend"
- name: Run linter 👀
run: yarn lint
working-directory: "frontend"
- name: Run tests 🧪
run: yarn test:ci
working-directory: "frontend"
build:
runs-on: ubuntu-latest
steps:
- name: Checkout 🛎
uses: actions/checkout@v4
- name: Setup node env 🏗
uses: actions/setup-node@v4.0.0
with:
node-version: 16
check-latest: true
- name: Get yarn cache directory path 🛠
id: yarn-cache-dir-path
run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT
- name: Cache node_modules 📦
uses: actions/cache@v4
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Install dependencies 👨🏻‍💻
run: yarn
working-directory: "frontend"
- name: Run Build 🚚
run: yarn build
working-directory: "frontend"

View File

@@ -1,33 +0,0 @@
name: Trivy Container Scanning
on:
workflow_call:
jobs:
build:
name: Build and Scan Container
runs-on: ubuntu-latest
strategy:
fail-fast: true
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Build Dockerfile
run: |
docker build -t mealie --file=./docker/Dockerfile .
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@master
with:
ignore-unfixed: true
image-ref: "mealie"
format: "sarif"
output: "trivy-results.sarif"
env:
TRIVY_DB_REPOSITORY: ghcr.io/aquasecurity/trivy-db,public.ecr.aws/aquasecurity/trivy-db
- name: Upload Trivy scan results to GitHub Security tab
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: "trivy-results.sarif"

View File

@@ -1,42 +0,0 @@
name: Pull Request Linter
on:
workflow_call:
pull_request:
types: [edited] # This captures the PR title changing
branches:
- mealie-next
jobs:
validate-title:
name: Validate PR title
runs-on: ubuntu-latest
steps:
# https://github.com/amannn/action-semantic-pull-request
- uses: amannn/action-semantic-pull-request@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
# Configure which types are allowed (newline-delimited).
# Default: https://github.com/commitizen/conventional-commit-types
types: |
feat
fix
docs
chore
dev
# Configure which scopes are allowed (newline-delimited).
# These are regex patterns auto-wrapped in `^ $`.
scopes: |
deps
auto
l10n
# Configure that a scope must always be provided.
requireScope: false
# If the PR contains one of these newline-delimited labels, the
# validation is skipped. If you want to rerun the validation when
# labels change, you might want to use the `labeled` and `unlabeled`
# event triggers in your workflow.
ignoreLabels: |
bot
ignore-semantic-pull-request

View File

@@ -1,39 +0,0 @@
name: PR CI
on:
pull_request:
branches:
- mealie-next
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
pull-request-lint:
name: "Lint PR"
uses: ./.github/workflows/pull-request-lint.yml
backend-tests:
name: "Backend Server Tests"
uses: ./.github/workflows/partial-backend.yml
frontend-tests:
name: "Frontend and End-to-End Tests"
uses: ./.github/workflows/partial-frontend.yml
container-scanning:
name: "Trivy Container Scanning"
uses: ./.github/workflows/partial-trivy-container-scanning.yml
end-to-end:
name: "End-to-End Tests"
uses: ./.github/workflows/e2e.yml
code-ql:
name: "CodeQL"
uses: ./.github/workflows/codeql.yml
permissions:
actions: read
contents: read
security-events: write

View File

@@ -1,30 +0,0 @@
---
name: Release Drafter
on:
push:
branches:
- mealie-next
# pull_request event is required for autolabeler
pull_request:
types: [opened, labeled, unlabeled, reopened, synchronize]
# pull_request_target event is required for autolabeler to support PRs from forks
pull_request_target:
types: [opened, labeled, unlabeled, reopened, synchronize]
workflow_dispatch:
jobs:
update_release_draft:
permissions:
# write permission is required to create a github release
contents: write
# write permission is required for autolabeler
# otherwise, read permission is required at least
pull-requests: write
name: ✏️ Draft release
runs-on: ubuntu-latest
steps:
- name: 🚀 Run Release Drafter
uses: release-drafter/release-drafter@v6.0.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,88 +0,0 @@
name: Docker Build Production
on:
release:
types: [published]
jobs:
backend-tests:
name: "Backend Server Tests"
uses: ./.github/workflows/partial-backend.yml
frontend-tests:
name: "Frontend and End-to-End Tests"
uses: ./.github/workflows/partial-frontend.yml
build-release:
permissions:
contents: read
packages: write
# The id-token write permission is needed to connect to Depot.dev
# as part of the partial-builder.yml action. It needs to be declared
# in the parent action, as noted here:
# https://github.com/orgs/community/discussions/76409#discussioncomment-8131390
id-token: write
name: Build Tagged Release
uses: ./.github/workflows/partial-builder.yml
needs:
- backend-tests
- frontend-tests
with:
tag: ${{ github.event.release.tag_name }}
tags: |
hkotel/mealie:latest
ghcr.io/${{ github.repository }}:latest
secrets:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
notify-discord:
name: Notify Discord
needs:
- build-release
runs-on: ubuntu-latest
steps:
- name: Discord notification
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_RELEASE_WEBHOOK }}
uses: Ilshidur/action-discord@0.3.2
with:
args: "🚀 Version {{ EVENT_PAYLOAD.release.tag_name }} of Mealie has been released. See the release notes https://github.com/mealie-recipes/mealie/releases/tag/{{ EVENT_PAYLOAD.release.tag_name }}"
update-image-tags:
name: Update image tag in sample docker-compose files
needs:
- build-release
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout 🛎
uses: actions/checkout@v4
- name: Extract Version From Tag Name
run: echo "VERSION_NUM=$(echo ${{ github.event.release.tag_name }} | sed 's/^v//')" >> $GITHUB_ENV
- name: Modify version strings
run: |
sed -i 's/:v[0-9]*.[0-9]*.[0-9]*/:v${{ env.VERSION_NUM }}/' docs/docs/documentation/getting-started/installation/installation-checklist.md
sed -i 's/:v[0-9]*.[0-9]*.[0-9]*/:v${{ env.VERSION_NUM }}/' docs/docs/documentation/getting-started/installation/sqlite.md
sed -i 's/:v[0-9]*.[0-9]*.[0-9]*/:v${{ env.VERSION_NUM }}/' docs/docs/documentation/getting-started/installation/postgres.md
sed -i 's/^version = "[^"]*"/version = "${{ env.VERSION_NUM }}"/' pyproject.toml
sed -i 's/^\s*"version": "[^"]*"/"version": "${{ env.VERSION_NUM }}"/' frontend/package.json
- name: Create Pull Request
uses: peter-evans/create-pull-request@v6
# This doesn't currently work for us because it creates the PR but the workflows don't run.
# TODO: Provide a personal access token as a parameter here, that solves that problem.
# https://github.com/peter-evans/create-pull-request
with:
commit-message: "Update image tag, for release ${{ github.event.release.tag_name }}"
branch: "docs/newrelease-update-version-${{ github.event.release.tag_name }}"
labels: |
documentation
delete-branch: true
base: mealie-next
title: "docs(auto): Update image tag, for release ${{ github.event.release.tag_name }}"
body: "Auto-generated by `.github/workflows/release.yml`, on publish of release ${{ github.event.release.tag_name }}"

View File

@@ -1,56 +0,0 @@
name: Scheduled Checks
on:
schedule:
# Every monday at 7 AM
- cron: 0 7 * * 1
jobs:
update:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Checkout 🛎
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Set PY
shell: bash
run: echo "PY=$(python -VV | sha256sum | cut -d' ' -f1)" >> $GITHUB_ENV
- name: Cache
uses: actions/cache@v4
with:
path: |
~/.cache/pre-commit
~/.cache/pip
key: pre-commit-${{ env.PY }}-${{ hashFiles('.pre-commit-config.yaml') }}
- name: Install pre-commit
shell: bash
run: pip install -U pre-commit
- name: Run `pre-commit autoupdate`
shell: bash
run: pre-commit autoupdate --color=always
- name: Create Pull Request
uses: peter-evans/create-pull-request@v6
# This doesn't currently work for us because it creates the PR but the workflows don't run.
# TODO: Provide a personal access token as a parameter here, that solves that problem.
# https://github.com/peter-evans/create-pull-request
with:
commit-message: "Update pre-commit hooks"
branch: "fix/update-pre-commit-hooks"
labels: |
chore
delete-branch: true
base: mealie-next
title: "chore(auto): Update pre-commit hooks"
body: "Auto-generated by `.github/workflows/scheduled-checks.yml`"

View File

@@ -1,41 +0,0 @@
# Documentation: https://github.com/marketplace/actions/close-stale-issues
name: 'Stale: Flag and close stale issues and PRs'
on:
schedule:
- cron: '30 1 * * *'
permissions:
issues: write
pull-requests: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
stale-issue-label: 'stale'
exempt-issue-labels: 'pinned,security,early-stages,bug: confirmed,feedback,task'
stale-issue-message: 'This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.'
days-before-issue-stale: 30
days-before-issue-close: 5
stale-pr-label: 'stale'
stale-pr-message: 'This PR is stale because it has been open 45 days with no activity.'
days-before-pr-stale: 45
# This stops a PR from ever getting closed automatically.
days-before-pr-close: -1
# If an issue/PR has a milestone, it's exempt from being marked as stale.
exempt-all-milestones: true
# How many API calls will we allow the action to make, essentially.
# Doco: https://github.com/actions/stale?tab=readme-ov-file#operations-per-run
operations-per-run: 150
########################################################################
# The below are just default values, but populating here for reference #
########################################################################
# Automatically remove the stale label when the issues or the pull requests are updated
remove-stale-when-updated: true
# The reason used when closing issues. Valid values are `completed` and `not_planned`.
close-issue-reason: 'not_planned'
# If true, PRs currently in draft will not be marked as stale automatically.
# We can mark them stale (after `days-before-pr-stale`), though we don't auto-close.
exempt-draft-pr: false

78
.github/workflows/test-all.yml vendored Normal file
View File

@@ -0,0 +1,78 @@
name: Project Tests
on:
push:
branches:
- master
- dev
pull_request:
branches:
- master
- dev
types: [synchronize, opened, reopened, ready_for_review]
jobs:
tests:
env:
PRODUCTION: false
runs-on: ubuntu-latest
services:
postgres:
image: postgres
env:
POSTGRES_USER: mealie
POSTGRES_PASSWORD: mealie
POSTGRES_DB: mealie
options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
ports:
- 5432:5432
steps:
#----------------------------------------------
# check-out repo and set-up python
#----------------------------------------------
- name: Check out repository
uses: actions/checkout@v2
- name: Set up python
uses: actions/setup-python@v2
with:
python-version: 3.9
#----------------------------------------------
# ----- install & configure poetry -----
#----------------------------------------------
- name: Install Poetry
uses: snok/install-poetry@v1
with:
virtualenvs-create: true
virtualenvs-in-project: true
#----------------------------------------------
# load cached venv if cache exists
#----------------------------------------------
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v2
with:
path: .venv
key: venv-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}
#----------------------------------------------
# install dependencies if cache does not exist
#----------------------------------------------
- name: Install dependencies
run: |
sudo apt-get install libsasl2-dev libldap2-dev libssl-dev
poetry install
poetry add "psycopg2-binary==2.8.6"
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
#----------------------------------------------
# run test suite
#----------------------------------------------
- name: Run Test Suite
run: |
make test-all
#----------------------------------------------
# run test suite
#----------------------------------------------
- name: Run Test Suite Postgres
env:
DB_ENGINE: postgres
POSTGRES_SERVER: localhost
run: |
make test-all

18
.gitignore vendored
View File

@@ -3,7 +3,6 @@
*__pycache__/
*.py[cod]
*$py.class
*.temp
# frontend/.env.development
docs/site/
@@ -11,14 +10,11 @@ docs/site/
.secret
frontend/dist/
dev/code-generation/generated/*
dev/data/mealie.db-journal
dev/data/backups/*
dev/data/debug/*
dev/data/img/*
dev/data/migration/*
dev/data/users/*
dev/data/groups/*
.DS_Store
node_modules
@@ -56,6 +52,7 @@ develop-eggs/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
!frontend/src/components/Recipe/Parts/
@@ -87,7 +84,6 @@ coverage.xml
*.cover
.hypothesis/
.pytest_cache/
.ruff_cache/
test.db
# Translations
@@ -155,11 +151,7 @@ dev/data/recipes/*
dev/scripts/output/app_routes.py
dev/scripts/output/javascriptAPI/*
mealie/services/scraper/ingredient_nlp/model.crfmodel
dev/code-generation/generated/openapi.json
dev/code-generation/generated/test_routes.py
mealie/services/parser_services/crfpp/model.crfmodel
lcov.info
dev/code-generation/openapi.json
.run/
.task/*
.gitignore
frontend/.nuxt/**
frontend/static/sw.js
dev/code-generation/generated/*

View File

@@ -1,18 +0,0 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: check-yaml
exclude: "mkdocs.yml"
- id: check-json
exclude: (.vscode|.devcontainer)
- id: check-toml
- id: end-of-file-fixer
- id: trailing-whitespace
exclude: ^tests/data/
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.7.2
hooks:
- id: ruff
- id: ruff-format

View File

@@ -60,7 +60,17 @@ confidence=
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=raw-checker-failed,
disable=print-statement,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
backtick,
long-suffix,
old-ne-operator,
old-octal-literal,
import-star-module-level,
non-ascii-bytes-literal,
raw-checker-failed,
bad-inline-option,
locally-disabled,
file-ignored,
@@ -68,10 +78,67 @@ disable=raw-checker-failed,
useless-suppression,
deprecated-pragma,
use-symbolic-message-instead,
missing-function-docstring,
missing-class-docstring,
missing-module-docstring,
too-few-public-methods
apply-builtin,
basestring-builtin,
buffer-builtin,
cmp-builtin,
coerce-builtin,
execfile-builtin,
file-builtin,
long-builtin,
raw_input-builtin,
reduce-builtin,
standarderror-builtin,
unicode-builtin,
xrange-builtin,
coerce-method,
delslice-method,
getslice-method,
setslice-method,
no-absolute-import,
old-division,
dict-iter-method,
dict-view-method,
next-method-called,
metaclass-assignment,
indexing-exception,
raising-string,
reload-builtin,
oct-method,
hex-method,
nonzero-method,
cmp-method,
input-builtin,
round-builtin,
intern-builtin,
unichr-builtin,
map-builtin-not-iterating,
zip-builtin-not-iterating,
range-builtin-not-iterating,
filter-builtin-not-iterating,
using-cmp-argument,
eq-without-hash,
div-method,
idiv-method,
rdiv-method,
exception-message-attribute,
invalid-str-codec,
sys-max-int,
bad-python3-import,
deprecated-string-function,
deprecated-str-translate-call,
deprecated-itertools-function,
deprecated-types-field,
next-method-defined,
dict-items-not-iterating,
dict-keys-not-iterating,
dict-values-not-iterating,
deprecated-operator-function,
deprecated-urllib-function,
xreadlines-attribute,
deprecated-sys-function,
exception-escape,
comprehension-escape
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
@@ -225,9 +292,7 @@ good-names=i,
k,
ex,
Run,
_,
e,
db
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
@@ -390,7 +455,7 @@ indent-after-paren=4
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=120
max-line-length=100
# Maximum number of lines in a module.
max-module-lines=1000
@@ -411,6 +476,7 @@ ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
w54
# Ignore imports when computing similarities.
ignore-imports=no
@@ -518,5 +584,5 @@ valid-metaclass-classmethod-first-arg=cls
# Exceptions that will emit a warning when being caught. Defaults to
# "BaseException, Exception".
overgeneral-exceptions=builtins.BaseException,
builtins.Exception
overgeneral-exceptions=BaseException,
Exception

View File

@@ -1,3 +0,0 @@
{
"recommendations": ["lokalise.i18n-ally"]
}

25
.vscode/launch.json vendored
View File

@@ -1,25 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Mealie Backend",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": [
"mealie.app:app",
"--port",
"9000"
],
"env": {
"PRODUCTION": "False",
},
"justMyCode": false,
"jinja": true,
"preLaunchTask": "Init Database"
}
]
}

76
.vscode/settings.json vendored
View File

@@ -1,64 +1,20 @@
{
"cSpell.enableFiletypes": [
"!javascript",
"!python",
"!yaml"
],
"cSpell.words": [
"chowdown",
"compression",
"hkotel",
"nextcloud",
"performant",
"postgres",
"webp"
],
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit",
"source.organizeImports": "never"
},
"editor.formatOnSave": true,
"eslint.workingDirectories": [
"./frontend"
],
"files.exclude": {
"**/__pycache__": true,
"**/.DS_Store": true,
"**/.git": true,
"**/.hg": true,
"**/.svn": true,
"**/CVS": true
},
"i18n-ally.enabledFrameworks": [
"vue"
],
"i18n-ally.keystyle": "nested",
"i18n-ally.localesPaths": "frontend/lang/messages",
"i18n-ally.sourceLanguage": "en-US",
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",
"python.testing.autoTestDiscoverOnSaveEnabled": false,
"python.testing.pytestArgs": [
"tests"
],
"python.testing.pytestEnabled": true,
"python.formatting.provider": "black",
"python.pythonPath": ".venv/bin/python3.9",
"python.linting.pylintEnabled": false,
"python.linting.enabled": true,
"python.testing.unittestEnabled": false,
"python.analysis.typeCheckingMode": "off",
"python.testing.nosetestsEnabled": false,
"python.testing.pytestEnabled": true,
"python.testing.autoTestDiscoverOnSaveEnabled": false,
"python.testing.pytestArgs": ["tests"],
"cSpell.enableFiletypes": ["!javascript", "!python", "!yaml"],
"i18n-ally.localesPaths": "frontend/src/locales/messages",
"i18n-ally.sourceLanguage": "en-US",
"i18n-ally.enabledFrameworks": ["vue"],
"i18n-ally.keystyle": "nested",
"cSpell.words": ["compression", "hkotel", "performant", "postgres", "webp"],
"search.mode": "reuseEditor",
"python.testing.unittestArgs": [
"-v",
"-s",
"./tests",
"-p",
"test_*.py"
],
"explorer.fileNesting.enabled": true,
"explorer.fileNesting.patterns": {
"package.json": "package-lock.json, yarn.lock, .eslintrc.js, tsconfig.json, .prettierrc, .editorconfig",
"pyproject.toml": "poetry.lock, alembic.ini, .pylintrc",
"netlify.toml": "runtime.txt",
"README.md": "LICENSE, SECURITY.md"
},
"[vue]": {
"editor.formatOnSave": false
}
"python.linting.flake8Enabled": true,
"conventionalCommits.scopes": ["frontend"]
}

27
.vscode/tasks.json vendored
View File

@@ -2,13 +2,22 @@
"version": "2.0.0",
"tasks": [
{
"label": "Production: Build and Start Docker Compose",
"command": "task docker:prod",
"label": "DEV: Build and Start Docker Compose",
"command": "make docker-dev",
"type": "shell",
"args": [],
"problemMatcher": [
"$tsc"
],
"problemMatcher": ["$tsc"],
"presentation": {
"reveal": "always"
},
"group": "test"
},
{
"label": "Production: Build and Start Docker Compose",
"command": "make docker-prod",
"type": "shell",
"args": [],
"problemMatcher": ["$tsc"],
"presentation": {
"reveal": "always"
},
@@ -16,7 +25,7 @@
},
{
"label": "Dev: Start Backend",
"command": "task py",
"command": "make backend",
"type": "shell",
"presentation": {
"reveal": "always",
@@ -26,7 +35,7 @@
},
{
"label": "Dev: Start Frontend",
"command": "task ui",
"command": "make frontend",
"type": "shell",
"presentation": {
"reveal": "always",
@@ -36,7 +45,7 @@
},
{
"label": "Dev: Start Docs Server",
"command": "task docs",
"command": "make docs",
"type": "shell",
"presentation": {
"reveal": "always",
@@ -46,7 +55,7 @@
},
{
"label": "Run python tests",
"command": "task py:test",
"command": "make test",
"type": "shell",
"presentation": {
"reveal": "always"

34
Caddyfile Normal file
View File

@@ -0,0 +1,34 @@
{
auto_https off
admin off
}
:80 {
@proxied path /api/* /docs /openapi.json
@static {
file
path *.ico *.css *.js *.gif *.jpg *.jpeg *.png *.svg *.woff *.woff2 *.webp
}
encode gzip zstd
# Handles Recipe Images / Assets
handle_path /api/media/recipes/* {
header @static Cache-Control max-age=31536000
root * /app/data/recipes/
file_server
}
handle @proxied {
uri strip_suffix /
reverse_proxy http://127.0.0.1:9000
}
handle {
header @static Cache-Control max-age=31536000
root * /app/dist
try_files {path}.html {path} /
file_server
}
}

142
Dockerfile Normal file
View File

@@ -0,0 +1,142 @@
###############################################
# Frontend Builder Image
###############################################
FROM node:lts-alpine as frontend-build
WORKDIR /app
COPY ./frontend/package*.json ./
RUN npm install
COPY ./frontend/ .
RUN npm run build
###############################################
# Base Image
###############################################
FROM python:3.9-slim as python-base
ENV MEALIE_HOME="/app"
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_NO_CACHE_DIR=off \
PIP_DISABLE_PIP_VERSION_CHECK=on \
PIP_DEFAULT_TIMEOUT=100 \
POETRY_HOME="/opt/poetry" \
POETRY_VIRTUALENVS_IN_PROJECT=true \
POETRY_NO_INTERACTION=1 \
PYSETUP_PATH="/opt/pysetup" \
VENV_PATH="/opt/pysetup/.venv"
# prepend poetry and venv to path
ENV PATH="$POETRY_HOME/bin:$VENV_PATH/bin:$PATH"
# create user account
RUN useradd -u 911 -U -d $MEALIE_HOME -s /bin/bash abc \
&& usermod -G users abc \
&& mkdir $MEALIE_HOME
###############################################
# Builder Image
###############################################
FROM python-base as builder-base
RUN apt-get update \
&& apt-get install --no-install-recommends -y \
curl \
build-essential \
libpq-dev \
libwebp-dev \
# LDAP Dependencies
libsasl2-dev libldap2-dev libssl-dev \
gnupg gnupg2 gnupg1 \
debian-keyring \
debian-archive-keyring \
apt-transport-https \
&& curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | apt-key add - \
&& curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list \
&& apt-get update \
&& apt-get install --no-install-recommends -y \
caddy \
&& pip install -U --no-cache-dir pip
# install poetry - respects $POETRY_VERSION & $POETRY_HOME
ENV POETRY_VERSION=1.1.6
RUN curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/install-poetry.py | python -
# copy project requirement files here to ensure they will be cached.
WORKDIR $PYSETUP_PATH
COPY ./poetry.lock ./pyproject.toml ./
# install runtime deps - uses $POETRY_VIRTUALENVS_IN_PROJECT internally
RUN poetry install -E pgsql --no-dev
###############################################
# Development Image
###############################################
FROM python-base as development
ENV PRODUCTION=false
# copying poetry and venv into image
COPY --from=builder-base $POETRY_HOME $POETRY_HOME
COPY --from=builder-base $PYSETUP_PATH $PYSETUP_PATH
# copy backend
COPY ./mealie $MEALIE_HOME/mealie
COPY ./poetry.lock ./pyproject.toml $MEALIE_HOME/
#! Future
# COPY ./alembic ./alembic.ini $MEALIE_HOME/
# venv already has runtime deps installed we get a quicker install
WORKDIR $MEALIE_HOME
RUN . $VENV_PATH/bin/activate && poetry install
WORKDIR /
RUN chmod +x $MEALIE_HOME/mealie/run.sh
ENTRYPOINT $MEALIE_HOME/mealie/run.sh "reload"
###############################################
# Production Image
###############################################
FROM python-base as production
ENV PRODUCTION=true
# curl for used by healthcheck
RUN apt-get update \
&& apt-get install --no-install-recommends -y \
curl \
&& apt-get autoremove \
&& rm -rf /var/lib/apt/lists/*
# copying poetry and venv into image
COPY --from=builder-base $POETRY_HOME $POETRY_HOME
COPY --from=builder-base $PYSETUP_PATH $PYSETUP_PATH
# copying caddy into image
COPY --from=builder-base /usr/bin/caddy /usr/bin/caddy
# copy backend
COPY ./mealie $MEALIE_HOME/mealie
COPY ./poetry.lock ./pyproject.toml $MEALIE_HOME/
COPY ./gunicorn_conf.py $MEALIE_HOME
#! Future
# COPY ./alembic ./alembic.ini $MEALIE_HOME/
# venv already has runtime deps installed we get a quicker install
WORKDIR $MEALIE_HOME
RUN . $VENV_PATH/bin/activate && poetry install -E pgsql --no-dev
WORKDIR /
# copy frontend
COPY --from=frontend-build /app/dist $MEALIE_HOME/dist
COPY ./dev/data/templates $MEALIE_HOME/data/templates
COPY ./Caddyfile $MEALIE_HOME
VOLUME [ "$MEALIE_HOME/data/" ]
ENV APP_PORT=80
EXPOSE ${APP_PORT}
HEALTHCHECK CMD curl -fs http://localhost:${APP_PORT} || exit 1
RUN chmod +x $MEALIE_HOME/mealie/run.sh
ENTRYPOINT $MEALIE_HOME/mealie/run.sh

682
LICENSE
View File

@@ -1,661 +1,21 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
MIT License
Copyright (c) 2020, Hayden Kotelman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,3 +0,0 @@
# Maintainers Guide
See -> [/docs/docs/contributors/developers-guide/maintainers.md](/docs/docs/contributors/developers-guide/maintainers.md)

133
README.md
View File

@@ -1,15 +1,19 @@
[![Latest Release][latest-release-shield]][latest-release-url]
[![Contributors][contributors-shield]][contributors-url]
[![Forks][forks-shield]][forks-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
[![AGPL License][license-shield]][license-url]
[![Docker Pulls][docker-pull]][docker-url]
[![GHCR Pulls][ghcr-pulls]][ghcr-url]
[![MIT License][license-shield]][license-url]
[![Docker Pulls][docker-pull]][docker-pull]
[![CodeFactor](https://www.codefactor.io/repository/github/hay-kot/mealie/badge)](https://www.codefactor.io/repository/github/hay-kot/mealie)
[![Docker Build Production](https://github.com/hay-kot/mealie/actions/workflows/dockerbuild.release.yml/badge.svg)](https://github.com/hay-kot/mealie/actions/workflows/dockerbuild.release.yml)
[![Project Tests Production](https://github.com/hay-kot/mealie/actions/workflows/test-all.yml/badge.svg)](https://github.com/hay-kot/mealie/actions/workflows/test-all.yml)
[![Docker Build Dev](https://github.com/hay-kot/mealie/actions/workflows/dockerbuild.dev.yml/badge.svg?branch=dev)](https://github.com/hay-kot/mealie/actions/workflows/dockerbuild.dev.yml)
[![Project Tests Dev](https://github.com/hay-kot/mealie/actions/workflows/test-all.yml/badge.svg?branch=dev)](https://github.com/hay-kot/mealie/actions/workflows/test-all.yml)
<!-- PROJECT LOGO -->
<br />
<p align="center">
<a href="https://github.com/mealie-recipes/mealie">
<a href="https://github.com/hay-kot/mealie">
<svg style="width:100px;height:100px" viewBox="0 0 24 24">
<path fill="currentColor" d="M8.1,13.34L3.91,9.16C2.35,7.59 2.35,5.06 3.91,3.5L10.93,10.5L8.1,13.34M13.41,13L20.29,19.88L18.88,21.29L12,14.41L5.12,21.29L3.71,19.88L13.36,10.22L13.16,10C12.38,9.23 12.38,7.97 13.16,7.19L17.5,2.82L18.43,3.74L15.19,7L16.15,7.94L19.39,4.69L20.31,5.61L17.06,8.85L18,9.81L21.26,6.56L22.18,7.5L17.81,11.84C17.03,12.62 15.77,12.62 15,11.84L14.78,11.64L13.41,13Z" />
</svg>
@@ -18,89 +22,110 @@
<h3 align="center">Mealie</h3>
<p align="center">
A Place For All Your Recipes
A Place for All Your Recipes
<br />
<a href="https://docs.mealie.io/"><strong>Explore the docs »</strong></a>
<a href="https://github.com/mealie-recipes/mealie">
<a href="https://hay-kot.github.io/mealie/"><strong>Explore the docs »</strong></a>
<a href="https://github.com/hay-kot/mealie">
</a>
<br />
<a href="https://demo.mealie.io/">View Demo</a>
<a href="https://mealie-demo.hay-kot.dev/">View Demo</a>
·
<a href="https://github.com/mealie-recipes/mealie/issues">Report Bug</a>
<a href="https://github.com/hay-kot/mealie/issues">Report Bug</a>
·
<a href="https://github.com/mealie-recipes/mealie/pkgs/container/mealie">GitHub Container Registry</a>
<a href="https://hay-kot.github.io/mealie/api/redoc/">API</a>
·
<a href="https://github.com/hay-kot/mealie/issues">
Request Feature
</a>
·
<a href="https://hub.docker.com/r/hkotel/mealie"> Docker Hub
</a>
</p>
[![Product Name Screen Shot][product-screenshot]](https://docs.mealie.io)
[![Product Name Screen Shot][product-screenshot]](https://example.com)
# About The Project
Mealie is a self hosted recipe manager, meal planner and shopping list with a RestAPI backend and a reactive frontend built in Vue for a pleasant user experience for the whole family. Easily add recipes into your database by providing the URL and Mealie will automatically import the relevant data, or add a family recipe with the UI editor. Mealie also provides an API for interactions from 3rd party applications.
Mealie is a self hosted recipe manager and meal planner with a RestAPI backend and a reactive frontend application built in Vue for a pleasant user experience for the whole family. Easily add recipes into your database by providing the url and Mealie will automatically import the relevant data or add a family recipe with the UI editor. Mealie also provides an API for interactions from 3rd party applications.
[Remember to join the Discord](https://discord.gg/QuStdQGSGK)!
- [Remember to join the Discord](https://discord.gg/QuStdQGSGK)!
- [Documentation](https://docs.mealie.io/)
## Key Features
- Recipe imports: Create recipes, by **importing from a URL** or entering data manually
- Meal Planner: Use the **Meal Planner** to plan your what you'll cook for the next week
- Shopping List: Put the necessary ingredients on your **Shopping List**, organised into sections of your local supermarket
- Cookbooks: Group recipes into **Cookbooks** based on your own criteria
- Docker: Easy **Docker** deployment
- Localisation: **Translations** for 35+ languages
- 🔍 Fuzzy search
- 🏷️ Tag recipes with categories or tags for flexible sorting
- 🕸 Import recipes from around the web by URL
- 💪 Powerful bulk Category/Tag assignment
- 📱 Beautiful Mobile Views
- 📆 Create Meal Plans
- 🛒 Generate shopping lists
- 🐳 Easy setup with Docker
- 🎨 Customize your interface with color themes
- 💾 Export all your data in any format with Jinja2 Templates
- 🔒 Keep your data safe with automated backup and easy restore options
- 🌍 localized in many languages
- Plus tons more!
- Flexible API
- Custom key/value pairs for recipes
- Webhook support
- Interactive API Documentation thanks to [FastAPI](https://fastapi.tiangolo.com/) and [Swagger](https://petstore.swagger.io/)
- Raw JSON Recipe Editor
- Migration from other platforms
- Chowdown
- Nextcloud Cookbook
- Random meal plan generation
## FAQ
### Why An API?
An API allows integration into applications like [Home Assistant](https://www.home-assistant.io/) that can act as notification engines to provide custom notifications based of Meal Plan data to remind you to defrost the chicken, marinade the steak, or start the CrockPot. Additionally, you can access nearly any backend service via the API giving you total control to extend the application. To explore the API spin up your server and navigate to http://yourserver.com/docs for interactive API documentation.
### Why a Database?
Some users of static-site generator applications like ChowDown have expressed concerns about their data being stuck in a database. Considering this is a new project it is a valid concern to be worried about your data. Mealie specifically addresses this concern by provided automatic daily backups that export your data in json, plain-text markdown files, and/or custom Jinja2 templates. **This puts you in controls of how your data is represented** when exported from Mealie, which means you can easily migrate to any other service provided Mealie doesn't work for you.
As to why we need a database?
- **Developer Experience:** Without a database a lot of the work to maintain your data is taken on by the developer instead of a battle tested platform for storing data.
- **Multi User Support:** With a solid database as backend storage for your data Mealie can better support multi-user sites and avoid read/write access errors when multiple actions are taken at the same time.
<!-- CONTRIBUTING -->
## Contributing
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**. If you're going to be working on the code-base, you'll want to use the nightly documentation to ensure you get the latest information.
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**. Especially test. Literally any tests. See the [Contributors Guide](https://hay-kot.github.io/mealie/contributors/non-coders/) for help getting started.
- See the [Contributors Guide](https://nightly.mealie.io/contributors/developers-guide/code-contributions/) for help getting started.
- We use [VSCode Dev Containers](https://code.visualstudio.com/docs/remote/containers) to make it easy for contributors to get started!
If you are not a coder, you can still contribute financially. Financial contributions help me prioritize working on this project over others and helps me know that there is a real demand for project development.
If you are not a coder, you can still contribute financially. financial contributions help me prioritize working on this project over others and helps me know that there is a real demand for project development.
<a href="https://www.buymeacoffee.com/haykot" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-green.png" alt="Buy Me A Coffee" style="height: 30px !important;width: 107px !important;" ></a>
### Translations
Translations can be a great way for **non-coders** to contribute to the project. We use [Crowdin](https://crowdin.com/project/mealie) to allow several contributors to work on translating Mealie. You can simply help by voting for your preferred translations, or even by completely translating Mealie into a new language.
For more information, check out the translation page on the [contributor's guide](https://nightly.mealie.io/contributors/translating/).
<!-- LICENSE -->
## License
Distributed under the AGPL License. See `LICENSE` for more information.
Distributed under the MIT License. See `LICENSE` for more information.
## Sponsors
Huge thanks to all the sponsors of this project on [Github Sponsors](https://github.com/sponsors/hay-kot) and Buy Me a Coffee. Without you, this project would surely not be possible.
Thanks to Depot for providing build instances for our Docker image builds.
[![Built with Depot](https://depot.dev/badges/built-with-depot.svg)](https://depot.dev?utm_source=Mealie)
<!-- CONTACT -->
## Contact
Project Link: [https://github.com/hay-kot/mealie](https://github.com/hay-kot/mealie)
<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[contributors-shield]: https://img.shields.io/github/contributors/mealie-recipes/mealie.svg?style=flat-square
[docker-pull]: https://img.shields.io/docker/pulls/hkotel/mealie?style=flat-square
[docker-url]: https://hub.docker.com/r/hkotel/mealie
[ghcr-pulls]: https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fipitio.github.io%2Fbackage%2Fmealie-recipes%2Fmealie%2Fmealie.json&query=%24.downloads&style=flat-square&label=ghcr%20pulls
[ghcr-url]: https://github.com/mealie-recipes/mealie/pkgs/container/mealie
[contributors-url]: https://github.com/mealie-recipes/mealie/graphs/contributors
[stars-shield]: https://img.shields.io/github/stars/mealie-recipes/mealie.svg?style=flat-square
[stars-url]: https://github.com/mealie-recipes/mealie/stargazers
[issues-shield]: https://img.shields.io/github/issues/mealie-recipes/mealie.svg?style=flat-square
[issues-url]: https://github.com/mealie-recipes/mealie/issues
[latest-release-shield]: https://img.shields.io/github/v/release/mealie-recipes/mealie?style=flat-square&label=latest%20release
[latest-release-url]: https://github.com/mealie-recipes/mealie/releases
[license-shield]: https://img.shields.io/github/license/mealie-recipes/mealie.svg?style=flat-square
[license-url]: https://github.com/mealie-recipes/mealie/blob/mealie-next/LICENSE
[contributors-shield]: https://img.shields.io/github/contributors/hay-kot/mealie.svg?style=flat-square
[docker-pull]: https://img.shields.io/docker/pulls/hkotel/mealie
[contributors-url]: https://github.com/hay-kot/mealie/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/hay-kot/mealie.svg?style=flat-square
[forks-url]: https://github.com/hay-kot/mealie/network/members
[stars-shield]: https://img.shields.io/github/stars/hay-kot/mealie.svg?style=flat-square
[stars-url]: https://github.com/hay-kot/mealie/stargazers
[issues-shield]: https://img.shields.io/github/issues/hay-kot/mealie.svg?style=flat-square
[issues-url]: https://github.com/hay-kot/mealie/issues
[license-shield]: https://img.shields.io/github/license/hay-kot/mealie.svg?style=flat-square
[license-url]: https://github.com/hay-kot/mealie/blob/master/LICENSE.txt
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=flat-square&logo=linkedin&colorB=555
[linkedin-url]: https://linkedin.com/in/hay-kot
[product-screenshot]: docs/docs/assets/img/home_screenshot.png

View File

@@ -1,9 +0,0 @@
# Security Policy
## Supported Versions
Since this software is still considered beta/WIP support is always only given for the latest version. Security patches are only available for the latest version and not back-ported to older versions.
## Reporting a Vulnerability
For general security vulnerabilities you're welcome to open a GitHub issues or contribute a fix. If you feel the vulnerability should not be disclosed you can open a generic issue on GitHub and email to the details to [ob92oy0sl@mozmail.com](mailto:ob92oy0sl@mozmail.com) which is monitored by the maintainer.

View File

@@ -1,191 +0,0 @@
# https://taskfile.dev
version: "3"
vars:
GREETING: Hello, World!
env:
DEFAULT_GROUP: Home
DEFAULT_HOUSEHOLD: Family
PRODUCTION: false
API_PORT: 9000
API_DOCS: True
TOKEN_TIME: 256 # hours
# mailplit SMTP config
# start dev:services to use mailpit
SMTP_HOST: localhost
SMTP_PORT: 1025
SMTP_FROM_NAME: MealieDev
SMTP_FROM_EMAIL: mealie@example.com
SMTP_AUTH_STRATEGY: NONE
BASE_URL: http://localhost:3000
LANG: en-US
# loads .env file if it exists
dotenv:
- .env
- .dev.env
tasks:
docs:gen:
desc: runs the API documentation generator
cmds:
- poetry run python dev/code-generation/gen_docs_api.py
docs:
desc: runs the documentation server
dir: docs
deps:
- docs:gen
cmds:
- poetry run python -m mkdocs serve
setup:ui:
desc: setup frontend dependencies
dir: frontend
cmds:
- yarn install
setup:py:
desc: setup python dependencies
cmds:
- poetry install --with main,dev,postgres
- poetry run pre-commit install
setup:model:
desc: setup nlp model
vars:
MODEL_URL: https://github.com/mealie-recipes/nlp-model/releases/download/v1.0.0/model.crfmodel
OUTPUT: ./mealie/services/parser_services/crfpp/model.crfmodel
sources:
# using pyproject.toml as the dependency since this should only ever need to run once
# during setup. There is perhaps a better way to do this.
- ./pyproject.toml
generates:
- ./mealie/services/parser_services/crfpp/model.crfmodel
cmds:
- curl -L0 {{ .MODEL_URL }} --output {{ .OUTPUT }}
setup:
desc: setup all dependencies
deps:
- setup:ui
- setup:py
- setup:model
dev:generate:
desc: run code generators
cmds:
- poetry run python dev/code-generation/main.py
- task: py:format
dev:services:
desc: starts postgres and mailpit containers
dir: docker
cmds:
- docker compose -f docker-compose.dev.yml up
dev:clean:
desc: cleans up dev environment !! removes all data files !!
vars:
DEV_DATA: ""
cmds:
- rm -r ./dev/data/recipes/
- rm -r ./dev/data/users/
- rm -f ./dev/data/mealie*.db
- rm -f ./dev/data/mealie.log
- rm -f ./dev/data/.secret
py:mypy:
desc: runs python type checking
cmds:
- poetry run mypy mealie
py:test:
desc: runs python tests (support args after '--')
cmds:
- poetry run pytest {{ .CLI_ARGS }}
py:format:
desc: runs python code formatter
cmds:
- poetry run ruff format .
py:lint:
desc: runs python linter
cmds:
- poetry run ruff check mealie
py:check:
desc: runs all linters, type checkers, and formatters
deps:
- py:format
- py:lint
- py:mypy
- py:test
py:coverage:
desc: runs python coverage and generates html report
cmds:
- poetry run pytest
- poetry run coverage report -m
- poetry run coveragepy-lcov
- poetry run coverage html
- open htmlcov/index.html
py:
desc: runs the backend server
cmds:
- poetry run python mealie/app.py
py:postgres:
desc: runs the backend server configured for containerized postgres
env:
DB_ENGINE: postgres
POSTGRES_USER: mealie
POSTGRES_PASSWORD: mealie
POSTGRES_SERVER: localhost
POSTGRES_PORT: 5432
POSTGRES_DB: mealie
cmds:
- poetry run python mealie/app.py
py:migrate:
desc: generates a new database migration file e.g. task py:migrate -- "add new column"
cmds:
- poetry run alembic revision --autogenerate -m "{{ .CLI_ARGS }}"
- task: py:format
ui:build:
desc: builds the frontend in frontend/dist
dir: frontend
cmds:
- yarn build
ui:lint:
desc: runs the frontend linter
dir: frontend
cmds:
- yarn lint
ui:test:
desc: runs the frontend tests
dir: frontend
cmds:
- yarn test
ui:check:
desc: runs all frontend checks
deps:
- ui:lint
- ui:test
ui:
desc: runs the frontend server
dir: frontend
cmds:
- yarn run dev
docker:prod:
desc: builds and runs the production docker image locally
dir: docker
cmds:
- docker compose -f docker-compose.yml -p mealie up -d --build

View File

@@ -1,60 +0,0 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# template used to generate migration files
file_template = %%(year)d-%%(month).2d-%%(day).2d-%%(hour).2d.%%(minute).2d.%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator"
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. Valid values are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # default: use os.pathsep
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# Will be replaced in alembic/env.py with the actual url
sqlalchemy.url =
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

View File

@@ -1 +0,0 @@
Generic single-database configuration.

View File

@@ -1,109 +0,0 @@
from typing import Any
import sqlalchemy as sa
import mealie.db.models._all_models # noqa: F401
from alembic import context
from mealie.core.config import get_app_settings
from mealie.db.models._model_base import SqlAlchemyBase
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = SqlAlchemyBase.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
# Set DB url from config
settings = get_app_settings()
if not settings.DB_URL:
raise Exception("DB URL not set in config")
config.set_main_option("sqlalchemy.url", settings.DB_URL.replace("%", "%%"))
def include_object(object: Any, name: str, type_: str, reflected: bool, compare_to: Any):
# skip dropping food/unit unique constraints; they are defined manually so alembic doesn't see them
# see: revision dded3119c1fe
if type_ == "unique_constraint" and name == "ingredient_foods_name_group_id_key" and compare_to is None:
return False
if type_ == "unique_constraint" and name == "ingredient_units_name_group_id_key" and compare_to is None:
return False
# skip changing the quantity column in recipes_ingredients; it's a float on postgres, but an integer on sqlite
# see: revision 263dd6707191
if (
type_ == "column"
and name == "quantity"
and object.table.name == "recipes_ingredients"
and hasattr(compare_to, "type")
and isinstance(compare_to.type, sa.Integer)
):
return False
return True
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = sa.engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=sa.pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
user_module_prefix="mealie.db.migration_types.",
render_as_batch=True,
include_object=include_object,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View File

@@ -1,28 +0,0 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
import sqlalchemy as sa
import mealie.db.migration_types
from alembic import op
% if imports:
${imports}
% endif
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision: str | None = ${repr(down_revision)}
branch_labels: str | tuple[str, ...] | None = ${repr(branch_labels)}
depends_on: str | tuple[str, ...] | None = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}

View File

@@ -1,921 +0,0 @@
"""Initial tables
Revision ID: 6b0f5f32d602
Revises:
Create Date: 2022-02-21 19:56:24.351115
"""
import sqlalchemy as sa
from sqlalchemy import engine_from_config
import mealie.db.migration_types
from alembic import op
# revision identifiers, used by Alembic.
revision = "6b0f5f32d602"
down_revision: str | None = None
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
# Adapted from https://improveandrepeat.com/2021/09/python-friday-87-handling-pre-existing-tables-with-alembic-and-sqlalchemy/
def table_exists(table, schema=None):
config = op.get_context().config
engine = engine_from_config(config.get_section(config.config_ini_section), prefix="sqlalchemy.")
insp = sa.inspect(engine)
return insp.has_table(table, schema)
def upgrade():
# Only create initial tables if they don't exist yet, to ease transition from pre-alembic state
if table_exists("users"):
return
op.create_table(
"groups",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_groups_name"), "groups", ["name"], unique=True)
op.create_table(
"categories",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.Column("slug", sa.String(), nullable=False),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("slug", "group_id", name="category_slug_group_id_key"),
)
op.create_index(op.f("ix_categories_group_id"), "categories", ["group_id"], unique=False)
op.create_index(op.f("ix_categories_name"), "categories", ["name"], unique=False)
op.create_index(op.f("ix_categories_slug"), "categories", ["slug"], unique=False)
op.create_table(
"cookbooks",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("position", sa.Integer(), nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.Column("slug", sa.String(), nullable=False),
sa.Column("description", sa.String(), nullable=True),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"group_data_exports",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("name", sa.String(), nullable=False),
sa.Column("filename", sa.String(), nullable=False),
sa.Column("path", sa.String(), nullable=False),
sa.Column("size", sa.String(), nullable=False),
sa.Column("expires", sa.String(), nullable=False),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_group_data_exports_group_id"), "group_data_exports", ["group_id"], unique=False)
op.create_table(
"group_events_notifiers",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.Column("enabled", sa.Boolean(), nullable=False),
sa.Column("apprise_url", sa.String(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_group_events_notifiers_group_id"), "group_events_notifiers", ["group_id"], unique=False)
op.create_table(
"group_meal_plan_rules",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("day", sa.String(), nullable=False),
sa.Column("entry_type", sa.String(), nullable=False),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"group_preferences",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("private_group", sa.Boolean(), nullable=True),
sa.Column("first_day_of_week", sa.Integer(), nullable=True),
sa.Column("recipe_public", sa.Boolean(), nullable=True),
sa.Column("recipe_show_nutrition", sa.Boolean(), nullable=True),
sa.Column("recipe_show_assets", sa.Boolean(), nullable=True),
sa.Column("recipe_landscape_view", sa.Boolean(), nullable=True),
sa.Column("recipe_disable_comments", sa.Boolean(), nullable=True),
sa.Column("recipe_disable_amount", sa.Boolean(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_group_preferences_group_id"), "group_preferences", ["group_id"], unique=False)
op.create_table(
"group_reports",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.Column("status", sa.String(), nullable=False),
sa.Column("category", sa.String(), nullable=False),
sa.Column("timestamp", sa.DateTime(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_group_reports_category"), "group_reports", ["category"], unique=False)
op.create_index(op.f("ix_group_reports_group_id"), "group_reports", ["group_id"], unique=False)
op.create_table(
"ingredient_units",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=True),
sa.Column("description", sa.String(), nullable=True),
sa.Column("abbreviation", sa.String(), nullable=True),
sa.Column("fraction", sa.Boolean(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"invite_tokens",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("token", sa.String(), nullable=False),
sa.Column("uses_left", sa.Integer(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_invite_tokens_token"), "invite_tokens", ["token"], unique=True)
op.create_table(
"multi_purpose_labels",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("color", sa.String(length=10), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_multi_purpose_labels_group_id"), "multi_purpose_labels", ["group_id"], unique=False)
op.create_table(
"recipes",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("slug", sa.String(), nullable=True),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("user_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("name", sa.String(), nullable=False),
sa.Column("description", sa.String(), nullable=True),
sa.Column("image", sa.String(), nullable=True),
sa.Column("total_time", sa.String(), nullable=True),
sa.Column("prep_time", sa.String(), nullable=True),
sa.Column("perform_time", sa.String(), nullable=True),
sa.Column("cook_time", sa.String(), nullable=True),
sa.Column("recipe_yield", sa.String(), nullable=True),
sa.Column("recipeCuisine", sa.String(), nullable=True),
sa.Column("rating", sa.Integer(), nullable=True),
sa.Column("org_url", sa.String(), nullable=True),
sa.Column("date_added", sa.Date(), nullable=True),
sa.Column("date_updated", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], use_alter=True),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("slug", "group_id", name="recipe_slug_group_id_key"),
)
op.create_index(op.f("ix_recipes_group_id"), "recipes", ["group_id"], unique=False)
op.create_index(op.f("ix_recipes_slug"), "recipes", ["slug"], unique=False)
op.create_index(op.f("ix_recipes_user_id"), "recipes", ["user_id"], unique=False)
op.create_table(
"server_tasks",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("name", sa.String(), nullable=False),
sa.Column("completed_date", sa.DateTime(), nullable=True),
sa.Column("status", sa.String(), nullable=False),
sa.Column("log", sa.String(), nullable=True),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_server_tasks_group_id"), "server_tasks", ["group_id"], unique=False)
op.create_table(
"shopping_lists",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_shopping_lists_group_id"), "shopping_lists", ["group_id"], unique=False)
op.create_table(
"tags",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.Column("slug", sa.String(), nullable=False),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("slug", "group_id", name="tags_slug_group_id_key"),
)
op.create_index(op.f("ix_tags_group_id"), "tags", ["group_id"], unique=False)
op.create_index(op.f("ix_tags_name"), "tags", ["name"], unique=False)
op.create_index(op.f("ix_tags_slug"), "tags", ["slug"], unique=False)
op.create_table(
"tools",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.Column("slug", sa.String(), nullable=False),
sa.Column("on_hand", sa.Boolean(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("slug", "group_id", name="tools_slug_group_id_key"),
)
op.create_index(op.f("ix_tools_name"), "tools", ["name"], unique=True)
op.create_index(op.f("ix_tools_slug"), "tools", ["slug"], unique=True)
op.create_table(
"webhook_urls",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("enabled", sa.Boolean(), nullable=True),
sa.Column("name", sa.String(), nullable=True),
sa.Column("url", sa.String(), nullable=True),
sa.Column("time", sa.String(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_webhook_urls_group_id"), "webhook_urls", ["group_id"], unique=False)
op.create_table(
"api_extras",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("recipee_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("key_name", sa.String(), nullable=True),
sa.Column("value", sa.String(), nullable=True),
sa.ForeignKeyConstraint(
["recipee_id"],
["recipes.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"cookbooks_to_categories",
sa.Column("cookbook_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("category_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["category_id"],
["categories.id"],
),
sa.ForeignKeyConstraint(
["cookbook_id"],
["cookbooks.id"],
),
)
op.create_table(
"group_events_notifier_options",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("event_notifier_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("recipe_created", sa.Boolean(), nullable=False),
sa.Column("recipe_updated", sa.Boolean(), nullable=False),
sa.Column("recipe_deleted", sa.Boolean(), nullable=False),
sa.Column("user_signup", sa.Boolean(), nullable=False),
sa.Column("data_migrations", sa.Boolean(), nullable=False),
sa.Column("data_export", sa.Boolean(), nullable=False),
sa.Column("data_import", sa.Boolean(), nullable=False),
sa.Column("mealplan_entry_created", sa.Boolean(), nullable=False),
sa.Column("shopping_list_created", sa.Boolean(), nullable=False),
sa.Column("shopping_list_updated", sa.Boolean(), nullable=False),
sa.Column("shopping_list_deleted", sa.Boolean(), nullable=False),
sa.Column("cookbook_created", sa.Boolean(), nullable=False),
sa.Column("cookbook_updated", sa.Boolean(), nullable=False),
sa.Column("cookbook_deleted", sa.Boolean(), nullable=False),
sa.Column("tag_created", sa.Boolean(), nullable=False),
sa.Column("tag_updated", sa.Boolean(), nullable=False),
sa.Column("tag_deleted", sa.Boolean(), nullable=False),
sa.Column("category_created", sa.Boolean(), nullable=False),
sa.Column("category_updated", sa.Boolean(), nullable=False),
sa.Column("category_deleted", sa.Boolean(), nullable=False),
sa.ForeignKeyConstraint(
["event_notifier_id"],
["group_events_notifiers.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"group_meal_plans",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("date", sa.Date(), nullable=False),
sa.Column("entry_type", sa.String(), nullable=False),
sa.Column("title", sa.String(), nullable=False),
sa.Column("text", sa.String(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_group_meal_plans_date"), "group_meal_plans", ["date"], unique=False)
op.create_index(op.f("ix_group_meal_plans_entry_type"), "group_meal_plans", ["entry_type"], unique=False)
op.create_index(op.f("ix_group_meal_plans_group_id"), "group_meal_plans", ["group_id"], unique=False)
op.create_index(op.f("ix_group_meal_plans_recipe_id"), "group_meal_plans", ["recipe_id"], unique=False)
op.create_index(op.f("ix_group_meal_plans_title"), "group_meal_plans", ["title"], unique=False)
op.create_table(
"group_to_categories",
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("category_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["category_id"],
["categories.id"],
),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
)
op.create_table(
"ingredient_foods",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=True),
sa.Column("description", sa.String(), nullable=True),
sa.Column("label_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.ForeignKeyConstraint(
["label_id"],
["multi_purpose_labels.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"notes",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("title", sa.String(), nullable=True),
sa.Column("text", sa.String(), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"plan_rules_to_categories",
sa.Column("group_plan_rule_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("category_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["category_id"],
["categories.id"],
),
sa.ForeignKeyConstraint(
["group_plan_rule_id"],
["group_meal_plan_rules.id"],
),
)
op.create_table(
"plan_rules_to_tags",
sa.Column("plan_rule_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("tag_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["plan_rule_id"],
["group_meal_plan_rules.id"],
),
sa.ForeignKeyConstraint(
["tag_id"],
["tags.id"],
),
)
op.create_table(
"recipe_assets",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("name", sa.String(), nullable=True),
sa.Column("icon", sa.String(), nullable=True),
sa.Column("file_name", sa.String(), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"recipe_instructions",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("position", sa.Integer(), nullable=True),
sa.Column("type", sa.String(), nullable=True),
sa.Column("title", sa.String(), nullable=True),
sa.Column("text", sa.String(), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"recipe_nutrition",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("calories", sa.String(), nullable=True),
sa.Column("fat_content", sa.String(), nullable=True),
sa.Column("fiber_content", sa.String(), nullable=True),
sa.Column("protein_content", sa.String(), nullable=True),
sa.Column("carbohydrate_content", sa.String(), nullable=True),
sa.Column("sodium_content", sa.String(), nullable=True),
sa.Column("sugar_content", sa.String(), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"recipe_settings",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("public", sa.Boolean(), nullable=True),
sa.Column("show_nutrition", sa.Boolean(), nullable=True),
sa.Column("show_assets", sa.Boolean(), nullable=True),
sa.Column("landscape_view", sa.Boolean(), nullable=True),
sa.Column("disable_amount", sa.Boolean(), nullable=True),
sa.Column("disable_comments", sa.Boolean(), nullable=True),
sa.Column("locked", sa.Boolean(), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"recipe_share_tokens",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("expires_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_recipe_share_tokens_group_id"), "recipe_share_tokens", ["group_id"], unique=False)
op.create_table(
"recipes_to_categories",
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("category_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["category_id"],
["categories.id"],
),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
)
op.create_table(
"recipes_to_tags",
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("tag_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.ForeignKeyConstraint(
["tag_id"],
["tags.id"],
),
)
op.create_table(
"recipes_to_tools",
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("tool_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.ForeignKeyConstraint(
["tool_id"],
["tools.id"],
),
)
op.create_table(
"report_entries",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("success", sa.Boolean(), nullable=True),
sa.Column("message", sa.String(), nullable=True),
sa.Column("exception", sa.String(), nullable=True),
sa.Column("timestamp", sa.DateTime(), nullable=False),
sa.Column("report_id", mealie.db.migration_types.GUID(), nullable=False),
sa.ForeignKeyConstraint(
["report_id"],
["group_reports.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"shopping_list_recipe_reference",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("shopping_list_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("recipe_quantity", sa.Float(), nullable=False),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.ForeignKeyConstraint(
["shopping_list_id"],
["shopping_lists.id"],
),
sa.PrimaryKeyConstraint("id", "shopping_list_id"),
)
op.create_index(
op.f("ix_shopping_list_recipe_reference_recipe_id"),
"shopping_list_recipe_reference",
["recipe_id"],
unique=False,
)
op.create_table(
"users",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("full_name", sa.String(), nullable=True),
sa.Column("username", sa.String(), nullable=True),
sa.Column("email", sa.String(), nullable=True),
sa.Column("password", sa.String(), nullable=True),
sa.Column("admin", sa.Boolean(), nullable=True),
sa.Column("advanced", sa.Boolean(), nullable=True),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("cache_key", sa.String(), nullable=True),
sa.Column("can_manage", sa.Boolean(), nullable=True),
sa.Column("can_invite", sa.Boolean(), nullable=True),
sa.Column("can_organize", sa.Boolean(), nullable=True),
sa.Column("owned_recipes_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.ForeignKeyConstraint(
["owned_recipes_id"],
["recipes.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True)
op.create_index(op.f("ix_users_full_name"), "users", ["full_name"], unique=False)
op.create_index(op.f("ix_users_group_id"), "users", ["group_id"], unique=False)
op.create_index(op.f("ix_users_username"), "users", ["username"], unique=True)
op.create_table(
"long_live_tokens",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("name", sa.String(), nullable=False),
sa.Column("token", sa.String(), nullable=False),
sa.Column("user_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"password_reset_tokens",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("user_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("token", sa.String(length=64), nullable=False),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("token"),
)
op.create_table(
"recipe_comments",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("text", sa.String(), nullable=True),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("user_id", mealie.db.migration_types.GUID(), nullable=False),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"recipe_ingredient_ref_link",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("instruction_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("reference_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["instruction_id"],
["recipe_instructions.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"recipes_ingredients",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("position", sa.Integer(), nullable=True),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("title", sa.String(), nullable=True),
sa.Column("note", sa.String(), nullable=True),
sa.Column("unit_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("food_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("quantity", sa.Integer(), nullable=True),
sa.Column("reference_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["food_id"],
["ingredient_foods.id"],
),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.ForeignKeyConstraint(
["unit_id"],
["ingredient_units.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"shopping_list_items",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("shopping_list_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("is_ingredient", sa.Boolean(), nullable=True),
sa.Column("position", sa.Integer(), nullable=False),
sa.Column("checked", sa.Boolean(), nullable=True),
sa.Column("quantity", sa.Float(), nullable=True),
sa.Column("note", sa.String(), nullable=True),
sa.Column("is_food", sa.Boolean(), nullable=True),
sa.Column("unit_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("food_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("label_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["food_id"],
["ingredient_foods.id"],
),
sa.ForeignKeyConstraint(
["label_id"],
["multi_purpose_labels.id"],
),
sa.ForeignKeyConstraint(
["shopping_list_id"],
["shopping_lists.id"],
),
sa.ForeignKeyConstraint(
["unit_id"],
["ingredient_units.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"users_to_favorites",
sa.Column("user_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
)
op.create_table(
"shopping_list_item_recipe_reference",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("shopping_list_item_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("recipe_quantity", sa.Float(), nullable=False),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.ForeignKeyConstraint(
["shopping_list_item_id"],
["shopping_list_items.id"],
),
sa.PrimaryKeyConstraint("id", "shopping_list_item_id"),
)
op.create_index(
op.f("ix_shopping_list_item_recipe_reference_recipe_id"),
"shopping_list_item_recipe_reference",
["recipe_id"],
unique=False,
)
def downgrade():
op.drop_index(
op.f("ix_shopping_list_item_recipe_reference_recipe_id"), table_name="shopping_list_item_recipe_reference"
)
op.drop_table("shopping_list_item_recipe_reference")
op.drop_table("users_to_favorites")
op.drop_table("shopping_list_items")
op.drop_table("recipes_ingredients")
op.drop_table("recipe_ingredient_ref_link")
op.drop_table("recipe_comments")
op.drop_table("password_reset_tokens")
op.drop_table("long_live_tokens")
op.drop_index(op.f("ix_users_username"), table_name="users")
op.drop_index(op.f("ix_users_group_id"), table_name="users")
op.drop_index(op.f("ix_users_full_name"), table_name="users")
op.drop_index(op.f("ix_users_email"), table_name="users")
op.drop_table("users")
op.drop_index(op.f("ix_shopping_list_recipe_reference_recipe_id"), table_name="shopping_list_recipe_reference")
op.drop_table("shopping_list_recipe_reference")
op.drop_table("report_entries")
op.drop_table("recipes_to_tools")
op.drop_table("recipes_to_tags")
op.drop_table("recipes_to_categories")
op.drop_index(op.f("ix_recipe_share_tokens_group_id"), table_name="recipe_share_tokens")
op.drop_table("recipe_share_tokens")
op.drop_table("recipe_settings")
op.drop_table("recipe_nutrition")
op.drop_table("recipe_instructions")
op.drop_table("recipe_assets")
op.drop_table("plan_rules_to_tags")
op.drop_table("plan_rules_to_categories")
op.drop_table("notes")
op.drop_table("ingredient_foods")
op.drop_table("group_to_categories")
op.drop_index(op.f("ix_group_meal_plans_title"), table_name="group_meal_plans")
op.drop_index(op.f("ix_group_meal_plans_recipe_id"), table_name="group_meal_plans")
op.drop_index(op.f("ix_group_meal_plans_group_id"), table_name="group_meal_plans")
op.drop_index(op.f("ix_group_meal_plans_entry_type"), table_name="group_meal_plans")
op.drop_index(op.f("ix_group_meal_plans_date"), table_name="group_meal_plans")
op.drop_table("group_meal_plans")
op.drop_table("group_events_notifier_options")
op.drop_table("cookbooks_to_categories")
op.drop_table("api_extras")
op.drop_index(op.f("ix_webhook_urls_group_id"), table_name="webhook_urls")
op.drop_table("webhook_urls")
op.drop_index(op.f("ix_tools_slug"), table_name="tools")
op.drop_index(op.f("ix_tools_name"), table_name="tools")
op.drop_table("tools")
op.drop_index(op.f("ix_tags_slug"), table_name="tags")
op.drop_index(op.f("ix_tags_name"), table_name="tags")
op.drop_index(op.f("ix_tags_group_id"), table_name="tags")
op.drop_table("tags")
op.drop_index(op.f("ix_shopping_lists_group_id"), table_name="shopping_lists")
op.drop_table("shopping_lists")
op.drop_index(op.f("ix_server_tasks_group_id"), table_name="server_tasks")
op.drop_table("server_tasks")
op.drop_index(op.f("ix_recipes_user_id"), table_name="recipes")
op.drop_index(op.f("ix_recipes_slug"), table_name="recipes")
op.drop_index(op.f("ix_recipes_group_id"), table_name="recipes")
op.drop_table("recipes")
op.drop_index(op.f("ix_multi_purpose_labels_group_id"), table_name="multi_purpose_labels")
op.drop_table("multi_purpose_labels")
op.drop_index(op.f("ix_invite_tokens_token"), table_name="invite_tokens")
op.drop_table("invite_tokens")
op.drop_table("ingredient_units")
op.drop_index(op.f("ix_group_reports_group_id"), table_name="group_reports")
op.drop_index(op.f("ix_group_reports_category"), table_name="group_reports")
op.drop_table("group_reports")
op.drop_index(op.f("ix_group_preferences_group_id"), table_name="group_preferences")
op.drop_table("group_preferences")
op.drop_table("group_meal_plan_rules")
op.drop_index(op.f("ix_group_events_notifiers_group_id"), table_name="group_events_notifiers")
op.drop_table("group_events_notifiers")
op.drop_index(op.f("ix_group_data_exports_group_id"), table_name="group_data_exports")
op.drop_table("group_data_exports")
op.drop_table("cookbooks")
op.drop_index(op.f("ix_categories_slug"), table_name="categories")
op.drop_index(op.f("ix_categories_name"), table_name="categories")
op.drop_index(op.f("ix_categories_group_id"), table_name="categories")
op.drop_table("categories")
op.drop_index(op.f("ix_groups_name"), table_name="groups")
op.drop_table("groups")

View File

@@ -1,52 +0,0 @@
"""convert quantity from integer to float
Revision ID: 263dd6707191
Revises: 6b0f5f32d602
Create Date: 2022-03-23 17:43:34.727829
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "263dd6707191"
down_revision = "6b0f5f32d602"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def is_postgres():
return op.get_context().dialect.name == "postgresql"
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
# SQLite doesn't require migration as types are not enforced.
# Postgres Specific Migration
if is_postgres():
op.alter_column(
"recipes_ingredients",
"quantity",
type_=sa.Float(),
existing_type=sa.Integer(),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
# SQLite doesn't require migration as types are not enforced.
# Postgres Specific Migration
if is_postgres():
op.alter_column(
"recipes_ingredients",
"quantity",
type_=sa.Integer(),
existing_type=sa.Float(),
)
# ### end Alembic commands ###

View File

@@ -1,25 +0,0 @@
"""Add original_text column to recipes_ingredients
Revision ID: f1a2dbee5fe9
Revises: 263dd6707191
Create Date: 2022-03-27 19:30:28.545846
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "f1a2dbee5fe9"
down_revision = "263dd6707191"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
op.add_column("recipes_ingredients", sa.Column("original_text", sa.String(), nullable=True))
def downgrade():
op.drop_column("recipes_ingredients", "original_text")

View File

@@ -1,58 +0,0 @@
"""add tags to cookbooks
Revision ID: 59eb59135381
Revises: f1a2dbee5fe9
Create Date: 2022-03-31 19:19:55.428965
"""
import sqlalchemy as sa
import mealie.db.migration_types
from alembic import op
# revision identifiers, used by Alembic.
revision = "59eb59135381"
down_revision = "f1a2dbee5fe9"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"cookbooks_to_tags",
sa.Column("cookbook_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("tag_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["cookbook_id"],
["cookbooks.id"],
),
sa.ForeignKeyConstraint(
["tag_id"],
["tags.id"],
),
)
op.create_table(
"cookbooks_to_tools",
sa.Column("cookbook_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("tool_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["cookbook_id"],
["cookbooks.id"],
),
sa.ForeignKeyConstraint(
["tool_id"],
["tools.id"],
),
)
op.add_column("cookbooks", sa.Column("public", sa.Boolean(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("cookbooks", "public")
op.drop_table("cookbooks_to_tools")
op.drop_table("cookbooks_to_tags")
# ### end Alembic commands ###

View File

@@ -1,46 +0,0 @@
"""add require_all for cookbook filters
Revision ID: 09dfc897ad62
Revises: 59eb59135381
Create Date: 2022-04-03 10:48:51.379968
"""
import sqlalchemy as sa
import mealie.db.migration_types # noqa: F401
from alembic import op
# revision identifiers, used by Alembic.
revision = "09dfc897ad62"
down_revision = "59eb59135381"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("cookbooks", sa.Column("require_all_categories", sa.Boolean(), nullable=True))
op.add_column("cookbooks", sa.Column("require_all_tags", sa.Boolean(), nullable=True))
op.add_column("cookbooks", sa.Column("require_all_tools", sa.Boolean(), nullable=True))
# Set Defaults for Existing Cookbooks
op.execute(
"""
UPDATE cookbooks
SET require_all_categories = TRUE,
require_all_tags = TRUE,
require_all_tools = TRUE
"""
)
# ### end Alembic commands ###
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("cookbooks", "require_all_tools")
op.drop_column("cookbooks", "require_all_tags")
op.drop_column("cookbooks", "require_all_categories")
# ### end Alembic commands ###

View File

@@ -1,31 +0,0 @@
"""Add use_abbreviation column to ingredients
Revision ID: ab0bae02578f
Revises: 09dfc897ad62
Create Date: 2022-06-01 11:12:06.748383
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "ab0bae02578f"
down_revision = "09dfc897ad62"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("ingredient_units", sa.Column("use_abbreviation", sa.Boolean(), nullable=True))
op.execute("UPDATE ingredient_units SET use_abbreviation = FALSE WHERE use_abbreviation IS NULL")
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("ingredient_units", "use_abbreviation")
# ### end Alembic commands ###

View File

@@ -1,32 +0,0 @@
"""add new webhook fields
Revision ID: f30cf048c228
Revises: ab0bae02578f
Create Date: 2022-06-15 21:05:34.851857
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "f30cf048c228"
down_revision = "ab0bae02578f"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("webhook_urls", sa.Column("webhook_type", sa.String(), nullable=True))
op.add_column("webhook_urls", sa.Column("scheduled_time", sa.Time(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("webhook_urls", "scheduled_time")
op.drop_column("webhook_urls", "webhook_type")
# ### end Alembic commands ###

View File

@@ -1,27 +0,0 @@
"""add login_attemps and locked_at field to user table
Revision ID: 188374910655
Revises: f30cf048c228
Create Date: 2022-08-12 19:05:59.776361
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "188374910655"
down_revision = "f30cf048c228"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
op.add_column("users", sa.Column("login_attemps", sa.Integer(), nullable=True))
op.add_column("users", sa.Column("locked_at", sa.DateTime(), nullable=True))
def downgrade():
op.drop_column("users", "locked_at")
op.drop_column("users", "login_attemps")

View File

@@ -1,28 +0,0 @@
"""Add is_ocr_recipe column to recipes
Revision ID: 089bfa50d0ed
Revises: 188374910655
Create Date: 2022-08-05 17:07:07.389271
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "089bfa50d0ed"
down_revision = "188374910655"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
op.add_column("recipes", sa.Column("is_ocr_recipe", sa.Boolean(), default=False, nullable=True))
op.execute("UPDATE recipes SET is_ocr_recipe = FALSE")
# SQLITE does not support ALTER COLUMN, so the column will stay nullable to prevent making this migration a mess
# The Recipe pydantic model and the SQL server use False as default value anyway for this column so Null should be a very rare sight
def downgrade():
op.drop_column("recipes", "is_ocr_recipe")

View File

@@ -1,73 +0,0 @@
"""add extras to shopping lists, list items, and ingredient foods
Revision ID: 44e8d670719d
Revises: 089bfa50d0ed
Create Date: 2022-08-29 13:57:40.452245
"""
import sqlalchemy as sa
import mealie.db.migration_types
from alembic import op
# revision identifiers, used by Alembic.
revision = "44e8d670719d"
down_revision = "089bfa50d0ed"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"shopping_list_extras",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("key_name", sa.String(), nullable=True),
sa.Column("value", sa.String(), nullable=True),
sa.Column("shopping_list_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["shopping_list_id"],
["shopping_lists.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"ingredient_food_extras",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("key_name", sa.String(), nullable=True),
sa.Column("value", sa.String(), nullable=True),
sa.Column("ingredient_food_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["ingredient_food_id"],
["ingredient_foods.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"shopping_list_item_extras",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("key_name", sa.String(), nullable=True),
sa.Column("value", sa.String(), nullable=True),
sa.Column("shopping_list_item_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["shopping_list_item_id"],
["shopping_list_items.id"],
),
sa.PrimaryKeyConstraint("id"),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("shopping_list_item_extras")
op.drop_table("ingredient_food_extras")
op.drop_table("shopping_list_extras")
# ### end Alembic commands ###

View File

@@ -1,51 +0,0 @@
"""add recipe_timeline_events table
Revision ID: 2ea7a807915c
Revises: 44e8d670719d
Create Date: 2022-09-27 14:53:14.111054
"""
import sqlalchemy as sa
import mealie.db.migration_types
from alembic import op
# revision identifiers, used by Alembic.
revision = "2ea7a807915c"
down_revision = "44e8d670719d"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"recipe_timeline_events",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("user_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("subject", sa.String(), nullable=False),
sa.Column("message", sa.String(), nullable=True),
sa.Column("event_type", sa.String(), nullable=True),
sa.Column("image", sa.String(), nullable=True),
sa.Column("timestamp", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
sa.PrimaryKeyConstraint("id"),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("recipe_timeline_events")
# ### end Alembic commands ###

View File

@@ -1,29 +0,0 @@
"""added recipe last made timestamp
Revision ID: 1923519381ad
Revises: 2ea7a807915c
Create Date: 2022-11-03 13:10:24.811134
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "1923519381ad"
down_revision = "2ea7a807915c"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("recipes", sa.Column("last_made", sa.DateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("recipes", "last_made")
# ### end Alembic commands ###

View File

@@ -1,30 +0,0 @@
"""add recipe_scale to shopping list item ref
Revision ID: 167eb69066ad
Revises: 1923519381ad
Create Date: 2022-11-22 03:42:45.494567
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "167eb69066ad"
down_revision = "1923519381ad"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("shopping_list_item_recipe_reference", sa.Column("recipe_scale", sa.Float(), nullable=True))
op.execute("UPDATE shopping_list_item_recipe_reference SET recipe_scale = 1")
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("shopping_list_item_recipe_reference", "recipe_scale")
# ### end Alembic commands ###

View File

@@ -1,44 +0,0 @@
"""add related user to mealplan
Revision ID: 165d943c64ee
Revises: 167eb69066ad
Create Date: 2023-01-21 16:54:44.368768
"""
import sqlalchemy as sa
import mealie.db.migration_types
from alembic import op
# revision identifiers, used by Alembic.
revision = "165d943c64ee"
down_revision = "167eb69066ad"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("group_meal_plans", schema=None) as batch_op:
batch_op.add_column(sa.Column("user_id", mealie.db.migration_types.GUID(), nullable=True))
batch_op.create_index(batch_op.f("ix_group_meal_plans_user_id"), ["user_id"], unique=False)
batch_op.create_foreign_key("fk_user_mealplans", "users", ["user_id"], ["id"])
with op.batch_alter_table("shopping_list_item_recipe_reference", schema=None) as batch_op:
batch_op.alter_column("recipe_scale", existing_type=sa.FLOAT(), nullable=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("shopping_list_item_recipe_reference", schema=None) as batch_op:
batch_op.alter_column("recipe_scale", existing_type=sa.FLOAT(), nullable=True)
with op.batch_alter_table("group_meal_plans", schema=None) as batch_op:
batch_op.drop_constraint("fk_user_mealplans", type_="foreignkey")
batch_op.drop_index(batch_op.f("ix_group_meal_plans_user_id"))
batch_op.drop_column("user_id")
# ### end Alembic commands ###

View File

@@ -1,280 +0,0 @@
"""add missing foreign key and order indices
Revision ID: ff5f73b01a7a
Revises: 165d943c64ee
Create Date: 2023-02-07 20:57:21.066927
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "ff5f73b01a7a"
down_revision = "165d943c64ee"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_index(op.f("ix_api_extras_created_at"), "api_extras", ["created_at"], unique=False)
op.create_index(op.f("ix_api_extras_recipee_id"), "api_extras", ["recipee_id"], unique=False)
op.create_index(op.f("ix_categories_created_at"), "categories", ["created_at"], unique=False)
op.create_index(op.f("ix_cookbooks_created_at"), "cookbooks", ["created_at"], unique=False)
op.create_index(op.f("ix_cookbooks_group_id"), "cookbooks", ["group_id"], unique=False)
op.create_index(op.f("ix_cookbooks_slug"), "cookbooks", ["slug"], unique=False)
op.create_index(
op.f("ix_cookbooks_to_categories_category_id"), "cookbooks_to_categories", ["category_id"], unique=False
)
op.create_index(
op.f("ix_cookbooks_to_categories_cookbook_id"), "cookbooks_to_categories", ["cookbook_id"], unique=False
)
op.create_index(op.f("ix_cookbooks_to_tags_cookbook_id"), "cookbooks_to_tags", ["cookbook_id"], unique=False)
op.create_index(op.f("ix_cookbooks_to_tags_tag_id"), "cookbooks_to_tags", ["tag_id"], unique=False)
op.create_index(op.f("ix_cookbooks_to_tools_cookbook_id"), "cookbooks_to_tools", ["cookbook_id"], unique=False)
op.create_index(op.f("ix_cookbooks_to_tools_tool_id"), "cookbooks_to_tools", ["tool_id"], unique=False)
op.create_index(op.f("ix_group_data_exports_created_at"), "group_data_exports", ["created_at"], unique=False)
op.create_index(
op.f("ix_group_events_notifier_options_created_at"),
"group_events_notifier_options",
["created_at"],
unique=False,
)
op.create_index(
op.f("ix_group_events_notifiers_created_at"), "group_events_notifiers", ["created_at"], unique=False
)
op.create_index(op.f("ix_group_meal_plan_rules_created_at"), "group_meal_plan_rules", ["created_at"], unique=False)
op.create_index(op.f("ix_group_meal_plan_rules_group_id"), "group_meal_plan_rules", ["group_id"], unique=False)
op.create_index(op.f("ix_group_meal_plans_created_at"), "group_meal_plans", ["created_at"], unique=False)
op.create_index(op.f("ix_group_preferences_created_at"), "group_preferences", ["created_at"], unique=False)
op.create_index(op.f("ix_group_reports_created_at"), "group_reports", ["created_at"], unique=False)
op.create_index(op.f("ix_group_to_categories_category_id"), "group_to_categories", ["category_id"], unique=False)
op.create_index(op.f("ix_group_to_categories_group_id"), "group_to_categories", ["group_id"], unique=False)
op.create_index(op.f("ix_groups_created_at"), "groups", ["created_at"], unique=False)
op.create_index(
op.f("ix_ingredient_food_extras_created_at"), "ingredient_food_extras", ["created_at"], unique=False
)
op.create_index(
op.f("ix_ingredient_food_extras_ingredient_food_id"),
"ingredient_food_extras",
["ingredient_food_id"],
unique=False,
)
op.create_index(op.f("ix_ingredient_foods_created_at"), "ingredient_foods", ["created_at"], unique=False)
op.create_index(op.f("ix_ingredient_foods_group_id"), "ingredient_foods", ["group_id"], unique=False)
op.create_index(op.f("ix_ingredient_foods_label_id"), "ingredient_foods", ["label_id"], unique=False)
op.create_index(op.f("ix_ingredient_units_created_at"), "ingredient_units", ["created_at"], unique=False)
op.create_index(op.f("ix_ingredient_units_group_id"), "ingredient_units", ["group_id"], unique=False)
op.create_index(op.f("ix_invite_tokens_created_at"), "invite_tokens", ["created_at"], unique=False)
op.create_index(op.f("ix_invite_tokens_group_id"), "invite_tokens", ["group_id"], unique=False)
op.create_index(op.f("ix_long_live_tokens_created_at"), "long_live_tokens", ["created_at"], unique=False)
op.create_index(op.f("ix_long_live_tokens_token"), "long_live_tokens", ["token"], unique=False)
op.create_index(op.f("ix_long_live_tokens_user_id"), "long_live_tokens", ["user_id"], unique=False)
op.create_index(op.f("ix_multi_purpose_labels_created_at"), "multi_purpose_labels", ["created_at"], unique=False)
op.create_index(op.f("ix_notes_created_at"), "notes", ["created_at"], unique=False)
op.create_index(op.f("ix_notes_recipe_id"), "notes", ["recipe_id"], unique=False)
op.create_index(op.f("ix_password_reset_tokens_created_at"), "password_reset_tokens", ["created_at"], unique=False)
op.create_index(op.f("ix_password_reset_tokens_user_id"), "password_reset_tokens", ["user_id"], unique=False)
op.create_index(
op.f("ix_plan_rules_to_categories_category_id"), "plan_rules_to_categories", ["category_id"], unique=False
)
op.create_index(
op.f("ix_plan_rules_to_categories_group_plan_rule_id"),
"plan_rules_to_categories",
["group_plan_rule_id"],
unique=False,
)
op.create_index(op.f("ix_plan_rules_to_tags_plan_rule_id"), "plan_rules_to_tags", ["plan_rule_id"], unique=False)
op.create_index(op.f("ix_plan_rules_to_tags_tag_id"), "plan_rules_to_tags", ["tag_id"], unique=False)
op.create_index(op.f("ix_recipe_assets_created_at"), "recipe_assets", ["created_at"], unique=False)
op.create_index(op.f("ix_recipe_assets_recipe_id"), "recipe_assets", ["recipe_id"], unique=False)
op.create_index(op.f("ix_recipe_comments_created_at"), "recipe_comments", ["created_at"], unique=False)
op.create_index(op.f("ix_recipe_comments_recipe_id"), "recipe_comments", ["recipe_id"], unique=False)
op.create_index(op.f("ix_recipe_comments_user_id"), "recipe_comments", ["user_id"], unique=False)
op.create_index(
op.f("ix_recipe_ingredient_ref_link_created_at"), "recipe_ingredient_ref_link", ["created_at"], unique=False
)
op.create_index(
op.f("ix_recipe_ingredient_ref_link_instruction_id"),
"recipe_ingredient_ref_link",
["instruction_id"],
unique=False,
)
op.create_index(
op.f("ix_recipe_ingredient_ref_link_reference_id"), "recipe_ingredient_ref_link", ["reference_id"], unique=False
)
op.create_index(op.f("ix_recipe_instructions_created_at"), "recipe_instructions", ["created_at"], unique=False)
op.create_index(op.f("ix_recipe_instructions_position"), "recipe_instructions", ["position"], unique=False)
op.create_index(op.f("ix_recipe_instructions_recipe_id"), "recipe_instructions", ["recipe_id"], unique=False)
op.create_index(op.f("ix_recipe_nutrition_created_at"), "recipe_nutrition", ["created_at"], unique=False)
op.create_index(op.f("ix_recipe_nutrition_recipe_id"), "recipe_nutrition", ["recipe_id"], unique=False)
op.create_index(op.f("ix_recipe_settings_created_at"), "recipe_settings", ["created_at"], unique=False)
op.create_index(op.f("ix_recipe_settings_recipe_id"), "recipe_settings", ["recipe_id"], unique=False)
op.create_index(op.f("ix_recipe_share_tokens_created_at"), "recipe_share_tokens", ["created_at"], unique=False)
op.create_index(op.f("ix_recipe_share_tokens_recipe_id"), "recipe_share_tokens", ["recipe_id"], unique=False)
op.create_index(
op.f("ix_recipe_timeline_events_created_at"), "recipe_timeline_events", ["created_at"], unique=False
)
op.create_index(op.f("ix_recipe_timeline_events_recipe_id"), "recipe_timeline_events", ["recipe_id"], unique=False)
op.create_index(op.f("ix_recipe_timeline_events_timestamp"), "recipe_timeline_events", ["timestamp"], unique=False)
op.create_index(op.f("ix_recipe_timeline_events_user_id"), "recipe_timeline_events", ["user_id"], unique=False)
op.create_index(op.f("ix_recipes_created_at"), "recipes", ["created_at"], unique=False)
op.create_index(op.f("ix_recipes_name"), "recipes", ["name"], unique=False)
op.create_index(op.f("ix_recipes_ingredients_created_at"), "recipes_ingredients", ["created_at"], unique=False)
op.create_index(op.f("ix_recipes_ingredients_food_id"), "recipes_ingredients", ["food_id"], unique=False)
op.create_index(op.f("ix_recipes_ingredients_position"), "recipes_ingredients", ["position"], unique=False)
op.create_index(op.f("ix_recipes_ingredients_unit_id"), "recipes_ingredients", ["unit_id"], unique=False)
op.create_index(
op.f("ix_recipes_to_categories_category_id"), "recipes_to_categories", ["category_id"], unique=False
)
op.create_index(op.f("ix_recipes_to_categories_recipe_id"), "recipes_to_categories", ["recipe_id"], unique=False)
op.create_index(op.f("ix_recipes_to_tags_recipe_id"), "recipes_to_tags", ["recipe_id"], unique=False)
op.create_index(op.f("ix_recipes_to_tags_tag_id"), "recipes_to_tags", ["tag_id"], unique=False)
op.create_index(op.f("ix_recipes_to_tools_recipe_id"), "recipes_to_tools", ["recipe_id"], unique=False)
op.create_index(op.f("ix_recipes_to_tools_tool_id"), "recipes_to_tools", ["tool_id"], unique=False)
op.create_index(op.f("ix_report_entries_created_at"), "report_entries", ["created_at"], unique=False)
op.create_index(op.f("ix_report_entries_report_id"), "report_entries", ["report_id"], unique=False)
op.create_index(op.f("ix_server_tasks_created_at"), "server_tasks", ["created_at"], unique=False)
op.create_index(op.f("ix_shopping_list_extras_created_at"), "shopping_list_extras", ["created_at"], unique=False)
op.create_index(
op.f("ix_shopping_list_extras_shopping_list_id"), "shopping_list_extras", ["shopping_list_id"], unique=False
)
op.create_index(
op.f("ix_shopping_list_item_extras_created_at"), "shopping_list_item_extras", ["created_at"], unique=False
)
op.create_index(
op.f("ix_shopping_list_item_extras_shopping_list_item_id"),
"shopping_list_item_extras",
["shopping_list_item_id"],
unique=False,
)
op.create_index(
op.f("ix_shopping_list_item_recipe_reference_created_at"),
"shopping_list_item_recipe_reference",
["created_at"],
unique=False,
)
op.create_index(op.f("ix_shopping_list_items_created_at"), "shopping_list_items", ["created_at"], unique=False)
op.create_index(op.f("ix_shopping_list_items_position"), "shopping_list_items", ["position"], unique=False)
op.create_index(
op.f("ix_shopping_list_items_shopping_list_id"), "shopping_list_items", ["shopping_list_id"], unique=False
)
op.create_index(
op.f("ix_shopping_list_recipe_reference_created_at"),
"shopping_list_recipe_reference",
["created_at"],
unique=False,
)
op.create_index(op.f("ix_shopping_lists_created_at"), "shopping_lists", ["created_at"], unique=False)
op.create_index(op.f("ix_tags_created_at"), "tags", ["created_at"], unique=False)
op.create_index(op.f("ix_tools_created_at"), "tools", ["created_at"], unique=False)
op.create_index(op.f("ix_tools_group_id"), "tools", ["group_id"], unique=False)
op.create_index(op.f("ix_users_created_at"), "users", ["created_at"], unique=False)
op.create_index(op.f("ix_users_to_favorites_recipe_id"), "users_to_favorites", ["recipe_id"], unique=False)
op.create_index(op.f("ix_users_to_favorites_user_id"), "users_to_favorites", ["user_id"], unique=False)
op.create_index(op.f("ix_webhook_urls_created_at"), "webhook_urls", ["created_at"], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_webhook_urls_created_at"), table_name="webhook_urls")
op.drop_index(op.f("ix_users_to_favorites_user_id"), table_name="users_to_favorites")
op.drop_index(op.f("ix_users_to_favorites_recipe_id"), table_name="users_to_favorites")
op.drop_index(op.f("ix_users_created_at"), table_name="users")
op.drop_index(op.f("ix_tools_group_id"), table_name="tools")
op.drop_index(op.f("ix_tools_created_at"), table_name="tools")
op.drop_index(op.f("ix_tags_created_at"), table_name="tags")
op.drop_index(op.f("ix_shopping_lists_created_at"), table_name="shopping_lists")
op.drop_index(op.f("ix_shopping_list_recipe_reference_created_at"), table_name="shopping_list_recipe_reference")
op.drop_index(op.f("ix_shopping_list_items_shopping_list_id"), table_name="shopping_list_items")
op.drop_index(op.f("ix_shopping_list_items_position"), table_name="shopping_list_items")
op.drop_index(op.f("ix_shopping_list_items_created_at"), table_name="shopping_list_items")
op.drop_index(
op.f("ix_shopping_list_item_recipe_reference_created_at"), table_name="shopping_list_item_recipe_reference"
)
op.drop_index(op.f("ix_shopping_list_item_extras_shopping_list_item_id"), table_name="shopping_list_item_extras")
op.drop_index(op.f("ix_shopping_list_item_extras_created_at"), table_name="shopping_list_item_extras")
op.drop_index(op.f("ix_shopping_list_extras_shopping_list_id"), table_name="shopping_list_extras")
op.drop_index(op.f("ix_shopping_list_extras_created_at"), table_name="shopping_list_extras")
op.drop_index(op.f("ix_server_tasks_created_at"), table_name="server_tasks")
op.drop_index(op.f("ix_report_entries_report_id"), table_name="report_entries")
op.drop_index(op.f("ix_report_entries_created_at"), table_name="report_entries")
op.drop_index(op.f("ix_recipes_to_tools_tool_id"), table_name="recipes_to_tools")
op.drop_index(op.f("ix_recipes_to_tools_recipe_id"), table_name="recipes_to_tools")
op.drop_index(op.f("ix_recipes_to_tags_tag_id"), table_name="recipes_to_tags")
op.drop_index(op.f("ix_recipes_to_tags_recipe_id"), table_name="recipes_to_tags")
op.drop_index(op.f("ix_recipes_to_categories_recipe_id"), table_name="recipes_to_categories")
op.drop_index(op.f("ix_recipes_to_categories_category_id"), table_name="recipes_to_categories")
op.drop_index(op.f("ix_recipes_ingredients_unit_id"), table_name="recipes_ingredients")
op.drop_index(op.f("ix_recipes_ingredients_position"), table_name="recipes_ingredients")
op.drop_index(op.f("ix_recipes_ingredients_food_id"), table_name="recipes_ingredients")
op.drop_index(op.f("ix_recipes_ingredients_created_at"), table_name="recipes_ingredients")
op.drop_index(op.f("ix_recipes_name"), table_name="recipes")
op.drop_index(op.f("ix_recipes_created_at"), table_name="recipes")
op.drop_index(op.f("ix_recipe_timeline_events_user_id"), table_name="recipe_timeline_events")
op.drop_index(op.f("ix_recipe_timeline_events_timestamp"), table_name="recipe_timeline_events")
op.drop_index(op.f("ix_recipe_timeline_events_recipe_id"), table_name="recipe_timeline_events")
op.drop_index(op.f("ix_recipe_timeline_events_created_at"), table_name="recipe_timeline_events")
op.drop_index(op.f("ix_recipe_share_tokens_recipe_id"), table_name="recipe_share_tokens")
op.drop_index(op.f("ix_recipe_share_tokens_created_at"), table_name="recipe_share_tokens")
op.drop_index(op.f("ix_recipe_settings_recipe_id"), table_name="recipe_settings")
op.drop_index(op.f("ix_recipe_settings_created_at"), table_name="recipe_settings")
op.drop_index(op.f("ix_recipe_nutrition_recipe_id"), table_name="recipe_nutrition")
op.drop_index(op.f("ix_recipe_nutrition_created_at"), table_name="recipe_nutrition")
op.drop_index(op.f("ix_recipe_instructions_recipe_id"), table_name="recipe_instructions")
op.drop_index(op.f("ix_recipe_instructions_position"), table_name="recipe_instructions")
op.drop_index(op.f("ix_recipe_instructions_created_at"), table_name="recipe_instructions")
op.drop_index(op.f("ix_recipe_ingredient_ref_link_reference_id"), table_name="recipe_ingredient_ref_link")
op.drop_index(op.f("ix_recipe_ingredient_ref_link_instruction_id"), table_name="recipe_ingredient_ref_link")
op.drop_index(op.f("ix_recipe_ingredient_ref_link_created_at"), table_name="recipe_ingredient_ref_link")
op.drop_index(op.f("ix_recipe_comments_user_id"), table_name="recipe_comments")
op.drop_index(op.f("ix_recipe_comments_recipe_id"), table_name="recipe_comments")
op.drop_index(op.f("ix_recipe_comments_created_at"), table_name="recipe_comments")
op.drop_index(op.f("ix_recipe_assets_recipe_id"), table_name="recipe_assets")
op.drop_index(op.f("ix_recipe_assets_created_at"), table_name="recipe_assets")
op.drop_index(op.f("ix_plan_rules_to_tags_tag_id"), table_name="plan_rules_to_tags")
op.drop_index(op.f("ix_plan_rules_to_tags_plan_rule_id"), table_name="plan_rules_to_tags")
op.drop_index(op.f("ix_plan_rules_to_categories_group_plan_rule_id"), table_name="plan_rules_to_categories")
op.drop_index(op.f("ix_plan_rules_to_categories_category_id"), table_name="plan_rules_to_categories")
op.drop_index(op.f("ix_password_reset_tokens_user_id"), table_name="password_reset_tokens")
op.drop_index(op.f("ix_password_reset_tokens_created_at"), table_name="password_reset_tokens")
op.drop_index(op.f("ix_notes_recipe_id"), table_name="notes")
op.drop_index(op.f("ix_notes_created_at"), table_name="notes")
op.drop_index(op.f("ix_multi_purpose_labels_created_at"), table_name="multi_purpose_labels")
op.drop_index(op.f("ix_long_live_tokens_user_id"), table_name="long_live_tokens")
op.drop_index(op.f("ix_long_live_tokens_token"), table_name="long_live_tokens")
op.drop_index(op.f("ix_long_live_tokens_created_at"), table_name="long_live_tokens")
op.drop_index(op.f("ix_invite_tokens_group_id"), table_name="invite_tokens")
op.drop_index(op.f("ix_invite_tokens_created_at"), table_name="invite_tokens")
op.drop_index(op.f("ix_ingredient_units_group_id"), table_name="ingredient_units")
op.drop_index(op.f("ix_ingredient_units_created_at"), table_name="ingredient_units")
op.drop_index(op.f("ix_ingredient_foods_label_id"), table_name="ingredient_foods")
op.drop_index(op.f("ix_ingredient_foods_group_id"), table_name="ingredient_foods")
op.drop_index(op.f("ix_ingredient_foods_created_at"), table_name="ingredient_foods")
op.drop_index(op.f("ix_ingredient_food_extras_ingredient_food_id"), table_name="ingredient_food_extras")
op.drop_index(op.f("ix_ingredient_food_extras_created_at"), table_name="ingredient_food_extras")
op.drop_index(op.f("ix_groups_created_at"), table_name="groups")
op.drop_index(op.f("ix_group_to_categories_group_id"), table_name="group_to_categories")
op.drop_index(op.f("ix_group_to_categories_category_id"), table_name="group_to_categories")
op.drop_index(op.f("ix_group_reports_created_at"), table_name="group_reports")
op.drop_index(op.f("ix_group_preferences_created_at"), table_name="group_preferences")
op.drop_index(op.f("ix_group_meal_plans_created_at"), table_name="group_meal_plans")
op.drop_index(op.f("ix_group_meal_plan_rules_group_id"), table_name="group_meal_plan_rules")
op.drop_index(op.f("ix_group_meal_plan_rules_created_at"), table_name="group_meal_plan_rules")
op.drop_index(op.f("ix_group_events_notifiers_created_at"), table_name="group_events_notifiers")
op.drop_index(op.f("ix_group_events_notifier_options_created_at"), table_name="group_events_notifier_options")
op.drop_index(op.f("ix_group_data_exports_created_at"), table_name="group_data_exports")
op.drop_index(op.f("ix_cookbooks_to_tools_tool_id"), table_name="cookbooks_to_tools")
op.drop_index(op.f("ix_cookbooks_to_tools_cookbook_id"), table_name="cookbooks_to_tools")
op.drop_index(op.f("ix_cookbooks_to_tags_tag_id"), table_name="cookbooks_to_tags")
op.drop_index(op.f("ix_cookbooks_to_tags_cookbook_id"), table_name="cookbooks_to_tags")
op.drop_index(op.f("ix_cookbooks_to_categories_cookbook_id"), table_name="cookbooks_to_categories")
op.drop_index(op.f("ix_cookbooks_to_categories_category_id"), table_name="cookbooks_to_categories")
op.drop_index(op.f("ix_cookbooks_slug"), table_name="cookbooks")
op.drop_index(op.f("ix_cookbooks_group_id"), table_name="cookbooks")
op.drop_index(op.f("ix_cookbooks_created_at"), table_name="cookbooks")
op.drop_index(op.f("ix_categories_created_at"), table_name="categories")
op.drop_index(op.f("ix_api_extras_recipee_id"), table_name="api_extras")
op.drop_index(op.f("ix_api_extras_created_at"), table_name="api_extras")
# ### end Alembic commands ###

View File

@@ -1,35 +0,0 @@
"""add more indices necessary for search
Revision ID: 16160bf731a0
Revises: ff5f73b01a7a
Create Date: 2023-02-10 21:18:32.405130
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "16160bf731a0"
down_revision = "ff5f73b01a7a"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_index(op.f("ix_recipe_instructions_text"), "recipe_instructions", ["text"], unique=False)
op.create_index(op.f("ix_recipes_description"), "recipes", ["description"], unique=False)
op.create_index(op.f("ix_recipes_ingredients_note"), "recipes_ingredients", ["note"], unique=False)
op.create_index(
op.f("ix_recipes_ingredients_original_text"), "recipes_ingredients", ["original_text"], unique=False
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_recipes_ingredients_original_text"), table_name="recipes_ingredients")
op.drop_index(op.f("ix_recipes_ingredients_note"), table_name="recipes_ingredients")
op.drop_index(op.f("ix_recipes_description"), table_name="recipes")
op.drop_index(op.f("ix_recipe_instructions_text"), table_name="recipe_instructions")
# ### end Alembic commands ###

View File

@@ -1,133 +0,0 @@
"""add normalized search properties
Revision ID: 5ab195a474eb
Revises: 16160bf731a0
Create Date: 2023-02-14 20:45:41.102571
"""
import sqlalchemy as sa
from sqlalchemy import orm, select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from text_unidecode import unidecode
from alembic import op
from mealie.db.models._model_utils.guid import GUID
# revision identifiers, used by Alembic.
revision = "5ab195a474eb"
down_revision = "16160bf731a0"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
class SqlAlchemyBase(DeclarativeBase):
pass
# Intermediate table definitions
class RecipeModel(SqlAlchemyBase):
__tablename__ = "recipes"
id: Mapped[GUID] = mapped_column(GUID, primary_key=True, default=GUID.generate)
name: Mapped[str] = mapped_column(sa.String, nullable=False)
description: Mapped[str | None] = mapped_column(sa.String)
name_normalized: Mapped[str] = mapped_column(sa.String, nullable=False, index=True)
description_normalized: Mapped[str | None] = mapped_column(sa.String, index=True)
class RecipeIngredient(SqlAlchemyBase):
__tablename__ = "recipes_ingredients"
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True)
note: Mapped[str | None] = mapped_column(sa.String)
original_text: Mapped[str | None] = mapped_column(sa.String)
note_normalized: Mapped[str | None] = mapped_column(sa.String, index=True)
original_text_normalized: Mapped[str | None] = mapped_column(sa.String, index=True)
def do_data_migration():
bind = op.get_bind()
session = orm.Session(bind=bind)
recipes = session.execute(select(RecipeModel)).scalars().all()
for recipe in recipes:
if recipe.name is not None:
session.execute(
sa.text(
f"UPDATE {RecipeModel.__tablename__} SET name_normalized=:name_normalized WHERE id=:id"
).bindparams(name_normalized=unidecode(recipe.name).lower().strip(), id=recipe.id)
)
if recipe.description is not None:
session.execute(
sa.text(
f"UPDATE {RecipeModel.__tablename__} SET description_normalized=:description_normalized WHERE id=:id"
).bindparams(description_normalized=unidecode(recipe.description).lower().strip(), id=recipe.id)
)
ingredients = session.execute(select(RecipeIngredient)).scalars().all()
for ingredient in ingredients:
if ingredient.note is not None:
session.execute(
sa.text(
f"UPDATE {RecipeIngredient.__tablename__} SET note_normalized=:note_normalized WHERE id=:id"
).bindparams(note_normalized=unidecode(ingredient.note).lower().strip(), id=ingredient.id)
)
if ingredient.original_text is not None:
session.execute(
sa.text(
f"UPDATE {RecipeIngredient.__tablename__} SET original_text_normalized=:original_text_normalized WHERE id=:id"
).bindparams(
original_text_normalized=unidecode(ingredient.original_text).lower().strip(), id=ingredient.id
)
)
session.commit()
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
# Set column default first, since we do not have values here yet
op.add_column("recipes", sa.Column("name_normalized", sa.String(), nullable=False, server_default=""))
op.add_column("recipes", sa.Column("description_normalized", sa.String(), nullable=True))
op.drop_index("ix_recipes_description", table_name="recipes")
op.drop_index("ix_recipes_name", table_name="recipes")
op.create_index(op.f("ix_recipes_description_normalized"), "recipes", ["description_normalized"], unique=False)
op.create_index(op.f("ix_recipes_name_normalized"), "recipes", ["name_normalized"], unique=False)
op.add_column("recipes_ingredients", sa.Column("note_normalized", sa.String(), nullable=True))
op.add_column("recipes_ingredients", sa.Column("original_text_normalized", sa.String(), nullable=True))
op.drop_index("ix_recipes_ingredients_note", table_name="recipes_ingredients")
op.drop_index("ix_recipes_ingredients_original_text", table_name="recipes_ingredients")
op.create_index(
op.f("ix_recipes_ingredients_note_normalized"), "recipes_ingredients", ["note_normalized"], unique=False
)
op.create_index(
op.f("ix_recipes_ingredients_original_text_normalized"),
"recipes_ingredients",
["original_text_normalized"],
unique=False,
)
do_data_migration()
# Remove server default now that column should be filled for all rows
with op.batch_alter_table("recipes", schema=None) as batch_op:
batch_op.alter_column("name_normalized", existing_type=sa.String(), server_default=None)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_recipes_ingredients_original_text_normalized"), table_name="recipes_ingredients")
op.drop_index(op.f("ix_recipes_ingredients_note_normalized"), table_name="recipes_ingredients")
op.create_index("ix_recipes_ingredients_original_text", "recipes_ingredients", ["original_text"], unique=False)
op.create_index("ix_recipes_ingredients_note", "recipes_ingredients", ["note"], unique=False)
op.drop_column("recipes_ingredients", "original_text_normalized")
op.drop_column("recipes_ingredients", "note_normalized")
op.drop_index(op.f("ix_recipes_name_normalized"), table_name="recipes")
op.drop_index(op.f("ix_recipes_description_normalized"), table_name="recipes")
op.create_index("ix_recipes_name", "recipes", ["name"], unique=False)
op.create_index("ix_recipes_description", "recipes", ["description"], unique=False)
op.drop_column("recipes", "description_normalized")
op.drop_column("recipes", "name_normalized")
# ### end Alembic commands ###

View File

@@ -1,90 +0,0 @@
"""added shopping list label settings
Revision ID: b04a08da2108
Revises: 5ab195a474eb
Create Date: 2023-21-02 22:03:19.837244
"""
from uuid import uuid4
import sqlalchemy as sa
from sqlalchemy import orm
import mealie.db.migration_types
from alembic import op
from mealie.db.models._model_utils.guid import GUID
# revision identifiers, used by Alembic.
revision = "b04a08da2108"
down_revision = "5ab195a474eb"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
# Intermediate table definitions
class SqlAlchemyBase(orm.DeclarativeBase):
pass
class ShoppingList(SqlAlchemyBase):
__tablename__ = "shopping_lists"
id: orm.Mapped[GUID] = orm.mapped_column(GUID, primary_key=True, default=GUID.generate)
group_id: orm.Mapped[GUID] = orm.mapped_column(GUID, sa.ForeignKey("groups.id"), nullable=False, index=True)
class MultiPurposeLabel(SqlAlchemyBase):
__tablename__ = "multi_purpose_labels"
id: orm.Mapped[GUID] = orm.mapped_column(GUID, primary_key=True, default=GUID.generate)
group_id: orm.Mapped[GUID] = orm.mapped_column(GUID, sa.ForeignKey("groups.id"), nullable=False, index=True)
def populate_shopping_lists_multi_purpose_labels(
shopping_lists_multi_purpose_labels_table: sa.Table, session: orm.Session
):
shopping_lists = session.query(ShoppingList).options(orm.load_only(ShoppingList.id, ShoppingList.group_id)).all()
shopping_lists_labels_data: list[dict] = []
for shopping_list in shopping_lists:
labels = session.query(MultiPurposeLabel).filter(MultiPurposeLabel.group_id == ShoppingList.group_id).all()
for i, label in enumerate(labels):
shopping_lists_labels_data.append(
{"id": uuid4(), "shopping_list_id": shopping_list.id, "label_id": label.id, "position": i}
)
op.bulk_insert(shopping_lists_multi_purpose_labels_table, shopping_lists_labels_data)
session.commit()
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
shopping_lists_multi_purpose_labels_table = op.create_table(
"shopping_lists_multi_purpose_labels",
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("shopping_list_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("label_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("position", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["label_id"],
["multi_purpose_labels.id"],
),
sa.ForeignKeyConstraint(
["shopping_list_id"],
["shopping_lists.id"],
),
sa.PrimaryKeyConstraint("id", "shopping_list_id", "label_id"),
)
# ### end Alembic commands ###
session = orm.Session(bind=op.get_bind())
populate_shopping_lists_multi_purpose_labels(shopping_lists_multi_purpose_labels_table, session)
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("shopping_lists_multi_purpose_labels")
# ### end Alembic commands ###

View File

@@ -1,43 +0,0 @@
"""add auth_method to user table
Revision ID: 38514b39a824
Revises: b04a08da2108
Create Date: 2023-02-22 21:45:52.900964
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "38514b39a824"
down_revision = "b04a08da2108"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def is_postgres():
return op.get_context().dialect.name == "postgresql"
authMethod = sa.Enum("MEALIE", "LDAP", name="authmethod")
def upgrade():
if is_postgres():
authMethod.create(op.get_bind())
op.add_column(
"users",
sa.Column("auth_method", authMethod, nullable=False, server_default="MEALIE"),
)
op.execute("UPDATE users SET auth_method = 'LDAP' WHERE password = 'LDAP'")
def downgrade():
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.drop_column("auth_method")
if is_postgres():
authMethod.drop(op.get_bind())

View File

@@ -1,85 +0,0 @@
"""postgres fuzzy search
Revision ID: b3dbb554ba53
Revises: 38514b39a824
Create Date: 2023-04-13 06:47:04.617131
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "b3dbb554ba53"
down_revision = "38514b39a824"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def get_db_type():
return op.get_context().dialect.name
def setup_postgres_trigrams():
op.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm;")
op.create_index(
"ix_recipes_name_normalized_gin",
table_name="recipes",
columns=["name_normalized"],
unique=False,
postgresql_using="gin",
postgresql_ops={
"name_normalized": "gin_trgm_ops",
},
)
op.create_index(
"ix_recipes_description_normalized_gin",
table_name="recipes",
columns=["description_normalized"],
unique=False,
postgresql_using="gin",
postgresql_ops={
"description_normalized": "gin_trgm_ops",
},
)
op.create_index(
"ix_recipes_ingredients_note_normalized_gin",
table_name="recipes_ingredients",
columns=["note_normalized"],
unique=False,
postgresql_using="gin",
postgresql_ops={
"note_normalized": "gin_trgm_ops",
},
)
op.create_index(
"ix_recipes_ingredients_original_text_normalized_gin",
table_name="recipes_ingredients",
columns=["original_text_normalized"],
unique=False,
postgresql_using="gin",
postgresql_ops={
"original_text_normalized": "gin_trgm_ops",
},
)
def remove_postgres_trigrams():
op.execute("DROP EXTENSION IF EXISTS pg_trgm;")
op.drop_index("ix_recipes_name_normalized_gin", table_name="recipe")
op.drop_index("ix_recipes_description_normalized_gin", table_name="recipe")
op.drop_index("ix_recipes_ingredients_note_normalized_gin", table_name="recipes_ingredients")
op.drop_index("ix_recipes_ingredients_original_text_normalized_gin", table_name="recipes_ingredients")
def upgrade():
if get_db_type() == "postgresql":
setup_postgres_trigrams()
else:
pass
def downgrade():
if get_db_type() == "postgres":
remove_postgres_trigrams()
else:
pass

View File

@@ -1,62 +0,0 @@
"""added group slug
Revision ID: 04ac51cbe9a4
Revises: b3dbb554ba53
Create Date: 2023-08-06 21:00:34.582905
"""
import sqlalchemy as sa
from slugify import slugify
from sqlalchemy.orm import Session
from alembic import op
from mealie.db.models.group.group import Group
# revision identifiers, used by Alembic.
revision = "04ac51cbe9a4"
down_revision = "b3dbb554ba53"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def populate_group_slugs(session: Session):
groups: list[Group] = session.query(Group).all()
seen_slugs: set[str] = set()
for group in groups:
original_name = group.name
new_name = original_name
attempts = 0
while True:
slug = slugify(new_name)
if slug not in seen_slugs:
break
attempts += 1
new_name = f"{original_name} ({attempts})"
seen_slugs.add(slug)
session.execute(
sa.text(f"UPDATE {Group.__tablename__} SET name=:name, slug=:slug WHERE id=:id").bindparams(
name=new_name, slug=slug, id=group.id
)
)
session.commit()
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("groups", sa.Column("slug", sa.String(), nullable=True))
op.create_index(op.f("ix_groups_slug"), "groups", ["slug"], unique=True)
# ### end Alembic commands ###
session = Session(bind=op.get_bind())
populate_group_slugs(session)
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_groups_slug"), table_name="groups")
op.drop_column("groups", "slug")
# ### end Alembic commands ###

View File

@@ -1,29 +0,0 @@
"""added recipe note to shopping list recipe ref
Revision ID: 1825b5225403
Revises: 04ac51cbe9a4
Create Date: 2023-08-14 19:30:49.103185
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "1825b5225403"
down_revision = "04ac51cbe9a4"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("shopping_list_item_recipe_reference", sa.Column("recipe_note", sa.String(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("shopping_list_item_recipe_reference", "recipe_note")
# ### end Alembic commands ###

View File

@@ -1,33 +0,0 @@
"""remove tool name and slug unique contraints
Revision ID: bcfdad6b7355
Revises: 1825b5225403
Create Date: 2023-08-15 16:25:07.058929
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "bcfdad6b7355"
down_revision = "1825b5225403"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index("ix_tools_name", table_name="tools")
op.create_index(op.f("ix_tools_name"), "tools", ["name"], unique=False)
op.drop_index("ix_tools_slug", table_name="tools")
op.create_index(op.f("ix_tools_slug"), "tools", ["slug"], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_tools_slug"), table_name="tools")
op.create_index("ix_tools_slug", "tools", ["slug"], unique=True)
op.drop_index(op.f("ix_tools_name"), table_name="tools")
op.create_index("ix_tools_name", "tools", ["name"], unique=True)
# ### end Alembic commands ###

View File

@@ -1,90 +0,0 @@
"""added normalized unit and food names
Revision ID: 0341b154f79a
Revises: bcfdad6b7355
Create Date: 2023-09-01 14:55:42.166766
"""
import sqlalchemy as sa
from sqlalchemy import orm, select
from alembic import op
from mealie.db.models.recipe.ingredient import IngredientFoodModel, IngredientUnitModel
# revision identifiers, used by Alembic.
revision = "0341b154f79a"
down_revision = "bcfdad6b7355"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def populate_normalized_fields():
bind = op.get_bind()
session = orm.Session(bind=bind)
units = (
session.execute(
select(IngredientUnitModel).options(
orm.load_only(IngredientUnitModel.name, IngredientUnitModel.abbreviation)
)
)
.scalars()
.all()
)
for unit in units:
if unit.name is not None:
session.execute(
sa.text(
f"UPDATE {IngredientUnitModel.__tablename__} SET name_normalized=:name_normalized WHERE id=:id"
).bindparams(name_normalized=IngredientUnitModel.normalize(unit.name), id=unit.id)
)
if unit.abbreviation is not None:
session.execute(
sa.text(
f"UPDATE {IngredientUnitModel.__tablename__} SET abbreviation_normalized=:abbreviation_normalized WHERE id=:id"
).bindparams(abbreviation_normalized=IngredientUnitModel.normalize(unit.abbreviation), id=unit.id)
)
foods = (
session.execute(select(IngredientFoodModel).options(orm.load_only(IngredientFoodModel.name))).scalars().all()
)
for food in foods:
if food.name is not None:
session.execute(
sa.text(
f"UPDATE {IngredientFoodModel.__tablename__} SET name_normalized=:name_normalized WHERE id=:id"
).bindparams(name_normalized=IngredientFoodModel.normalize(food.name), id=food.id)
)
session.commit()
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("ingredient_foods", sa.Column("name_normalized", sa.String(), nullable=True))
op.create_index(op.f("ix_ingredient_foods_name_normalized"), "ingredient_foods", ["name_normalized"], unique=False)
op.add_column("ingredient_units", sa.Column("name_normalized", sa.String(), nullable=True))
op.add_column("ingredient_units", sa.Column("abbreviation_normalized", sa.String(), nullable=True))
op.create_index(
op.f("ix_ingredient_units_abbreviation_normalized"),
"ingredient_units",
["abbreviation_normalized"],
unique=False,
)
op.create_index(op.f("ix_ingredient_units_name_normalized"), "ingredient_units", ["name_normalized"], unique=False)
# ### end Alembic commands ###
populate_normalized_fields()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_ingredient_units_name_normalized"), table_name="ingredient_units")
op.drop_index(op.f("ix_ingredient_units_abbreviation_normalized"), table_name="ingredient_units")
op.drop_column("ingredient_units", "abbreviation_normalized")
op.drop_column("ingredient_units", "name_normalized")
op.drop_index(op.f("ix_ingredient_foods_name_normalized"), table_name="ingredient_foods")
op.drop_column("ingredient_foods", "name_normalized")
# ### end Alembic commands ###

View File

@@ -1,306 +0,0 @@
"""added unique constraints
Revision ID: dded3119c1fe
Revises: 0341b154f79a
Create Date: 2023-10-04 14:29:26.688065
"""
from collections import defaultdict
from dataclasses import dataclass
from typing import Any
import sqlalchemy as sa
from pydantic import UUID4
from sqlalchemy import orm
from sqlalchemy.orm import Session, load_only
from alembic import op
from mealie.db.models._model_utils.guid import GUID
from mealie.db.models.labels import MultiPurposeLabel
from mealie.db.models.recipe.ingredient import IngredientFoodModel, IngredientUnitModel, RecipeIngredientModel
# revision identifiers, used by Alembic.
revision = "dded3119c1fe"
down_revision = "0341b154f79a"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
# Intermediate table definitions
class SqlAlchemyBase(orm.DeclarativeBase):
pass
class ShoppingList(SqlAlchemyBase):
__tablename__ = "shopping_lists"
id: orm.Mapped[GUID] = orm.mapped_column(GUID, primary_key=True, default=GUID.generate)
group_id: orm.Mapped[GUID] = orm.mapped_column(GUID, sa.ForeignKey("groups.id"), nullable=False, index=True)
class ShoppingListItem(SqlAlchemyBase):
__tablename__ = "shopping_list_items"
id: orm.Mapped[GUID] = orm.mapped_column(GUID, primary_key=True, default=GUID.generate)
food_id: orm.Mapped[GUID] = orm.mapped_column(GUID, sa.ForeignKey("ingredient_foods.id"))
unit_id: orm.Mapped[GUID] = orm.mapped_column(GUID, sa.ForeignKey("ingredient_units.id"))
label_id: orm.Mapped[GUID] = orm.mapped_column(GUID, sa.ForeignKey("multi_purpose_labels.id"))
@dataclass
class TableMeta:
tablename: str
pk_1: str
pk_2: str
@classmethod
def composite_pk(self, pk_1_val: Any, pk_2_val: Any) -> str:
return "$$".join([pk_1_val, pk_2_val])
def _is_postgres():
return op.get_context().dialect.name == "postgresql"
def _get_duplicates(session: Session, model: orm.DeclarativeBase) -> defaultdict[str, list]:
duplicate_map: defaultdict[str, list] = defaultdict(list)
query = session.execute(sa.text(f"SELECT id, group_id, name FROM {model.__tablename__}"))
for row in query.all():
id, group_id, name = row
key = f"{group_id}$${name}"
duplicate_map[key].append(id)
return duplicate_map
def _resolve_duplicate_food(
session: Session,
keep_food_id: UUID4,
dupe_food_id: UUID4,
):
for shopping_list_item in (
session.query(ShoppingListItem)
.options(load_only(ShoppingListItem.id, ShoppingListItem.food_id))
.filter_by(food_id=dupe_food_id)
.all()
):
shopping_list_item.food_id = keep_food_id
for recipe_ingredient in (
session.query(RecipeIngredientModel)
.options(load_only(RecipeIngredientModel.id, RecipeIngredientModel.food_id))
.filter_by(food_id=dupe_food_id)
.all()
):
recipe_ingredient.food_id = keep_food_id
session.commit()
session.execute(
sa.text(f"DELETE FROM {IngredientFoodModel.__tablename__} WHERE id=:id").bindparams(id=dupe_food_id)
)
session.commit()
def _resolve_duplicate_unit(
session: Session,
keep_unit_id: UUID4,
dupe_unit_id: UUID4,
):
for shopping_list_item in (
session.query(ShoppingListItem)
.options(load_only(ShoppingListItem.id, ShoppingListItem.unit_id))
.filter_by(unit_id=dupe_unit_id)
.all()
):
shopping_list_item.unit_id = keep_unit_id
for recipe_ingredient in (
session.query(RecipeIngredientModel)
.options(load_only(RecipeIngredientModel.id, RecipeIngredientModel.unit_id))
.filter_by(unit_id=dupe_unit_id)
.all()
):
recipe_ingredient.unit_id = keep_unit_id
session.commit()
session.execute(
sa.text(f"DELETE FROM {IngredientUnitModel.__tablename__} WHERE id=:id").bindparams(id=dupe_unit_id)
)
session.commit()
def _resolve_duplicate_label(
session: Session,
keep_label_id: UUID4,
dupe_label_id: UUID4,
):
for shopping_list_item in (
session.query(ShoppingListItem)
.options(load_only(ShoppingListItem.id, ShoppingListItem.label_id))
.filter_by(label_id=dupe_label_id)
.all()
):
shopping_list_item.label_id = keep_label_id
for ingredient_food in (
session.query(IngredientFoodModel)
.options(load_only(IngredientFoodModel.id, IngredientFoodModel.label_id))
.filter_by(label_id=dupe_label_id)
.all()
):
ingredient_food.label_id = keep_label_id
session.commit()
session.execute(sa.text(f"DELETE FROM {MultiPurposeLabel.__tablename__} WHERE id=:id").bindparams(id=dupe_label_id))
session.commit()
def _resolve_duplicate_foods_units_labels(session: Session):
for model, resolve_func in [
(IngredientFoodModel, _resolve_duplicate_food),
(IngredientUnitModel, _resolve_duplicate_unit),
(MultiPurposeLabel, _resolve_duplicate_label),
]:
duplicate_map = _get_duplicates(session, model)
for ids in duplicate_map.values():
if len(ids) < 2:
continue
keep_id = ids[0]
for dupe_id in ids[1:]:
resolve_func(session, keep_id, dupe_id)
def _remove_duplicates_from_m2m_table(session: Session, table_meta: TableMeta):
if _is_postgres():
default_pk = "CTID"
else:
default_pk = "ROWID"
# some of these tables are missing defined unique pks, so we have to rely on the database default pk
query = sa.text(
f"""
DELETE FROM {table_meta.tablename}
WHERE EXISTS (
SELECT 1 FROM {table_meta.tablename} t2
WHERE {table_meta.tablename}.{table_meta.pk_1} = t2.{table_meta.pk_1}
AND {table_meta.tablename}.{table_meta.pk_2} = t2.{table_meta.pk_2}
AND {table_meta.tablename}.{default_pk} > t2.{default_pk}
)
"""
)
session.execute(query)
session.commit()
def _remove_duplicates_from_m2m_tables(session: Session, table_metas: list[TableMeta]):
for table_meta in table_metas:
_remove_duplicates_from_m2m_table(session, table_meta)
def upgrade():
bind = op.get_bind()
session = Session(bind=bind)
_resolve_duplicate_foods_units_labels(session)
_remove_duplicates_from_m2m_tables(
session,
[
TableMeta("cookbooks_to_categories", "cookbook_id", "category_id"),
TableMeta("cookbooks_to_tags", "cookbook_id", "tag_id"),
TableMeta("cookbooks_to_tools", "cookbook_id", "tool_id"),
TableMeta("group_to_categories", "group_id", "category_id"),
TableMeta("plan_rules_to_categories", "group_plan_rule_id", "category_id"),
TableMeta("plan_rules_to_tags", "plan_rule_id", "tag_id"),
TableMeta("recipes_to_categories", "recipe_id", "category_id"),
TableMeta("recipes_to_tags", "recipe_id", "tag_id"),
TableMeta("recipes_to_tools", "recipe_id", "tool_id"),
TableMeta("users_to_favorites", "user_id", "recipe_id"),
TableMeta("shopping_lists_multi_purpose_labels", "shopping_list_id", "label_id"),
],
)
session.commit()
# ### commands auto generated by Alembic - please adjust! ###
# we use batch_alter_table here because otherwise this fails on sqlite
# M2M
with op.batch_alter_table("cookbooks_to_categories") as batch_op:
batch_op.create_unique_constraint("cookbook_id_category_id_key", ["cookbook_id", "category_id"])
with op.batch_alter_table("cookbooks_to_tags") as batch_op:
batch_op.create_unique_constraint("cookbook_id_tag_id_key", ["cookbook_id", "tag_id"])
with op.batch_alter_table("cookbooks_to_tools") as batch_op:
batch_op.create_unique_constraint("cookbook_id_tool_id_key", ["cookbook_id", "tool_id"])
with op.batch_alter_table("group_to_categories") as batch_op:
batch_op.create_unique_constraint("group_id_category_id_key", ["group_id", "category_id"])
with op.batch_alter_table("plan_rules_to_categories") as batch_op:
batch_op.create_unique_constraint("group_plan_rule_id_category_id_key", ["group_plan_rule_id", "category_id"])
with op.batch_alter_table("plan_rules_to_tags") as batch_op:
batch_op.create_unique_constraint("plan_rule_id_tag_id_key", ["plan_rule_id", "tag_id"])
with op.batch_alter_table("recipes_to_categories") as batch_op:
batch_op.create_unique_constraint("recipe_id_category_id_key", ["recipe_id", "category_id"])
with op.batch_alter_table("recipes_to_tags") as batch_op:
batch_op.create_unique_constraint("recipe_id_tag_id_key", ["recipe_id", "tag_id"])
with op.batch_alter_table("recipes_to_tools") as batch_op:
batch_op.create_unique_constraint("recipe_id_tool_id_key", ["recipe_id", "tool_id"])
with op.batch_alter_table("users_to_favorites") as batch_op:
batch_op.create_unique_constraint("user_id_recipe_id_key", ["user_id", "recipe_id"])
with op.batch_alter_table("shopping_lists_multi_purpose_labels") as batch_op:
batch_op.create_unique_constraint("shopping_list_id_label_id_key", ["shopping_list_id", "label_id"])
# Foods/Units/Labels
with op.batch_alter_table("ingredient_foods") as batch_op:
batch_op.create_unique_constraint("ingredient_foods_name_group_id_key", ["name", "group_id"])
with op.batch_alter_table("ingredient_units") as batch_op:
batch_op.create_unique_constraint("ingredient_units_name_group_id_key", ["name", "group_id"])
with op.batch_alter_table("multi_purpose_labels") as batch_op:
batch_op.create_unique_constraint("multi_purpose_labels_name_group_id_key", ["name", "group_id"])
op.create_index(
op.f("ix_shopping_lists_multi_purpose_labels_created_at"),
"shopping_lists_multi_purpose_labels",
["created_at"],
unique=False,
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
# M2M
op.drop_constraint("user_id_recipe_id_key", "users_to_favorites", type_="unique")
op.drop_index(
op.f("ix_shopping_lists_multi_purpose_labels_created_at"), table_name="shopping_lists_multi_purpose_labels"
)
op.drop_constraint("recipe_id_tool_id_key", "recipes_to_tools", type_="unique")
op.drop_constraint("recipe_id_tag_id_key", "recipes_to_tags", type_="unique")
op.drop_constraint("recipe_id_category_id_key", "recipes_to_categories", type_="unique")
op.drop_constraint("plan_rule_id_tag_id_key", "plan_rules_to_tags", type_="unique")
op.drop_constraint("group_plan_rule_id_category_id_key", "plan_rules_to_categories", type_="unique")
op.drop_constraint("group_id_category_id_key", "group_to_categories", type_="unique")
op.drop_constraint("cookbook_id_tool_id_key", "cookbooks_to_tools", type_="unique")
op.drop_constraint("cookbook_id_tag_id_key", "cookbooks_to_tags", type_="unique")
op.drop_constraint("cookbook_id_category_id_key", "cookbooks_to_categories", type_="unique")
op.drop_constraint("shopping_list_id_label_id_key", "shopping_lists_multi_purpose_labels", type_="unique")
# Foods/Units/Labels
op.drop_constraint("multi_purpose_labels_name_group_id_key", "multi_purpose_labels", type_="unique")
op.drop_constraint("ingredient_units_name_group_id_key", "ingredient_units", type_="unique")
op.drop_constraint("ingredient_foods_name_group_id_key", "ingredient_foods", type_="unique")
# ### end Alembic commands ###

View File

@@ -1,107 +0,0 @@
"""added plural names and alias tables for foods and units
Revision ID: ba1e4a6cfe99
Revises: dded3119c1fe
Create Date: 2023-10-19 19:22:55.369319
"""
import sqlalchemy as sa
import mealie.db.migration_types
from alembic import op
# revision identifiers, used by Alembic.
revision = "ba1e4a6cfe99"
down_revision = "dded3119c1fe"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"ingredient_units_aliases",
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("unit_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.Column("name_normalized", sa.String(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(
["unit_id"],
["ingredient_units.id"],
),
sa.PrimaryKeyConstraint("id", "unit_id"),
)
op.create_index(
op.f("ix_ingredient_units_aliases_created_at"), "ingredient_units_aliases", ["created_at"], unique=False
)
op.create_index(
op.f("ix_ingredient_units_aliases_name_normalized"),
"ingredient_units_aliases",
["name_normalized"],
unique=False,
)
op.create_table(
"ingredient_foods_aliases",
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("food_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.Column("name_normalized", sa.String(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(
["food_id"],
["ingredient_foods.id"],
),
sa.PrimaryKeyConstraint("id", "food_id"),
)
op.create_index(
op.f("ix_ingredient_foods_aliases_created_at"), "ingredient_foods_aliases", ["created_at"], unique=False
)
op.create_index(
op.f("ix_ingredient_foods_aliases_name_normalized"),
"ingredient_foods_aliases",
["name_normalized"],
unique=False,
)
op.add_column("ingredient_foods", sa.Column("plural_name", sa.String(), nullable=True))
op.add_column("ingredient_foods", sa.Column("plural_name_normalized", sa.String(), nullable=True))
op.create_index(
op.f("ix_ingredient_foods_plural_name_normalized"), "ingredient_foods", ["plural_name_normalized"], unique=False
)
op.add_column("ingredient_units", sa.Column("plural_name", sa.String(), nullable=True))
op.add_column("ingredient_units", sa.Column("plural_name_normalized", sa.String(), nullable=True))
op.create_index(
op.f("ix_ingredient_units_plural_name_normalized"), "ingredient_units", ["plural_name_normalized"], unique=False
)
op.add_column("ingredient_units", sa.Column("plural_abbreviation", sa.String(), nullable=True))
op.add_column("ingredient_units", sa.Column("plural_abbreviation_normalized", sa.String(), nullable=True))
op.create_index(
op.f("ix_ingredient_units_plural_abbreviation_normalized"),
"ingredient_units",
["plural_abbreviation_normalized"],
unique=False,
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_ingredient_units_plural_abbreviation_normalized"), table_name="ingredient_units")
op.drop_column("ingredient_units", "plural_abbreviation_normalized")
op.drop_column("ingredient_units", "plural_abbreviation")
op.drop_index(op.f("ix_ingredient_units_plural_name_normalized"), table_name="ingredient_units")
op.drop_column("ingredient_units", "plural_name_normalized")
op.drop_column("ingredient_units", "plural_name")
op.drop_index(op.f("ix_ingredient_foods_plural_name_normalized"), table_name="ingredient_foods")
op.drop_column("ingredient_foods", "plural_name_normalized")
op.drop_column("ingredient_foods", "plural_name")
op.drop_index(op.f("ix_ingredient_foods_aliases_name_normalized"), table_name="ingredient_foods_aliases")
op.drop_index(op.f("ix_ingredient_foods_aliases_created_at"), table_name="ingredient_foods_aliases")
op.drop_table("ingredient_foods_aliases")
op.drop_index(op.f("ix_ingredient_units_aliases_name_normalized"), table_name="ingredient_units_aliases")
op.drop_index(op.f("ix_ingredient_units_aliases_created_at"), table_name="ingredient_units_aliases")
op.drop_table("ingredient_units_aliases")
# ### end Alembic commands ###

View File

@@ -1,101 +0,0 @@
"""added user to shopping list
Revision ID: 2298bb460ffd
Revises: ba1e4a6cfe99
Create Date: 2024-02-23 16:15:07.115641
"""
from uuid import UUID
import sqlalchemy as sa
from sqlalchemy import orm
import mealie.db.migration_types
from alembic import op
from mealie.core.root_logger import get_logger
logger = get_logger()
# revision identifiers, used by Alembic.
revision = "2298bb460ffd"
down_revision = "ba1e4a6cfe99"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def is_postgres():
return op.get_context().dialect.name == "postgresql"
def find_user_id_for_group(group_id: UUID):
bind = op.get_bind()
session = orm.Session(bind=bind)
if is_postgres():
stmt = "SELECT id FROM users WHERE group_id=:group_id AND admin = TRUE LIMIT 1"
else:
stmt = "SELECT id FROM users WHERE group_id=:group_id AND admin = 1 LIMIT 1"
with session:
try:
# try to find an admin user
return session.execute(sa.text(stmt).bindparams(group_id=group_id)).scalar_one()
except orm.exc.NoResultFound:
pass
try:
# fallback to any user
return session.execute(
sa.text("SELECT id FROM users WHERE group_id=:group_id LIMIT 1").bindparams(group_id=group_id)
).scalar_one()
except orm.exc.NoResultFound:
pass
# no user could be found
return None
def populate_shopping_list_users():
bind = op.get_bind()
session = orm.Session(bind=bind)
with session:
list_ids_and_group_ids = session.execute(sa.text("SELECT id, group_id FROM shopping_lists")).all()
for list_id, group_id in list_ids_and_group_ids:
user_id = find_user_id_for_group(group_id)
if user_id:
session.execute(
sa.text("UPDATE shopping_lists SET user_id=:user_id WHERE id=:id").bindparams(
user_id=user_id, id=list_id
)
)
else:
logger.warning(
f"No user found for shopping list {list_id} with group {group_id}; deleting shopping list"
)
session.execute(sa.text("DELETE FROM shopping_lists WHERE id=:id").bindparams(id=list_id))
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("shopping_lists") as batch_op:
# allow nulls during migration
batch_op.add_column(sa.Column("user_id", mealie.db.migration_types.GUID(), nullable=True))
batch_op.create_index(op.f("ix_shopping_lists_user_id"), ["user_id"], unique=False)
batch_op.create_foreign_key("fk_user_shopping_lists", "users", ["user_id"], ["id"])
# ### end Alembic commands ###
populate_shopping_list_users()
# forbid nulls after migration
with op.batch_alter_table("shopping_lists") as batch_op:
batch_op.alter_column("user_id", nullable=False)
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, "shopping_lists", type_="foreignkey")
op.drop_index(op.f("ix_shopping_lists_user_id"), table_name="shopping_lists")
op.drop_column("shopping_lists", "user_id")
# ### end Alembic commands ###

View File

@@ -1,28 +0,0 @@
"""add OIDC auth method
Revision ID: 09aba125b57a
Revises: 2298bb460ffd
Create Date: 2024-03-10 05:08:32.397027
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "09aba125b57a"
down_revision = "2298bb460ffd"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def is_postgres():
return op.get_context().dialect.name == "postgresql"
def upgrade():
if is_postgres():
op.execute("ALTER TYPE authmethod ADD VALUE 'OIDC'")
def downgrade():
pass

View File

@@ -1,227 +0,0 @@
"""migrate favorites and ratings to user_ratings
Revision ID: d7c6efd2de42
Revises: 09aba125b57a
Create Date: 2024-03-18 02:28:15.896959
"""
from datetime import datetime, timezone
from textwrap import dedent
from typing import Any
from uuid import uuid4
import sqlalchemy as sa
from sqlalchemy import orm
import mealie.db.migration_types
from alembic import op
# revision identifiers, used by Alembic.
revision = "d7c6efd2de42"
down_revision = "09aba125b57a"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def is_postgres():
return op.get_context().dialect.name == "postgresql"
def new_user_rating(user_id: Any, recipe_id: Any, rating: float | None = None, is_favorite: bool = False):
if is_postgres():
id = str(uuid4())
else:
id = "%.32x" % uuid4().int # noqa: UP031
now = datetime.now(timezone.utc).isoformat()
return {
"id": id,
"user_id": user_id,
"recipe_id": recipe_id,
"rating": rating,
"is_favorite": is_favorite,
"created_at": now,
"update_at": now,
}
def migrate_user_favorites_to_user_ratings():
bind = op.get_bind()
session = orm.Session(bind=bind)
with session:
user_ids_and_recipe_ids = session.execute(sa.text("SELECT user_id, recipe_id FROM users_to_favorites")).all()
rows = [
new_user_rating(user_id, recipe_id, is_favorite=True)
for user_id, recipe_id in user_ids_and_recipe_ids
if user_id and recipe_id
]
if is_postgres():
query = dedent(
"""
INSERT INTO users_to_recipes (id, user_id, recipe_id, rating, is_favorite, created_at, update_at)
VALUES (:id, :user_id, :recipe_id, :rating, :is_favorite, :created_at, :update_at)
ON CONFLICT DO NOTHING
"""
)
else:
query = dedent(
"""
INSERT OR IGNORE INTO users_to_recipes
(id, user_id, recipe_id, rating, is_favorite, created_at, update_at)
VALUES (:id, :user_id, :recipe_id, :rating, :is_favorite, :created_at, :update_at)
"""
)
for row in rows:
session.execute(sa.text(query), row)
def migrate_group_to_user_ratings(group_id: Any):
bind = op.get_bind()
session = orm.Session(bind=bind)
with session:
user_ids = (
session.execute(sa.text("SELECT id FROM users WHERE group_id=:group_id").bindparams(group_id=group_id))
.scalars()
.all()
)
recipe_ids_ratings = session.execute(
sa.text(
"SELECT id, rating FROM recipes WHERE group_id=:group_id AND rating > 0 AND rating IS NOT NULL"
).bindparams(group_id=group_id)
).all()
# Convert recipe ratings to user ratings. Since we don't know who
# rated the recipe initially, we copy the rating to all users.
rows: list[dict] = []
for recipe_id, rating in recipe_ids_ratings:
for user_id in user_ids:
rows.append(new_user_rating(user_id, recipe_id, rating, is_favorite=False))
if is_postgres():
insert_query = dedent(
"""
INSERT INTO users_to_recipes (id, user_id, recipe_id, rating, is_favorite, created_at, update_at)
VALUES (:id, :user_id, :recipe_id, :rating, :is_favorite, :created_at, :update_at)
ON CONFLICT (user_id, recipe_id) DO NOTHING;
"""
)
else:
insert_query = dedent(
"""
INSERT OR IGNORE INTO users_to_recipes
(id, user_id, recipe_id, rating, is_favorite, created_at, update_at)
VALUES (:id, :user_id, :recipe_id, :rating, :is_favorite, :created_at, :update_at);
"""
)
update_query = dedent(
"""
UPDATE users_to_recipes
SET rating = :rating, update_at = :update_at
WHERE user_id = :user_id AND recipe_id = :recipe_id;
"""
)
# Create new user ratings with is_favorite set to False
for row in rows:
session.execute(sa.text(insert_query), row)
# Update existing user ratings with the correct rating
for row in rows:
session.execute(sa.text(update_query), row)
def migrate_to_user_ratings():
migrate_user_favorites_to_user_ratings()
bind = op.get_bind()
session = orm.Session(bind=bind)
with session:
group_ids = session.execute(sa.text("SELECT id FROM groups")).scalars().all()
for group_id in group_ids:
migrate_group_to_user_ratings(group_id)
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"users_to_recipes",
sa.Column("user_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("recipe_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("rating", sa.Float(), nullable=True),
sa.Column("is_favorite", sa.Boolean(), nullable=False),
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
sa.PrimaryKeyConstraint("user_id", "recipe_id", "id"),
sa.UniqueConstraint("user_id", "recipe_id", name="user_id_recipe_id_rating_key"),
)
op.create_index(op.f("ix_users_to_recipes_created_at"), "users_to_recipes", ["created_at"], unique=False)
op.create_index(op.f("ix_users_to_recipes_is_favorite"), "users_to_recipes", ["is_favorite"], unique=False)
op.create_index(op.f("ix_users_to_recipes_rating"), "users_to_recipes", ["rating"], unique=False)
op.create_index(op.f("ix_users_to_recipes_recipe_id"), "users_to_recipes", ["recipe_id"], unique=False)
op.create_index(op.f("ix_users_to_recipes_user_id"), "users_to_recipes", ["user_id"], unique=False)
migrate_to_user_ratings()
if is_postgres():
op.drop_index("ix_users_to_favorites_recipe_id", table_name="users_to_favorites")
op.drop_index("ix_users_to_favorites_user_id", table_name="users_to_favorites")
op.alter_column("recipes", "rating", existing_type=sa.INTEGER(), type_=sa.Float(), existing_nullable=True)
else:
op.execute("DROP INDEX IF EXISTS ix_users_to_favorites_recipe_id")
op.execute("DROP INDEX IF EXISTS ix_users_to_favorites_user_id")
with op.batch_alter_table("recipes") as batch_op:
batch_op.alter_column("rating", existing_type=sa.INTEGER(), type_=sa.Float(), existing_nullable=True)
op.drop_table("users_to_favorites")
op.create_index(op.f("ix_recipes_rating"), "recipes", ["rating"], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column(
"recipes_ingredients", "quantity", existing_type=sa.Float(), type_=sa.INTEGER(), existing_nullable=True
)
op.drop_index(op.f("ix_recipes_rating"), table_name="recipes")
op.alter_column("recipes", "rating", existing_type=sa.Float(), type_=sa.INTEGER(), existing_nullable=True)
op.create_table(
"users_to_favorites",
sa.Column("user_id", sa.CHAR(length=32), nullable=True),
sa.Column("recipe_id", sa.CHAR(length=32), nullable=True),
sa.ForeignKeyConstraint(
["recipe_id"],
["recipes.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
sa.UniqueConstraint("user_id", "recipe_id", name="user_id_recipe_id_key"),
)
op.create_index("ix_users_to_favorites_user_id", "users_to_favorites", ["user_id"], unique=False)
op.create_index("ix_users_to_favorites_recipe_id", "users_to_favorites", ["recipe_id"], unique=False)
op.drop_index(op.f("ix_users_to_recipes_user_id"), table_name="users_to_recipes")
op.drop_index(op.f("ix_users_to_recipes_recipe_id"), table_name="users_to_recipes")
op.drop_index(op.f("ix_users_to_recipes_rating"), table_name="users_to_recipes")
op.drop_index(op.f("ix_users_to_recipes_is_favorite"), table_name="users_to_recipes")
op.drop_index(op.f("ix_users_to_recipes_created_at"), table_name="users_to_recipes")
op.drop_table("users_to_recipes")
# ### end Alembic commands ###

View File

@@ -1,52 +0,0 @@
"""add group recipe actions
Revision ID: 7788478a0338
Revises: d7c6efd2de42
Create Date: 2024-04-07 01:05:20.816270
"""
import sqlalchemy as sa
import mealie.db.migration_types
from alembic import op
# revision identifiers, used by Alembic.
revision = "7788478a0338"
down_revision = "d7c6efd2de42"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"recipe_actions",
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("action_type", sa.String(), nullable=False),
sa.Column("title", sa.String(), nullable=False),
sa.Column("url", sa.String(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_recipe_actions_action_type"), "recipe_actions", ["action_type"], unique=False)
op.create_index(op.f("ix_recipe_actions_created_at"), "recipe_actions", ["created_at"], unique=False)
op.create_index(op.f("ix_recipe_actions_group_id"), "recipe_actions", ["group_id"], unique=False)
op.create_index(op.f("ix_recipe_actions_title"), "recipe_actions", ["title"], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_recipe_actions_title"), table_name="recipe_actions")
op.drop_index(op.f("ix_recipe_actions_group_id"), table_name="recipe_actions")
op.drop_index(op.f("ix_recipe_actions_created_at"), table_name="recipe_actions")
op.drop_index(op.f("ix_recipe_actions_action_type"), table_name="recipe_actions")
op.drop_table("recipe_actions")
# ### end Alembic commands ###

View File

@@ -1,47 +0,0 @@
"""Add staple flag to foods
Revision ID: 32d69327997b
Revises: 7788478a0338
Create Date: 2024-06-22 10:17:03.323966
"""
import sqlalchemy as sa
from sqlalchemy import orm
from alembic import op
# revision identifiers, used by Alembic.
revision = "32d69327997b"
down_revision = "7788478a0338"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def is_postgres():
return op.get_context().dialect.name == "postgresql"
def upgrade():
with op.batch_alter_table("ingredient_foods") as batch_op:
batch_op.add_column(sa.Column("on_hand", sa.Boolean(), nullable=True, default=False))
bind = op.get_bind()
session = orm.Session(bind=bind)
with session:
if is_postgres():
stmt = "UPDATE ingredient_foods SET on_hand = FALSE;"
else:
stmt = "UPDATE ingredient_foods SET on_hand = 0;"
session.execute(sa.text(stmt))
# forbid nulls after migration
with op.batch_alter_table("ingredient_foods") as batch_op:
batch_op.alter_column("on_hand", nullable=False)
def downgrade():
with op.batch_alter_table("ingredient_foods") as batch_op:
batch_op.drop_column("on_hand")

View File

@@ -1,321 +0,0 @@
"""add households
Revision ID: feecc8ffb956
Revises: 32d69327997b
Create Date: 2024-07-12 16:16:29.973929
"""
from datetime import datetime, timezone
from textwrap import dedent
from typing import Any
from uuid import uuid4
import sqlalchemy as sa
from slugify import slugify
from sqlalchemy import orm
import mealie.db.migration_types
from alembic import op
from mealie.core.config import get_app_settings
# revision identifiers, used by Alembic.
revision = "feecc8ffb956"
down_revision = "32d69327997b"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
settings = get_app_settings()
def is_postgres():
return op.get_context().dialect.name == "postgresql"
def generate_id() -> str:
"""See GUID.convert_value_to_guid"""
val = uuid4()
if is_postgres():
return str(val)
else:
return f"{val.int:032x}"
def dedupe_cookbook_slugs():
bind = op.get_bind()
session = orm.Session(bind=bind)
with session:
sql = sa.text(
dedent(
"""
SELECT slug, group_id, COUNT(*)
FROM cookbooks
GROUP BY slug, group_id
HAVING COUNT(*) > 1
"""
)
)
rows = session.execute(sql).fetchall()
for slug, group_id, _ in rows:
sql = sa.text(
dedent(
"""
SELECT id
FROM cookbooks
WHERE slug = :slug AND group_id = :group_id
ORDER BY id
"""
)
)
cookbook_ids = session.execute(sql, {"slug": slug, "group_id": group_id}).fetchall()
for i, (cookbook_id,) in enumerate(cookbook_ids):
if i == 0:
continue
sql = sa.text(
dedent(
"""
UPDATE cookbooks
SET slug = :slug || '-' || :i
WHERE id = :id
"""
)
)
session.execute(sql, {"slug": slug, "i": i, "id": cookbook_id})
def create_household(session: orm.Session, group_id: str) -> str:
# create/insert household
household_id = generate_id()
timestamp = datetime.now(timezone.utc).isoformat()
household_data = {
"id": household_id,
"name": settings.DEFAULT_HOUSEHOLD,
"slug": slugify(settings.DEFAULT_HOUSEHOLD),
"group_id": group_id,
"created_at": timestamp,
"update_at": timestamp,
}
columns = ", ".join(household_data.keys())
placeholders = ", ".join(f":{key}" for key in household_data.keys())
sql_statement = f"INSERT INTO households ({columns}) VALUES ({placeholders})"
session.execute(sa.text(sql_statement), household_data)
# fetch group preferences so we can copy them over to household preferences
migrated_field_defaults = {
"private_group": True, # this is renamed later
"first_day_of_week": 0,
"recipe_public": True,
"recipe_show_nutrition": False,
"recipe_show_assets": False,
"recipe_landscape_view": False,
"recipe_disable_comments": False,
"recipe_disable_amount": True,
}
sql_statement = (
f"SELECT {', '.join(migrated_field_defaults.keys())} FROM group_preferences WHERE group_id = :group_id"
)
group_preferences = session.execute(sa.text(sql_statement), {"group_id": group_id}).fetchone()
# build preferences data
if group_preferences:
preferences_data: dict[str, Any] = {}
for i, (field, default_value) in enumerate(migrated_field_defaults.items()):
value = group_preferences[i]
preferences_data[field] = value if value is not None else default_value
else:
preferences_data = migrated_field_defaults
preferences_data["id"] = generate_id()
preferences_data["household_id"] = household_id
preferences_data["created_at"] = timestamp
preferences_data["update_at"] = timestamp
preferences_data["private_household"] = preferences_data.pop("private_group")
# insert preferences data
columns = ", ".join(preferences_data.keys())
placeholders = ", ".join(f":{key}" for key in preferences_data.keys())
sql_statement = f"INSERT INTO household_preferences ({columns}) VALUES ({placeholders})"
session.execute(sa.text(sql_statement), preferences_data)
return household_id
def create_households_for_groups() -> dict[str, str]:
bind = op.get_bind()
session = orm.Session(bind=bind)
group_id_household_id_map: dict[str, str] = {}
with session:
rows = session.execute(sa.text("SELECT id FROM groups")).fetchall()
for row in rows:
group_id = row[0]
group_id_household_id_map[group_id] = create_household(session, group_id)
return group_id_household_id_map
def _do_assignment(session: orm.Session, table: str, group_id: str, household_id: str):
sql = sa.text(
dedent(
f"""
UPDATE {table}
SET household_id = :household_id
WHERE group_id = :group_id
""",
)
)
session.execute(sql, {"group_id": group_id, "household_id": household_id})
def assign_households(group_id_household_id_map: dict[str, str]):
tables = [
"cookbooks",
"group_events_notifiers",
"group_meal_plan_rules",
"invite_tokens",
"recipe_actions",
"users",
"webhook_urls",
]
bind = op.get_bind()
session = orm.Session(bind=bind)
with session:
for table in tables:
for group_id, household_id in group_id_household_id_map.items():
_do_assignment(session, table, group_id, household_id)
def populate_household_data():
group_id_household_id_map = create_households_for_groups()
assign_households(group_id_household_id_map)
def upgrade():
dedupe_cookbook_slugs()
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"households",
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("name", sa.String(), nullable=False),
sa.Column("slug", sa.String(), nullable=True),
sa.Column("group_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(
["group_id"],
["groups.id"],
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("group_id", "name", name="household_name_group_id_key"),
sa.UniqueConstraint("group_id", "slug", name="household_slug_group_id_key"),
)
op.create_index(op.f("ix_households_created_at"), "households", ["created_at"], unique=False)
op.create_index(op.f("ix_households_group_id"), "households", ["group_id"], unique=False)
op.create_index(op.f("ix_households_name"), "households", ["name"], unique=False)
op.create_index(op.f("ix_households_slug"), "households", ["slug"], unique=False)
op.create_table(
"household_preferences",
sa.Column("id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("household_id", mealie.db.migration_types.GUID(), nullable=False),
sa.Column("private_household", sa.Boolean(), nullable=True),
sa.Column("first_day_of_week", sa.Integer(), nullable=True),
sa.Column("recipe_public", sa.Boolean(), nullable=True),
sa.Column("recipe_show_nutrition", sa.Boolean(), nullable=True),
sa.Column("recipe_show_assets", sa.Boolean(), nullable=True),
sa.Column("recipe_landscape_view", sa.Boolean(), nullable=True),
sa.Column("recipe_disable_comments", sa.Boolean(), nullable=True),
sa.Column("recipe_disable_amount", sa.Boolean(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("update_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(
["household_id"],
["households.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_household_preferences_created_at"), "household_preferences", ["created_at"], unique=False)
op.create_index(
op.f("ix_household_preferences_household_id"), "household_preferences", ["household_id"], unique=False
)
with op.batch_alter_table("cookbooks") as batch_op:
batch_op.add_column(sa.Column("household_id", mealie.db.migration_types.GUID(), nullable=True))
batch_op.create_index(op.f("ix_cookbooks_household_id"), ["household_id"], unique=False)
batch_op.create_foreign_key("fk_cookbooks_household_id", "households", ["household_id"], ["id"])
# not directly related to households, but important for frontend routes
batch_op.create_unique_constraint("cookbook_slug_group_id_key", ["slug", "group_id"])
with op.batch_alter_table("group_events_notifiers") as batch_op:
batch_op.add_column(sa.Column("household_id", mealie.db.migration_types.GUID(), nullable=True))
batch_op.create_index(op.f("ix_group_events_notifiers_household_id"), ["household_id"], unique=False)
batch_op.create_foreign_key("fk_group_events_notifiers_household_id", "households", ["household_id"], ["id"])
with op.batch_alter_table("group_meal_plan_rules") as batch_op:
batch_op.add_column(sa.Column("household_id", mealie.db.migration_types.GUID(), nullable=True))
batch_op.create_index(op.f("ix_group_meal_plan_rules_household_id"), ["household_id"], unique=False)
batch_op.create_foreign_key("fk_group_meal_plan_rules_household_id", "households", ["household_id"], ["id"])
with op.batch_alter_table("invite_tokens") as batch_op:
batch_op.add_column(sa.Column("household_id", mealie.db.migration_types.GUID(), nullable=True))
batch_op.create_index(op.f("ix_invite_tokens_household_id"), ["household_id"], unique=False)
batch_op.create_foreign_key("fk_invite_tokens_household_id", "households", ["household_id"], ["id"])
with op.batch_alter_table("recipe_actions") as batch_op:
batch_op.add_column(sa.Column("household_id", mealie.db.migration_types.GUID(), nullable=True))
batch_op.create_index(op.f("ix_recipe_actions_household_id"), ["household_id"], unique=False)
batch_op.create_foreign_key("fk_recipe_actions_household_id", "households", ["household_id"], ["id"])
with op.batch_alter_table("users") as batch_op:
batch_op.add_column(sa.Column("household_id", mealie.db.migration_types.GUID(), nullable=True))
batch_op.create_index(op.f("ix_users_household_id"), ["household_id"], unique=False)
batch_op.create_foreign_key("fk_users_household_id", "households", ["household_id"], ["id"])
with op.batch_alter_table("webhook_urls") as batch_op:
batch_op.add_column(sa.Column("household_id", mealie.db.migration_types.GUID(), nullable=True))
batch_op.create_index(op.f("ix_webhook_urls_household_id"), ["household_id"], unique=False)
batch_op.create_foreign_key("fk_webhook_urls_household_id", "households", ["household_id"], ["id"])
# ### end Alembic commands ###
populate_household_data()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, "webhook_urls", type_="foreignkey")
op.drop_index(op.f("ix_webhook_urls_household_id"), table_name="webhook_urls")
op.drop_column("webhook_urls", "household_id")
op.drop_constraint(None, "users", type_="foreignkey")
op.drop_index(op.f("ix_users_household_id"), table_name="users")
op.drop_column("users", "household_id")
op.drop_constraint(None, "recipe_actions", type_="foreignkey")
op.drop_index(op.f("ix_recipe_actions_household_id"), table_name="recipe_actions")
op.drop_column("recipe_actions", "household_id")
op.drop_constraint(None, "invite_tokens", type_="foreignkey")
op.drop_index(op.f("ix_invite_tokens_household_id"), table_name="invite_tokens")
op.drop_column("invite_tokens", "household_id")
op.drop_constraint(None, "group_meal_plan_rules", type_="foreignkey")
op.drop_index(op.f("ix_group_meal_plan_rules_household_id"), table_name="group_meal_plan_rules")
op.drop_column("group_meal_plan_rules", "household_id")
op.drop_constraint(None, "group_events_notifiers", type_="foreignkey")
op.drop_index(op.f("ix_group_events_notifiers_household_id"), table_name="group_events_notifiers")
op.drop_column("group_events_notifiers", "household_id")
op.drop_constraint(None, "cookbooks", type_="foreignkey")
op.drop_index(op.f("ix_cookbooks_household_id"), table_name="cookbooks")
op.drop_column("cookbooks", "household_id")
op.drop_constraint("cookbook_slug_group_id_key", "cookbooks", type_="unique")
op.drop_index(op.f("ix_household_preferences_household_id"), table_name="household_preferences")
op.drop_index(op.f("ix_household_preferences_created_at"), table_name="household_preferences")
op.drop_table("household_preferences")
op.drop_index(op.f("ix_households_slug"), table_name="households")
op.drop_index(op.f("ix_households_name"), table_name="households")
op.drop_index(op.f("ix_households_group_id"), table_name="households")
op.drop_index(op.f("ix_households_created_at"), table_name="households")
op.drop_table("households")
# ### end Alembic commands ###

View File

@@ -1,75 +0,0 @@
"""added household recipe lock setting and household management user permission
Revision ID: be568e39ffdf
Revises: feecc8ffb956
Create Date: 2024-09-02 21:39:49.210355
"""
from textwrap import dedent
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "be568e39ffdf"
down_revision = "feecc8ffb956"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def populate_defaults():
if op.get_context().dialect.name == "postgresql":
TRUE = "TRUE"
FALSE = "FALSE"
else:
TRUE = "1"
FALSE = "0"
op.execute(
dedent(
f"""
UPDATE household_preferences
SET lock_recipe_edits_from_other_households = {TRUE}
WHERE lock_recipe_edits_from_other_households IS NULL
"""
)
)
op.execute(
dedent(
f"""
UPDATE users
SET can_manage_household = {FALSE}
WHERE can_manage_household IS NULL AND admin = {FALSE}
"""
)
)
op.execute(
dedent(
f"""
UPDATE users
SET can_manage_household = {TRUE}
WHERE can_manage_household IS NULL AND admin = {TRUE}
"""
)
)
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"household_preferences",
sa.Column("lock_recipe_edits_from_other_households", sa.Boolean(), nullable=True),
)
op.add_column("users", sa.Column("can_manage_household", sa.Boolean(), nullable=True))
# ### end Alembic commands ###
populate_defaults()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("users", "can_manage_household")
op.drop_column("household_preferences", "lock_recipe_edits_from_other_households")
# ### end Alembic commands ###

View File

@@ -1,53 +0,0 @@
"""add households filter to meal plans
Revision ID: 1fe4bd37ccc8
Revises: be568e39ffdf
Create Date: 2024-09-18 14:52:55.831540
"""
import sqlalchemy as sa
import mealie.db.migration_types
from alembic import op
# revision identifiers, used by Alembic.
revision = "1fe4bd37ccc8"
down_revision: str | None = "be568e39ffdf"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"plan_rules_to_households",
sa.Column("group_plan_rule_id", mealie.db.migration_types.GUID(), nullable=True),
sa.Column("household_id", mealie.db.migration_types.GUID(), nullable=True),
sa.ForeignKeyConstraint(
["group_plan_rule_id"],
["group_meal_plan_rules.id"],
),
sa.ForeignKeyConstraint(
["household_id"],
["households.id"],
),
sa.UniqueConstraint("group_plan_rule_id", "household_id", name="group_plan_rule_id_household_id_key"),
)
with op.batch_alter_table("plan_rules_to_households", schema=None) as batch_op:
batch_op.create_index(
batch_op.f("ix_plan_rules_to_households_group_plan_rule_id"), ["group_plan_rule_id"], unique=False
)
batch_op.create_index(batch_op.f("ix_plan_rules_to_households_household_id"), ["household_id"], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("plan_rules_to_households", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_plan_rules_to_households_household_id"))
batch_op.drop_index(batch_op.f("ix_plan_rules_to_households_group_plan_rule_id"))
op.drop_table("plan_rules_to_households")
# ### end Alembic commands ###

View File

@@ -1,39 +0,0 @@
"""'add the rest of the schema.org nutrition properties'
Revision ID: 602927e1013e
Revises: 1fe4bd37ccc8
Create Date: 2024-10-01 14:17:00.611398
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "602927e1013e"
down_revision: str | None = "1fe4bd37ccc8"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("recipe_nutrition", schema=None) as batch_op:
batch_op.add_column(sa.Column("cholesterol_content", sa.String(), nullable=True))
batch_op.add_column(sa.Column("saturated_fat_content", sa.String(), nullable=True))
batch_op.add_column(sa.Column("trans_fat_content", sa.String(), nullable=True))
batch_op.add_column(sa.Column("unsaturated_fat_content", sa.String(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("recipe_nutrition", schema=None) as batch_op:
batch_op.drop_column("unsaturated_fat_content")
batch_op.drop_column("trans_fat_content")
batch_op.drop_column("saturated_fat_content")
batch_op.drop_column("cholesterol_content")
# ### end Alembic commands ###

View File

@@ -1,188 +0,0 @@
"""added query_filter_string to cookbook and mealplan
Revision ID: 86054b40fd06
Revises: 602927e1013e
Create Date: 2024-10-08 21:17:31.601903
"""
import sqlalchemy as sa
from sqlalchemy import orm
from alembic import op
from mealie.db.models._model_utils import guid
# revision identifiers, used by Alembic.
revision = "86054b40fd06"
down_revision: str | None = "602927e1013e"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
# Intermediate table definitions
class SqlAlchemyBase(orm.DeclarativeBase):
pass
class Category(SqlAlchemyBase):
__tablename__ = "categories"
id: orm.Mapped[guid.GUID] = orm.mapped_column(guid.GUID, primary_key=True, default=guid.GUID.generate)
class Tag(SqlAlchemyBase):
__tablename__ = "tags"
id: orm.Mapped[guid.GUID] = orm.mapped_column(guid.GUID, primary_key=True, default=guid.GUID.generate)
class Tool(SqlAlchemyBase):
__tablename__ = "tools"
id: orm.Mapped[guid.GUID] = orm.mapped_column(guid.GUID, primary_key=True, default=guid.GUID.generate)
class Household(SqlAlchemyBase):
__tablename__ = "households"
id: orm.Mapped[guid.GUID] = orm.mapped_column(guid.GUID, primary_key=True, default=guid.GUID.generate)
cookbooks_to_categories = sa.Table(
"cookbooks_to_categories",
SqlAlchemyBase.metadata,
sa.Column("cookbook_id", guid.GUID, sa.ForeignKey("cookbooks.id"), index=True),
sa.Column("category_id", guid.GUID, sa.ForeignKey("categories.id"), index=True),
)
cookbooks_to_tags = sa.Table(
"cookbooks_to_tags",
SqlAlchemyBase.metadata,
sa.Column("cookbook_id", guid.GUID, sa.ForeignKey("cookbooks.id"), index=True),
sa.Column("tag_id", guid.GUID, sa.ForeignKey("tags.id"), index=True),
)
cookbooks_to_tools = sa.Table(
"cookbooks_to_tools",
SqlAlchemyBase.metadata,
sa.Column("cookbook_id", guid.GUID, sa.ForeignKey("cookbooks.id"), index=True),
sa.Column("tool_id", guid.GUID, sa.ForeignKey("tools.id"), index=True),
)
plan_rules_to_categories = sa.Table(
"plan_rules_to_categories",
SqlAlchemyBase.metadata,
sa.Column("group_plan_rule_id", guid.GUID, sa.ForeignKey("group_meal_plan_rules.id"), index=True),
sa.Column("category_id", guid.GUID, sa.ForeignKey("categories.id"), index=True),
)
plan_rules_to_tags = sa.Table(
"plan_rules_to_tags",
SqlAlchemyBase.metadata,
sa.Column("plan_rule_id", guid.GUID, sa.ForeignKey("group_meal_plan_rules.id"), index=True),
sa.Column("tag_id", guid.GUID, sa.ForeignKey("tags.id"), index=True),
)
plan_rules_to_households = sa.Table(
"plan_rules_to_households",
SqlAlchemyBase.metadata,
sa.Column("group_plan_rule_id", guid.GUID, sa.ForeignKey("group_meal_plan_rules.id"), index=True),
sa.Column("household_id", guid.GUID, sa.ForeignKey("households.id"), index=True),
)
class CookBook(SqlAlchemyBase):
__tablename__ = "cookbooks"
id: orm.Mapped[guid.GUID] = orm.mapped_column(guid.GUID, primary_key=True, default=guid.GUID.generate)
query_filter_string: orm.Mapped[str] = orm.mapped_column(sa.String, nullable=False, default="")
categories: orm.Mapped[list[Category]] = orm.relationship(
Category, secondary=cookbooks_to_categories, single_parent=True
)
require_all_categories: orm.Mapped[bool | None] = orm.mapped_column(sa.Boolean, default=True)
tags: orm.Mapped[list[Tag]] = orm.relationship(Tag, secondary=cookbooks_to_tags, single_parent=True)
require_all_tags: orm.Mapped[bool | None] = orm.mapped_column(sa.Boolean, default=True)
tools: orm.Mapped[list[Tool]] = orm.relationship(Tool, secondary=cookbooks_to_tools, single_parent=True)
require_all_tools: orm.Mapped[bool | None] = orm.mapped_column(sa.Boolean, default=True)
class GroupMealPlanRules(SqlAlchemyBase):
__tablename__ = "group_meal_plan_rules"
id: orm.Mapped[guid.GUID] = orm.mapped_column(guid.GUID, primary_key=True, default=guid.GUID.generate)
query_filter_string: orm.Mapped[str] = orm.mapped_column(sa.String, nullable=False, default="")
categories: orm.Mapped[list[Category]] = orm.relationship(Category, secondary=plan_rules_to_categories)
tags: orm.Mapped[list[Tag]] = orm.relationship(Tag, secondary=plan_rules_to_tags)
households: orm.Mapped[list["Household"]] = orm.relationship("Household", secondary=plan_rules_to_households)
def migrate_cookbooks():
bind = op.get_bind()
session = orm.Session(bind=bind)
cookbooks = session.query(CookBook).all()
for cookbook in cookbooks:
parts = []
if cookbook.categories:
relop = "CONTAINS ALL" if cookbook.require_all_categories else "IN"
vals = ",".join([f'"{cat.id}"' for cat in cookbook.categories])
parts.append(f"recipe_category.id {relop} [{vals}]")
if cookbook.tags:
relop = "CONTAINS ALL" if cookbook.require_all_tags else "IN"
vals = ",".join([f'"{tag.id}"' for tag in cookbook.tags])
parts.append(f"tags.id {relop} [{vals}]")
if cookbook.tools:
relop = "CONTAINS ALL" if cookbook.require_all_tools else "IN"
vals = ",".join([f'"{tool.id}"' for tool in cookbook.tools])
parts.append(f"tools.id {relop} [{vals}]")
cookbook.query_filter_string = " AND ".join(parts)
session.commit()
def migrate_mealplan_rules():
bind = op.get_bind()
session = orm.Session(bind=bind)
rules = session.query(GroupMealPlanRules).all()
for rule in rules:
parts = []
if rule.categories:
vals = ",".join([f'"{cat.id}"' for cat in rule.categories])
parts.append(f"recipe_category.id CONTAINS ALL [{vals}]")
if rule.tags:
vals = ",".join([f'"{tag.id}"' for tag in rule.tags])
parts.append(f"tags.id CONTAINS ALL [{vals}]")
if rule.households:
vals = ",".join([f'"{household.id}"' for household in rule.households])
parts.append(f"household_id IN [{vals}]")
rule.query_filter_string = " AND ".join(parts)
session.commit()
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("cookbooks", schema=None) as batch_op:
batch_op.add_column(sa.Column("query_filter_string", sa.String(), nullable=False, server_default=""))
with op.batch_alter_table("group_meal_plan_rules", schema=None) as batch_op:
batch_op.add_column(sa.Column("query_filter_string", sa.String(), nullable=False, server_default=""))
# ### end Alembic commands ###
migrate_cookbooks()
migrate_mealplan_rules()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("group_meal_plan_rules", schema=None) as batch_op:
batch_op.drop_column("query_filter_string")
with op.batch_alter_table("cookbooks", schema=None) as batch_op:
batch_op.drop_column("query_filter_string")
# ### end Alembic commands ###

View File

@@ -1,34 +0,0 @@
"""'Add summary to recipe instructions'
Revision ID: 3897397b4631
Revises: 86054b40fd06
Create Date: 2024-10-20 09:47:46.844436
"""
import sqlalchemy as sa
import mealie.db.migration_types
from alembic import op
# revision identifiers, used by Alembic.
revision = "3897397b4631"
down_revision: str | None = "86054b40fd06"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("recipe_instructions", schema=None) as batch_op:
batch_op.add_column(sa.Column("summary", sa.String(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("recipe_instructions", schema=None) as batch_op:
batch_op.drop_column("summary")
# ### end Alembic commands ###

View File

@@ -1,64 +0,0 @@
# configuration file for git-cliff (0.1.0)
[changelog]
# changelog header
header = """
# Changelog\n
All notable changes to this project will be documented in this file.\n
"""
# template for the changelog body
# https://tera.netlify.app/docs/#introduction
body = """
{% if version %}\
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
{% else %}\
## [unreleased]
{% endif %}\
{% for group, commits in commits | group_by(attribute="group") %}
### {{ group | upper_first }}
{% for commit in commits %}
- {% if commit.breaking %}[**breaking**] {% endif %}{{ commit.message | upper_first }}\
{% endfor %}
{% endfor %}\n
"""
# remove the leading and trailing whitespace from the template
trim = true
# changelog footer
footer = """
<!-- generated by git-cliff -->
"""
[git]
# parse the commits based on https://www.conventionalcommits.org
conventional_commits = true
# filter out the commits that are not conventional
filter_unconventional = true
# regex for preprocessing the commit messages
commit_preprocessors = [
{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/hay-kot/mealie/issues/${2}))"},
]
# regex for parsing and grouping commits
commit_parsers = [
{ message = "^feat", group = "Features"},
{ message = "^fix", group = "Bug Fixes"},
{ message = "^doc", group = "Documentation"},
{ message = "^perf", group = "Performance"},
{ message = "^refactor", group = "Refactor"},
{ message = "^style", group = "Styling"},
{ message = "^test", group = "Testing"},
{ message = "^chore\\(release\\): prepare for", skip = true},
{ message = "^chore", group = "Miscellaneous Tasks"},
{ body = ".*security", group = "Security"},
]
# filter out the commits that are not matched by commit parsers
filter_commits = false
# glob pattern for matching git tags
tag_pattern = "v[0-9]*"
# regex for skipping tags
skip_tags = "v0.1.0-beta.1"
# regex for ignoring tags
ignore_tags = ""
# sort the tags chronologically
date_order = false
# sort the commits inside sections by oldest/newest order
sort_commits = "oldest"

View File

@@ -1,16 +1,6 @@
preserve_hierarchy: false
pull_request_title: "chore(l10n): New Crowdin updates"
pull_request_labels: [
"l10n"
]
files:
- source: /frontend/lang/messages/en-US.json
translation: /frontend/lang/messages/%locale%.json
- source: /mealie/lang/messages/en-US.json
translation: /mealie/lang/messages/%locale%.json
- source: /mealie/repos/seed/resources/foods/locales/en-US.json
translation: /mealie/repos/seed/resources/foods/locales/%locale%.json
- source: /mealie/repos/seed/resources/units/locales/en-US.json
translation: /mealie/repos/seed/resources/units/locales/%locale%.json
- source: /mealie/repos/seed/resources/labels/locales/en-US.json
translation: /mealie/repos/seed/resources/labels/locales/%locale%.json
- source: /frontend/src/locales/messages/en-US.json
translation: /frontend/src/locales/messages/%locale%.json
- source: /frontend/src/locales/dateTimeFormats/en-US.json
translation: /frontend/src/locales/dateTimeFormats/%locale%.json

View File

@@ -1,116 +0,0 @@
from dataclasses import dataclass
from pathlib import Path
from slugify import slugify
from utils import render_python_template
CWD = Path(__file__).parent
TEMPLATE = CWD / "templates" / "test_data.py.j2"
TEST_DATA = CWD.parent.parent / "tests" / "data"
GENERATED = CWD / "generated"
@dataclass
class TestDataPath:
var: str
path: str
@classmethod
def from_path(cls, path: Path):
var = str(path)
var = var.replace(str(TEST_DATA), "")
rel_path = var.removeprefix("/")
# Remove any file extension
var = var.split(".")[0]
var = var.replace("'", "")
var = slugify(var, separator="_")
return cls(var, rel_path)
@dataclass
class DataDir:
name: str
path: Path
children: list[TestDataPath]
def get_data_paths(path: Path) -> list[DataDir]:
"""
Recursively walks the given path and returns a list of TestDataPaths
"""
def recursive_test_paths(p: Path) -> list[TestDataPath]:
test_paths = []
for child in p.iterdir():
if child.is_dir():
test_paths += recursive_test_paths(child)
else:
test_paths.append(TestDataPath.from_path(child))
return [x for x in test_paths if not None]
data_paths = []
for p in path.iterdir():
if p.is_dir():
data_paths.append(DataDir(p.name, p, recursive_test_paths(p)))
return data_paths
def rename_non_compliant_paths():
"""
Recursively itterates through a directory and renames all files/folders to be
kabab case.
"""
ignore_files = ["DS_Store", ".gitkeep", "af-ZA.json", "en-US.json"]
ignore_extensions = [".pyc", ".pyo", ".py"]
def recursive_rename(p: Path):
for child in p.iterdir():
if str(child).startswith("."):
continue
if child.suffix in ignore_extensions:
continue
if child.name in ignore_files:
continue
if child.is_dir():
recursive_rename(child)
else:
new_name = slugify(child.stem)
extension = child.suffix
if new_name != child.name:
child.rename(child.parent / f"{new_name}{extension}")
recursive_rename(TEST_DATA)
def main():
rename_non_compliant_paths()
GENERATED.mkdir(exist_ok=True)
data_dirs = get_data_paths(TEST_DATA)
all_children = [x.children for x in data_dirs]
# Flatten list of lists
all_children = [item for sublist in all_children for item in sublist]
render_python_template(
TEMPLATE,
GENERATED / "__init__.py",
{"children": all_children},
)
if __name__ == "__main__":
main()

View File

@@ -1,91 +0,0 @@
import json
from pathlib import Path
from fastapi import FastAPI
from jinja2 import Template
from pydantic import BaseModel, ConfigDict
from utils import PROJECT_DIR, CodeTemplates, HTTPRequest, RouteObject
CWD = Path(__file__).parent
OUTFILE = PROJECT_DIR / "tests" / "utils" / "api_routes" / "__init__.py"
class PathObject(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
route_object: RouteObject
http_verbs: list[HTTPRequest]
def force_include_in_schema(app: FastAPI):
# clear schema cache
app.openapi_schema = None
for route in app.routes:
route.include_in_schema = True
def get_path_objects(app: FastAPI):
force_include_in_schema(app)
paths = []
for key, value in app.openapi().items():
if key == "paths":
for key, value2 in value.items():
verbs = []
for k, v in value2.items():
verbs.append(HTTPRequest(request_type=k, **v))
paths.append(
PathObject(
route_object=RouteObject(key),
http_verbs=verbs,
)
)
return paths
def dump_open_api(app: FastAPI):
"""Writes the Open API as JSON to a json file"""
OPEN_API_FILE = CWD / "openapi.json"
with open(OPEN_API_FILE, "w") as f:
f.write(json.dumps(app.openapi()))
def read_template(file: Path):
with open(file) as f:
return f.read()
def generate_python_templates(static_paths: list[PathObject], function_paths: list[PathObject]):
template = Template(read_template(CodeTemplates.pytest_routes))
content = template.render(
paths={
"prefix": "/api",
"static_paths": static_paths,
"function_paths": function_paths,
}
)
with open(OUTFILE, "w") as f:
f.write(content)
return
def main():
from mealie.app import app
dump_open_api(app)
paths = get_path_objects(app)
static_paths = [x.route_object for x in paths if not x.route_object.is_function]
function_paths = [x.route_object for x in paths if x.route_object.is_function]
static_paths.sort(key=lambda x: x.router_slug)
function_paths.sort(key=lambda x: x.router_slug)
generate_python_templates(static_paths, function_paths)
if __name__ == "__main__":
main()

View File

@@ -1,100 +0,0 @@
import pathlib
import re
from dataclasses import dataclass, field
from utils import PROJECT_DIR, log, render_python_template
template = """# This file is auto-generated by gen_schema_exports.py
{% for file in data.module.files %}{{ file.import_str() }}
{% endfor %}
__all__ = [
{% for file in data.module.files %}
{%- for class in file.classes -%}
"{{ class }}",
{%- endfor -%}
{%- endfor %}
]
"""
SCHEMA_PATH = PROJECT_DIR / "mealie" / "schema"
SKIP = {"static", "__pycache__"}
class PyFile:
import_path: str
"""The import path of the file"""
classes: list[str]
"""A list of classes in the file"""
def __init__(self, path: pathlib.Path):
self.import_path = path.stem
self.classes = []
self.classes = PyFile.extract_classes(path)
self.classes.sort()
def import_str(self) -> str:
"""Returns a string that can be used to import the file"""
return f"from .{self.import_path} import {', '.join(self.classes)}"
@staticmethod
def extract_classes(file_path: pathlib.Path) -> list[str]:
name = file_path.stem
if name == "__init__" or name.startswith("_"):
return []
classes = re.findall(r"(?m)^class\s(\w+)", file_path.read_text())
return classes
@dataclass
class Modules:
directory: pathlib.Path
"""The directory to search for modules"""
files: list[PyFile] = field(default_factory=list)
"""A list of files in the directory"""
def __post_init__(self):
for file in self.directory.glob("*.py"):
if file.name.startswith("_"):
continue
pfile = PyFile(file)
if len(pfile.classes) > 0:
self.files.append(pfile)
else:
log.debug(f"Skipping {file.name} as it has no classes")
def find_modules(root: pathlib.Path) -> list[Modules]:
"""Finds all the top level modules in the provided folder"""
modules: list[Modules] = []
for file in root.iterdir():
if file.is_dir() and file.name not in SKIP:
modules.append(Modules(directory=file))
return modules
def main():
modules = find_modules(SCHEMA_PATH)
for module in modules:
log.debug(f"Module: {module.directory.name}")
for file in module.files:
log.debug(f" File: {file.import_path}")
log.debug(f" Classes: [{', '.join(file.classes)}]")
render_python_template(template, module.directory / "__init__.py", {"module": module})
if __name__ == "__main__":
main()

View File

@@ -1,219 +0,0 @@
import pathlib
from dataclasses import dataclass
from pathlib import Path
import dotenv
import requests
from jinja2 import Template
from pydantic import ConfigDict
from requests import Response
from utils import CodeDest, CodeKeys, inject_inline, log
from mealie.schema._mealie import MealieModel
BASE = pathlib.Path(__file__).parent.parent.parent
API_KEY = dotenv.get_key(BASE / ".env", "CROWDIN_API_KEY")
@dataclass
class LocaleData:
name: str
dir: str = "ltr"
LOCALE_DATA: dict[str, LocaleData] = {
"en-US": LocaleData(name="American English"),
"en-GB": LocaleData(name="British English"),
"af-ZA": LocaleData(name="Afrikaans (Afrikaans)"),
"ar-SA": LocaleData(name="العربية (Arabic)", dir="rtl"),
"ca-ES": LocaleData(name="Català (Catalan)"),
"cs-CZ": LocaleData(name="Čeština (Czech)"),
"da-DK": LocaleData(name="Dansk (Danish)"),
"de-DE": LocaleData(name="Deutsch (German)"),
"el-GR": LocaleData(name="Ελληνικά (Greek)"),
"es-ES": LocaleData(name="Español (Spanish)"),
"fi-FI": LocaleData(name="Suomi (Finnish)"),
"fr-FR": LocaleData(name="Français (French)"),
"fr-BE": LocaleData(name="Belge (Belgian)"),
"gl-ES": LocaleData(name="Galego (Galician)"),
"he-IL": LocaleData(name="עברית (Hebrew)", dir="rtl"),
"hr-HR": LocaleData(name="Hrvatski (Croatian)"),
"hu-HU": LocaleData(name="Magyar (Hungarian)"),
"is-IS": LocaleData(name="Íslenska (Icelandic)"),
"it-IT": LocaleData(name="Italiano (Italian)"),
"ja-JP": LocaleData(name="日本語 (Japanese)"),
"ko-KR": LocaleData(name="한국어 (Korean)"),
"lt-LT": LocaleData(name="Lietuvių (Lithuanian)"),
"lv-LV": LocaleData(name="Latviešu (Latvian)"),
"nl-NL": LocaleData(name="Nederlands (Dutch)"),
"no-NO": LocaleData(name="Norsk (Norwegian)"),
"pl-PL": LocaleData(name="Polski (Polish)"),
"pt-BR": LocaleData(name="Português do Brasil (Brazilian Portuguese)"),
"pt-PT": LocaleData(name="Português (Portuguese)"),
"ro-RO": LocaleData(name="Română (Romanian)"),
"ru-RU": LocaleData(name="Pусский (Russian)"),
"sl-SI": LocaleData(name="Slovenščina (Slovenian)"),
"sr-SP": LocaleData(name="српски (Serbian)"),
"sv-SE": LocaleData(name="Svenska (Swedish)"),
"tr-TR": LocaleData(name="Türkçe (Turkish)"),
"uk-UA": LocaleData(name="Українська (Ukrainian)"),
"vi-VN": LocaleData(name="Tiếng Việt (Vietnamese)"),
"zh-CN": LocaleData(name="简体中文 (Chinese simplified)"),
"zh-TW": LocaleData(name="繁體中文 (Chinese traditional)"),
}
LOCALE_TEMPLATE = """// This Code is auto generated by gen_ts_locales.py
export const LOCALES = [{% for locale in locales %}
{
name: "{{ locale.name }}",
value: "{{ locale.locale }}",
progress: {{ locale.progress }},
dir: "{{ locale.dir }}",
},{% endfor %}
]
"""
class TargetLanguage(MealieModel):
model_config = ConfigDict(populate_by_name=True, extra="allow")
id: str
name: str
locale: str
dir: str = "ltr"
threeLettersCode: str
twoLettersCode: str
progress: float = 0.0
class CrowdinApi:
project_name = "Mealie"
project_id = "451976"
api_key = API_KEY
def __init__(self, api_key: str):
api_key = api_key
@property
def headers(self) -> dict:
return {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}",
}
def get_projects(self) -> Response:
return requests.get("https://api.crowdin.com/api/v2/projects", headers=self.headers)
def get_project(self) -> Response:
return requests.get(f"https://api.crowdin.com/api/v2/projects/{self.project_id}", headers=self.headers)
def get_languages(self) -> list[TargetLanguage]:
response = self.get_project()
tls = response.json()["data"]["targetLanguages"]
models = [TargetLanguage(**t) for t in tls]
models.insert(
0,
TargetLanguage(
id="en-US",
name="English",
locale="en-US",
dir="ltr",
threeLettersCode="en",
twoLettersCode="en",
progress=100,
),
)
progress: list[dict] = self.get_progress()["data"]
for model in models:
if model.locale in LOCALE_DATA:
locale_data = LOCALE_DATA[model.locale]
model.name = locale_data.name
model.dir = locale_data.dir
for p in progress:
if p["data"]["languageId"] == model.id:
model.progress = p["data"]["translationProgress"]
models.sort(key=lambda x: x.locale, reverse=True)
return models
def get_progress(self) -> dict:
response = requests.get(
f"https://api.crowdin.com/api/v2/projects/{self.project_id}/languages/progress?limit=500",
headers=self.headers,
)
return response.json()
PROJECT_DIR = Path(__file__).parent.parent.parent
datetime_dir = PROJECT_DIR / "frontend" / "lang" / "dateTimeFormats"
locales_dir = PROJECT_DIR / "frontend" / "lang" / "messages"
nuxt_config = PROJECT_DIR / "frontend" / "nuxt.config.js"
reg_valid = PROJECT_DIR / "mealie" / "schema" / "_mealie" / "validators.py"
"""
This snippet walks the message and dat locales directories and generates the import information
for the nuxt.config.js file and automatically injects it into the nuxt.config.js file. Note that
the code generation ID is hardcoded into the script and required in the nuxt config.
"""
def inject_nuxt_values():
all_date_locales = [
f'"{match.stem}": require("./lang/dateTimeFormats/{match.name}"),' for match in datetime_dir.glob("*.json")
]
all_langs = []
for match in locales_dir.glob("*.json"):
lang_string = f'{{ code: "{match.stem}", file: "{match.name}" }},'
all_langs.append(lang_string)
log.debug(f"injecting locales into nuxt config -> {nuxt_config}")
inject_inline(nuxt_config, CodeKeys.nuxt_local_messages, all_langs)
inject_inline(nuxt_config, CodeKeys.nuxt_local_dates, all_date_locales)
def inject_registration_validation_values():
all_langs = []
for match in locales_dir.glob("*.json"):
lang_string = f'"{match.stem}",'
all_langs.append(lang_string)
# sort
all_langs.sort()
log.debug(f"injecting locales into user registration validation -> {reg_valid}")
inject_inline(reg_valid, CodeKeys.nuxt_local_messages, all_langs)
def generate_locales_ts_file():
api = CrowdinApi("")
models = api.get_languages()
tmpl = Template(LOCALE_TEMPLATE)
rendered = tmpl.render(locales=models)
log.debug(f"generating locales ts file -> {CodeDest.use_locales}")
with open(CodeDest.use_locales, "w") as f:
f.write(rendered) # type:ignore
def main():
if API_KEY is None or API_KEY == "":
log.error("CROWDIN_API_KEY is not set")
return
generate_locales_ts_file()
inject_nuxt_values()
inject_registration_validation_values()
if __name__ == "__main__":
main()

View File

@@ -1,128 +0,0 @@
from pathlib import Path
from jinja2 import Template
from pydantic2ts import generate_typescript_defs
from utils import log
# ============================================================
template = """// This Code is auto generated by gen_ts_types.py
{% for name in global %}import {{ name }} from "@/components/global/{{ name }}.vue";
{% endfor %}{% for name in layout %}import {{ name }} from "@/components/layout/{{ name }}.vue";
{% endfor %}
declare module "vue" {
export interface GlobalComponents {
// Global Components
{% for name in global -%}
{{ " " }}{{ name }}: typeof {{ name }};
{% endfor -%}
{{ " " }}// Layout Components
{% for name in layout -%}
{{ " " }}{{ name }}: typeof {{ name }};
{% endfor -%}{{ " }"}}
}
export {};
"""
CWD = Path(__file__).parent
PROJECT_DIR = Path(__file__).parent.parent.parent
def generate_global_components_types() -> None:
destination_file = PROJECT_DIR / "frontend" / "types" / "components.d.ts"
component_paths = {
"global": PROJECT_DIR / "frontend" / "components" / "global",
"layout": PROJECT_DIR / "frontend" / "components" / "Layout",
}
def render_template(template: str, data: dict) -> str | None:
tmpl = Template(template)
return tmpl.render(**data)
def build_data() -> dict:
data = {}
for name, path in component_paths.items():
components = [component.stem for component in path.glob("*.vue")]
components.sort()
data[name] = components
return data
def write_template(text: str) -> None:
destination_file.write_text(text)
text = render_template(template, build_data())
if text:
write_template(text)
# ============================================================
# Pydantic To Typescript Generator
def generate_typescript_types() -> None:
def path_to_module(path: Path):
str_path: str = str(path)
str_path = str_path.removeprefix(str(PROJECT_DIR))
str_path = str_path.removeprefix("/")
str_path = str_path.replace("/", ".")
return str_path
schema_path = PROJECT_DIR / "mealie" / "schema"
types_dir = PROJECT_DIR / "frontend" / "lib" / "api" / "types"
ignore_dirs = ["__pycache__", "static", "_mealie"]
skipped_files: list[Path] = []
skipped_dirs: list[Path] = []
failed_modules: list[Path] = []
for module in schema_path.iterdir():
if module.is_dir() and module.stem in ignore_dirs:
skipped_dirs.append(module)
continue
if not module.is_dir() or not module.joinpath("__init__.py").is_file():
skipped_files.append(module)
continue
ts_out_name = module.name.replace("_", "-") + ".ts"
out_path = types_dir.joinpath(ts_out_name)
try:
path_as_module = path_to_module(module)
generate_typescript_defs(path_as_module, str(out_path), exclude=("MealieModel")) # type: ignore
except Exception as e:
failed_modules.append(module)
log.error(f"Module Error: {e}")
log.debug("\n📁 Skipped Directories:")
for skipped_dir in skipped_dirs:
log.debug(f" 📁 {skipped_dir.name}")
log.debug("📄 Skipped Files:")
for f in skipped_files:
log.debug(f" 📄 {f.name}")
if len(failed_modules) > 0:
log.error("❌ Failed Modules:")
for f in failed_modules:
log.error(f"{f.name}")
def main():
log.debug("\n-- Starting Global Components Generator --")
generate_global_components_types()
log.debug("\n-- Starting Pydantic To Typescript Generator --")
generate_typescript_types()
if __name__ == "__main__":
main()

View File

@@ -1,28 +0,0 @@
from pathlib import Path
import gen_py_pytest_data_paths
import gen_py_pytest_routes
import gen_py_schema_exports
import gen_ts_locales
import gen_ts_types
from utils import log
CWD = Path(__file__).parent
def main():
items = [
(gen_py_schema_exports.main, "schema exports"),
(gen_ts_types.main, "frontend types"),
(gen_ts_locales.main, "locales"),
(gen_py_pytest_data_paths.main, "test data paths"),
(gen_py_pytest_routes.main, "pytest routes"),
]
for func, name in items:
log.info(f"Generating {name}...")
func()
if __name__ == "__main__":
main()

View File

@@ -1,7 +0,0 @@
from pathlib import Path
CWD = Path(__file__).parent
{% for f in data.children %}
{{ f.var }} = CWD / "{{ f.path }}"
{% endfor %}

View File

@@ -1,11 +0,0 @@
# This Content is Auto Generated for Pytest
prefix = "{{paths.prefix}}"
{% for path in paths.static_paths %}
{{ path.router_slug }} = "{{path.prefix}}{{ path.route }}"
"""`{{path.prefix}}{{ path.route }}`"""{% endfor %}
{% for path in paths.function_paths %}
def {{path.router_slug}}({{path.var|join(", ")}}):
"""`{{ paths.prefix }}{{ path.route }}`"""
return f"{prefix}{{ path.route }}"
{% endfor %}

Some files were not shown because too many files have changed in this diff Show More