Panduan Lengkap Menggunakan Alembic: Database Migration Made Easy
Alembic adalah tool migration database untuk SQLAlchemy yang powerful dan fleksibel. Tool ini memungkinkan Anda melacak perubahan skema database secara version control, membuat migration scripts, dan menjalankan upgrade atau downgrade database dengan mudah.
Dalam tutorial ini, kita akan mempelajari Alembic dari dasar hingga advanced usage dengan contoh praktis.
Mengapa Alembic?
Keunggulan Alembic:
Instalasi
Install Alembic
# Install Alembic
pip install alembic
Install dengan SQLAlchemy (jika belum)
pip install sqlalchemy
Install database driver sesuai kebutuhan
pip install psycopg2-binary # PostgreSQL
pip install pymysql # MySQL
pip install aiosqlite # SQLite async
Verifikasi Instalasi
alembic --version
Output: alembic 1.13.x
Setup Project: Konfigurasi Awal
1. Inisialisasi Alembic
# Buat folder project
mkdir myproject && cd myproject
Inisialisasi Alembic
alembic init alembic
Struktur folder yang dihasilkan:
myproject/
├── alembic/
│ ├── versions/ # Folder untuk migration files
│ ├── env.py # Environment configuration
│ ├── README # Dokumentasi
│ └── script.py.mako # Template untuk migration
├── alembic.ini # Konfigurasi utama Alembic
2. Konfigurasi Database URL
Edit file alembic.ini:
# alembic.ini
[alembic]
scriptlocation = alembic
prependsyspath = .
Database URL
sqlalchemy.url = postgresql://user:password@localhost/mydatabase
Untuk SQLite
sqlalchemy.url = sqlite:///./app.db
Untuk MySQL
sqlalchemy.url = mysql+pymysql://user:password@localhost/mydatabase
3. Setup Model SQLAlchemy
Buat file models.py:
# models.py
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean, Text
from sqlalchemy.orm import declarativebase, relationship
from datetime import datetime
Base = declarativebase()
class User(Base):
tablename = 'users'
id = Column(Integer, primarykey=True)
username = Column(String(50), unique=True, nullable=False)
email = Column(String(100), unique=True, nullable=False)
passwordhash = Column(String(255), nullable=False)
isactive = Column(Boolean, default=True)
createdat = Column(DateTime, default=datetime.utcnow)
# Relationship
posts = relationship("Post", backpopulates="author")
class Post(Base):
tablename = 'posts'
id = Column(Integer, primarykey=True)
title = Column(String(200), nullable=False)
content = Column(Text)
userid = Column(Integer, ForeignKey('users.id'), nullable=False)
createdat = Column(DateTime, default=datetime.utcnow)
updatedat = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
# Relationship
author = relationship("User", backpopulates="posts")
4. Konfigurasi env.py untuk Autogenerate
Edit file alembic/env.py:
# alembic/env.py
from logging.config import fileConfig
from sqlalchemy import enginefromconfig, pool
from alembic import context
Import Base dari models
import sys
from pathlib import Path
sys.path.append(str(Path(file).parent.parent))
from models import Base
Alembic Config object
config = context.config