Add some db migrations

This commit is contained in:
Lucas Verney 2018-03-11 17:36:49 +01:00
parent d30e5f9053
commit f529619c99
2 changed files with 59 additions and 0 deletions

View File

@ -49,6 +49,14 @@ If you serve the app with a reverse proxy, you should serve the content of
Bottle webserver.
## Updating
If you are updating the app, the database schema may have changed. There is a
set of migrations under the `migrations` folder which is a set of standalone
scripts to run to update your database schema. Each script is named after the
commit it is handling.
## Contributing
All contributions are welcome, feel free to open a MR. Just in case, if you

View File

@ -0,0 +1,51 @@
import base64
import os
import magic
from peewee import TextField
from playhouse.migrate import (
SqliteDatabase, SqliteMigrator, migrate
)
SCRIPT_DIR = os.path.dirname(__file__)
def update_picture(picture):
if not picture:
return picture
picture_mime = (
'data:%s;base64' % magic.from_buffer(picture,
mime=True)
)
return '%s,%s' % (
picture_mime,
base64.b64encode(picture).decode('utf-8')
)
def run_migration():
recipes_db = SqliteDatabase(os.path.join(SCRIPT_DIR, '../recipes.db'))
migrator = SqliteMigrator(recipes_db)
new_picture_field = TextField(null=True)
updated_pictures = [
(recipe_id, update_picture(picture))
for (recipe_id, picture) in recipes_db.execute_sql(
'SELECT id, picture FROM recipe'
)
]
migrate(
migrator.drop_column('recipe', 'picture'),
migrator.add_column('recipe', 'picture', new_picture_field),
)
for (recipe_id, picture) in updated_pictures:
if picture:
recipes_db.execute_sql('UPDATE recipe SET picture=? WHERE id=?',
(picture, recipe_id))
if __name__ == "__main__":
run_migration()