DEV Community

Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on

Cheat sheet of 'Alembic' commands

Here’s a complete cheat sheet of Alembic commands you'll use for managing database migrations in your project — especially useful since you’re using PostgreSQL + Alembic for version-controlled schema changes.


📦 Alembic Basics

🧱 1. Initialize Alembic

Run this once to set up Alembic in your project:

alembic init alembic
Enter fullscreen mode Exit fullscreen mode

🛠️ 2. Configure alembic.ini and env.py

  • In alembic.ini, set your database URL:
sqlalchemy.url = postgresql+asyncpg://user:pass@localhost/db
Enter fullscreen mode Exit fullscreen mode

⚠️ If you're using async SQLAlchemy, the URL above is fine, but you’ll need to tweak env.py. Let me know if you want the async-ready version of env.py.


🚀 Migration Commands

📌 3. Create a new migration script (autogenerate)

This compares your models and the DB, then generates a migration file:

alembic revision --autogenerate -m "create users table"
Enter fullscreen mode Exit fullscreen mode
  • You can also create an empty migration:
alembic revision -m "initial setup"
Enter fullscreen mode Exit fullscreen mode

🧱 4. Apply Migrations

Run migrations and apply changes to the database:

alembic upgrade head
Enter fullscreen mode Exit fullscreen mode

To upgrade to a specific revision:

alembic upgrade <revision_id>
Enter fullscreen mode Exit fullscreen mode

🔁 5. Downgrade Migrations

Revert last migration:

alembic downgrade -1
Enter fullscreen mode Exit fullscreen mode

To downgrade to a specific revision:

alembic downgrade <revision_id>
Enter fullscreen mode Exit fullscreen mode

🧾 6. View Current DB Revision

alembic current
Enter fullscreen mode Exit fullscreen mode

🕵️‍♂️ 7. Check History of Migrations

alembic history
Enter fullscreen mode Exit fullscreen mode

🔍 8. Show Detailed Info of a Migration

alembic show <revision_id>
Enter fullscreen mode Exit fullscreen mode

🔄 Bonus: Stamp DB without applying migrations

Useful if you want Alembic to think the DB is up-to-date without actually running the migration:

alembic stamp head
Enter fullscreen mode Exit fullscreen mode

⚙️ Common Structure Recap

Your alembic/ folder will contain:

alembic/
  versions/
    20240420_create_users_table.py
  env.py          # Main config (load metadata, engine)
alembic.ini       # Connection settings
Enter fullscreen mode Exit fullscreen mode

🔥 Pro Tip (for async users):

If you’re using asyncpg + async SQLAlchemy, you must modify env.py to support async migrations. Would you like a ready-to-use env.py file for async migrations?

Top comments (0)