Alembic is a lightweight database migration tool for use with SQLAlchemy in Python applications. It is designed to manage version control for your database schema, allowing you to evolve it gradually and predictably.
This guide walks through setting up and using Alembic for managing database schema migrations.
đź”§ Step 1: Initialize an Alembic Project
To start using Alembic, you first need to initialize it within your Python project. This sets up the necessary directory structure and configuration files.
alembic init <APP_NAME>
This command creates a directory structure like:
<APP_NAME>/
├── versions/
├── env.py
└── alembic.ini
⚙️ Step 2: Configure the Database URL
After initialization, configure the database connection string by editing the alembic.ini file.
Locate the line:
sqlalchemy.url = driver://user:pass@localhost/dbname
Replace it with your actual database credentials and driver.
🛠️ Step 3: Create a New Migration Script
To generate a new migration script, use the following command:
alembic revision -m "your commit message"
This creates a new Python script under the versions/ directory. These scripts represent individual migrations, each containing upgrade() and downgrade() functions.
Example structure:
versions/
└── abc123_add_users_table.py
Example Script Snippet
python
def upgrade():
op.create_table(
'users',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('username', sa.String(50), nullable=False),
sa.Column('email', sa.String(100), nullable=False)
)
def downgrade():
op.drop_table('users')
⬆️ Step 4: Apply the Migration
Once you've defined the schema changes in the migration script, apply them to the database using the upgrade command.
alembic upgrade <VERSION_NAME>
To upgrade to the latest migration (head):
alembic upgrade head
This updates your database schema to match the migration history.
âś… Summary
Alembic simplifies the process of managing schema changes in Python applications. Follow these four steps:
- Initialize Alembic in your project.
- Set the database URL in alembic.ini.
- Generate and modify migration scripts.
- Apply migrations using the upgrade command.
Using Alembic ensures that your database schema evolves in a controlled, versioned manner — perfect for collaborative development and production systems.
Top comments (0)