Setting Up Alembic For Migration In FastAPI
Every time you add a new attribute, modify the structure of your SQLAlchemy models, etc., you must perform a "migration" to replicate those changes in the database. Examples of migrations include adding new columns, tables, etc.
As a result, unlike Django, alembic is not included in the built-in fast API for migrating model updates to the database. What is alembic used for, then?
Alembic is a small database migration tool that may be used with Python's SQLAlchemy Database Toolkit.
Here are the steps involved:
- Install Alembic In Your Virtual Environment:
pip install alembic
Then we have to initialize alembic:
A) For Sync Database Connection:
alembic init alembic
B) For Async Database Connection:
alembic init -t async migrations
Following initialization, a file called "alembic.ini" will be created. Open this file to see "sqlalchemy.url," which is where you need to enter your database connection string but without commas.
For PostgreSQL:
A) For Sync Database Connection:
postgresql://user:password@host:port/db_name
B) For Async Database Connection:
postgresql+asyncpg://user:password@host:port/db_name
We have to make some changes in the env.py file under the alembic folder initially target_metadata = None. We must change this target metadata to our model base. In my example, the models folder has a model.py file, and my code looks like this:
from models.user_model import Base target_metadata = Base.metadata
When you set
target_metadata = Base.metadata
, you are telling Alembic to use the metadata from your SQLAlchemy models to generate the migration scripts.Now we have set our target_metadata after that we have to run
alembic revision --autogenerate -m "initial migrations"
this will create a migration file under alembic/versions but now you will see some code under these two functions “upgrade()” or “downgrade()” which is the SQL query generated for making the changes in your database.
Now run the following command is used to apply database migrations (changes in the database) in a project that uses Alembic for managing database schema changes
alembic upgrade head
Happy Learning !!
Subscribe to my newsletter
Read articles from Vishal Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by