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

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

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

⚠️ 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"
  • You can also create an empty migration:
alembic revision -m "initial setup"

🧱 4. Apply Migrations

Run migrations and apply changes to the database:

alembic upgrade head

To upgrade to a specific revision:

alembic upgrade

🔁 5. Downgrade Migrations

Revert last migration:

alembic downgrade -1

To downgrade to a specific revision:

alembic downgrade

🧾 6. View Current DB Revision

alembic current

🕵️‍♂️ 7. Check History of Migrations

alembic history

🔍 8. Show Detailed Info of a Migration

alembic show

🔄 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

⚙️ 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

🔥 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?