SQLAlchemy Migrate is a really good tool for managing database upgrades for SQLAlchemy centric projects. I've been using it for 6 months on New Metal Army and I haven't had a screwed website upgrade yet!
For those that don't know SQLAlchemy-migrate allows you to version control database changes and easily upgrade and downgrade a database. Basically you write a python script with two functions: upgrade and downgrade. You test the script against the database, commit it to the SQLAlchemy-migrate version repository (not to be confused with your source control mechanism). Finally you upgrade your development database.
When it the time comes to deploy the new application you simply ask sqlalchemy-migrate to upgrade your database to the current version. sqlalchemy-migrate reads the current version of your schema from the database (via a custom table it inserts) and proceeds to upgrade your schema by running each upgrade script in turn.
Often you want your upgrades and downgrades to run within a transaction. Not because you expect them to fail but because while writing them you don't wont to leave the database partially upgraded or downgraded if your script fails. To do this I wrote a transaction decorator. Here is a template for an upgrade script:
#!/usr/bin/env python # encoding: utf-8 from datetime import datetime from sqlalchemy import * from migrate import * from migrate.changeset import * metadata = MetaData(migrate_engine) def transaction(f, *args, **kwargs): def wrapper(*args, **kwargs): connection = migrate_engine.connect() transaction = connection.begin() try: result = f(*args, **kwargs) transaction.commit() return result except: transaction.rollback() raise finally: connection.close() wrapper.__name__ = f.__name__ wrapper.__dict__ = f.__dict__ wrapper.__doc__ = f.__doc__ return wrapper @transaction def upgrade(): pass @transaction def downgrade(): pass
I fill in the upgrade and downgrade functions and I'm done
I include the decorator in every script as it's good practice to make your scripts as independent as possible. If you imported it from a module you may improve it in the future and inadvertently break your old downgrade scripts.
I hope this helps you version control your database schema and data.
