This article explains how to create, modify, and roll back database tables using Alembic migrations for effective schema management.
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.
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:
Copy
Ask AI
(venv) C:\Users\sanje\Documents\Courses\fastapi>alembic revision -m "add content column to posts table"
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:
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:
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: