Skip to main content
In this article, we will walk through the process of creating and modifying database tables using Alembic migrations and how to roll back those changes when needed. This guide is ideal for developers looking to manage database schema changes in a seamless manner.

Creating the Initial Table

Initially, we created our first table using an Alembic revision. The following migration script creates a “posts” table:
When you run this migration, you may see output similar to the following:
Ensure your Alembic configuration is set correctly to avoid unrecognized argument errors.

Modifying the Table: Adding a New Column

After reviewing our application models, we decided to add a new column called “content” to the “posts” table. First, update your SQLAlchemy model as shown below:
Next, generate a new Alembic revision with an informative message:
This command creates a new migration file. You then need to define the upgrade and downgrade logic to add this column. Below is an example revision file for this change:
When you run the upgrade, the log output might look like this:

Verifying the Applied Migration

To ensure the migration has been applied successfully, you can check the current revision using:
To view the latest (head) migration, run:
Since the latest migration is referred to as the head, upgrade to it by specifying the revision number or simply using “head”:
After upgrading successfully, verify PostgreSQL table properties using a query like:

Rolling Back a Migration

If you decide that the “content” column is no longer needed, you can revert the change using the downgrade function defined in the migration script. To roll back the changes, run:
Alternatively, you can perform a relative downgrade by moving one revision back:
After downgrading, refresh your database client to verify that the “content” column has been removed.
Before executing a downgrade in a production environment, ensure that you have backed up your database to prevent any accidental data loss.

Summary

Alembic offers a streamlined way to manage your database schema:
  • Create new tables or modify existing ones by writing migrations.
  • Apply changes via alembic upgrade and roll them back with alembic downgrade.
This process provides excellent version control for your database, ensuring that any changes can be easily reversed if necessary. For further reading, check out these helpful resources:

Watch Video