Bỏ qua

Alembic Migrations

Alembic là gì?

Alembic là tool quản lý database schema migration cho SQLAlchemy. Thay vì chạy SQL thủ công, Alembic tự động detect thay đổi trong models và tạo migration scripts.

Các lệnh thường dùng

Tạo migration mới (auto-detect)

alembic revision --autogenerate -m "Mô tả thay đổi"

Alembic sẽ so sánh models hiện tại với database và tạo file migration trong thư mục migrations/versions/.

Best practice

Luôn viết message mô tả rõ ràng, ví dụ: "Add users table", "Add email column to courses".

Chạy migration (upgrade)

# Upgrade lên revision mới nhất
alembic upgrade head

# Upgrade 1 step
alembic upgrade +1

Rollback migration (downgrade)

# Rollback 1 step
alembic downgrade -1

# Rollback về đầu (xóa hết tables)
alembic downgrade base

Xem trạng thái hiện tại

# Xem revision hiện tại
alembic current

# Xem lịch sử migrations
alembic history

Workflow khi thay đổi database

graph LR
    A["Sửa models/*.py"] --> B["alembic revision<br/>--autogenerate"]
    B --> C["Review file migration"]
    C --> D["alembic upgrade head"]
    D --> E["Test trên local"]
    E --> F["Commit & Push"]

Step-by-step

  1. Sửa model — Thêm/sửa/xóa column trong models/*.py
  2. Tạo migration:
    alembic revision --autogenerate -m "Mô tả thay đổi"
    
  3. Review — Mở file vừa tạo trong migrations/versions/, kiểm tra upgrade()downgrade()
  4. Chạy local:
    alembic upgrade head
    
  5. Test — Verify database đã thay đổi đúng
  6. Commit — Push migration file lên Git

Không bao giờ sửa migration đã chạy trên production

Nếu cần sửa, tạo migration mới để thay đổi. Migration đã apply trên prod = lịch sử, không được edit.

Chạy migration trên các môi trường

cd backend
source venv/Scripts/activate  # Windows
alembic upgrade head
# Tạm đổi DATABASE_URL trong .env sang staging DB
# Hoặc set env var:
DATABASE_URL=postgresql://...staging... alembic upgrade head
# Cách 1: Từ máy local (đổi DATABASE_URL)
DATABASE_URL=postgresql://...supabase...?sslmode=require alembic upgrade head

# Cách 2: SSH/Shell trên hosting (Northflank Shell)
alembic upgrade head

Nhớ đổi lại DATABASE_URL

Sau khi chạy migration cho staging/prod, nhớ đổi .env về giá trị local dev.

Xử lý Conflicts

Khi 2 developer tạo migration cùng lúc:

  1. Pull code mới nhất
  2. Xóa migration file bị conflict (của mình)
  3. Tạo lại migration:
    alembic revision --autogenerate -m "Mô tả thay đổi"
    
  4. Chạy alembic upgrade head