💻 Installing Alembic
Before using Alembic, we need to install it into our FastAPI project.
Terminal Command:
pip install alembicOnce installed, we can access Alembic commands to manage migrations and keep our database up-to-date with our models.
⚡ Common Alembic Commands
Here are the most commonly used Alembic commands and what they do:
Alembic Command | Description |
|---|---|
| Initialize a new Alembic environment. |
| Create a new migration revision. |
| Auto-generate a migration based on model changes. |
| Apply a migration to upgrade the database. |
| Revert the database by one revision. |
| Display the current revision of the database. |
| List all migrations in chronological order. |
| Show the latest revision(s). |
| Show branch points in migration history. |
| Display details of a specific revision. |
| Mark the database with a revision without running migrations. |
| Merge two migration branches. |
| Check for new upgrade operations (used with autogenerate). |
| Open a migration revision file for editing. |
📁 Alembic Project Structure
After initializing Alembic in your project using:
alembic init alembicyou will see two new items in your project directory:
alembic.iniThis configuration file contains settings Alembic uses when running migrations.
You can update database connection URLs or other project-specific configurations here.
alembic/directoryThis folder holds the environmental scripts and migration files.
Each migration revision is stored here, along with upgrade and downgrade scripts.
This ensures your application can safely modify database tables while maintaining data integrity.