Checking For Multiple Migration Heads In Open Event server

While working on Open Event server, lots of db refactor were made in the first phase. That means a multiple contributors working on the refactor of the same database.

The open event server uses SQLAlchemy as its ORM. SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. It provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

While for database migrations, the server uses Alembic. Alembic is a lightweight database migration tool for usage with the SQLAlchemy Database Toolkit for Python. Alembic provides for the creation, management, and invocation of change management scripts for a relational database, using SQLAlchemy as the underlying engine.

The issue the project collaborators faced the most when handling database migrations was when multiple PRs were merged with migration files that pointed to different heads. In such cases, Alembic would raise a multiple heads error, after the deployment has been made. There were no tests to ensure that this doesn’t happen.

The number of migration heads can be found by the following command

python db heads


The above command prints the identifiers of the migration heads, each on a different line. We can count the no. of lines outputted by the above command with the help of wc (word count). The result can be stored as a variable as follows:

lines=`python db heads | wc | awk '{print $1}'`


If the no. of lines is one, it means there is only one head and our test should pass. If the head is not one, the test should fail. Following is the test script to do that:

lines=`python db heads | wc | awk '{print $1}'`

if [ $lines -ne 1 ]
   exit 1
   exit 0


Related links:

Published by


Full Stack Developer at Fossasia | Interested in software design and architecture | An Avid Potterhead <3