From 119d4a005234477894df569a992d142b699288c9 Mon Sep 17 00:00:00 2001 From: forest Date: Sat, 9 May 2020 19:22:25 -0500 Subject: [PATCH] correctly handle when the desiredSchemaVersion < schemaVersion --- README.md | 4 +++- capsulflask/db.py | 13 +++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index b3ff279..b9ea148 100644 --- a/README.md +++ b/README.md @@ -7,10 +7,12 @@ Python Flask web application for capsul.org capsulflask has a concept of a schema version. When the application starts, it will query the database for a table named `schemaversion` that has one row and one column (`version`). If the `version` it finds is not equal to the `desiredSchemaVersion` variable set in `db.py`, it will run migration scripts from the `schema_migrations` folder one by one until the `schemaversion` table shows the correct version. -For example, the script named `02_up_xyz.sql` should contain code that migrates the database in a reverse-able fashion from schema version 1 to schema version 2. Likewise, the script `02_down_xyz.sql` should contain code that migrates from schema version 2 back to schema version 1. +For example, the script named `02_up_xyz.sql` should contain code that migrates the database from schema version 1 to schema version 2. Likewise, the script `02_down_xyz.sql` should contain code that migrates from schema version 2 back to schema version 1. **IMPORTANT: if you need to make changes to the schema, make a NEW schema version. DO NOT EDIT the existing schema versions.** +In general, for safety, schema version upgrades should not delete data. Schema version downgrades will simply throw an error and exit for now. + ## how to run locally Ensure you have the pre-requisites for the psycopg2 Postgres database adapter package diff --git a/capsulflask/db.py b/capsulflask/db.py index 214ce88..a987b38 100644 --- a/capsulflask/db.py +++ b/capsulflask/db.py @@ -60,8 +60,13 @@ def init_app(app): cursor.execute("SELECT Version FROM schemaversion") schemaVersion = cursor.fetchall()[0][0] - - # print(schemaVersion) + + if schemaVersion > desiredSchemaVersion: + print("schemaVersion ({}) > desiredSchemaVersion ({}). schema downgrades are not supported yet. exiting.".format( + schemaVersion, desiredSchemaVersion + )) + exit(1) + while schemaVersion < desiredSchemaVersion: migrationKey = "%02d_up" % (schemaVersion+1) print("schemaVersion ({}) < desiredSchemaVersion ({}). running migration {}".format( @@ -94,8 +99,8 @@ def init_app(app): app.config['PSYCOPG2_CONNECTION_POOL'].putconn(db) - print("schema migration completed. {}current schemaVersion: \"{}\"".format( - ("" if actionWasTaken else "(no action was taken). "), schemaVersion + print("{} current schemaVersion: \"{}\"".format( + ("schema migration completed." if actionWasTaken else "schema is already up to date. "), schemaVersion )) app.teardown_appcontext(close_db)