From f529619c99ea481caae1cad33acee00cc76d4135 Mon Sep 17 00:00:00 2001 From: "Phyks (Lucas Verney)" Date: Sun, 11 Mar 2018 17:36:49 +0100 Subject: [PATCH] Add some db migrations --- README.md | 8 +++ ...30e5f90530f1d55f236c87aa279920269317047.py | 51 +++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 migrations/d30e5f90530f1d55f236c87aa279920269317047.py diff --git a/README.md b/README.md index 8a133e2..1ca1bb3 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/migrations/d30e5f90530f1d55f236c87aa279920269317047.py b/migrations/d30e5f90530f1d55f236c87aa279920269317047.py new file mode 100644 index 0000000..da9fd42 --- /dev/null +++ b/migrations/d30e5f90530f1d55f236c87aa279920269317047.py @@ -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()