π Why Alembic?
Currently, if we want to make changes to our database tables (for example, adding a column), we would have to:
Delete the existing table in SQLite, MySQL, or PostgreSQL.
Rerun the application so SQLAlchemy can recreate the table.
Unfortunately, this deletes all existing data.
Alembic solves this problem by allowing us to modify tables without losing data. It manages migrations efficiently, even in production.
π» Installing Alembic
First, we need to install Alembic in our project.
<aside> π‘
Make sure Virtual Environment is active and You are in TodoApp
</aside>
Terminal Command:
pip install alembicThis will download and install Alembic along with all required dependencies.
β‘ Initializing Alembic
Once Alembic is installed, we need to initialize it for our project:
alembic init alembicAfter running this command, Alembic will create:
Alembic version information
Alembic scripts and environment
alembic/directoryalembic.iniconfiguration fileREADME file
π Understanding the Alembic Project Structure
1. alembic.ini
This configuration file contains information about:
Database connection URL (
sqlalchemy.url)Migration script locations
Time zone and other Alembic options
In future sessions, we will update the
SQLAlchemy URLto point to our project database.
2. alembic/ Directory
The alembic/ directory contains all the environmental scripts and migration files. Key components include:
Versions folder β stores upgrade and downgrade migration scripts
env.pyβ contains environment setup for Alembic; weβll modify this for our project databaseREADMEβ generic information about Alembic environmentscript.py.makoβ template for migration scripts (optional; mostly for reference)
This directory is where all migration history is maintained, ensuring your database can evolve without losing data.