One of the first things that you learn in programming classes is that nobody can get a complex program right the very first time. Software evolves over time, and we hope for the best. Automation in automated testing helps ensure that our programs improve over time. However, when it comes to evolving database schemas, automation doesn't seem to be so obvious. Especially in large enterprises, database schemas are the domain of database administrators and specialists. Of course, there are security and operational issues related to changing schemas, even more so in production databases. In any case, you can always implement database migration in your local test environment and document proposed changes for the production team.
We will use Alembic to demonstrate how you can go about setting up migration scripts. In my opinion, Alembic is the right tool for the job, although it is in beta as of September 2015.
Install Alembic with the following command:
$ pip install alembic
Alembic depends on SQLAlchemy, and it will automatically install SQLAlchemy if needed. You should now have the alembic
command in your path. I used Alembic 0.8.2 for this chapter.
The following steps describe how to set up Alembic migration steps. When we run the Alembic initialization script in a directory, it creates an alembic
directory and a configuration file named alembic.ini
:
$ alembic init alembic
alembic.ini
file as required. For instance, change the sqlalchemy.url
property to point to the correct database.