Alembic 学习
Installation and initiate
pip install alembic
pip install python-decouple # To load environment variables
# Setup project
alembic init migrations
Config
.env
DATABASE_URL=postgresql://postgres:password@localhost:5432/databasename
env.py
from sqlmodel import SQLModel
from decouple import config
# ...
# Load Database_URL from .env file
DATABASE_URL = config("DATABASE_URL")
# ...
config.set_main_option("sqlalchemy.url", DATABASE_URL)
# ...
# Add 'autogenerate' migration support
from models import Hero
target_metadata = SQLModel.metadata
script.py.mako
# ...
# import sqlalchemy as sa
import sqlmodel
# ${imports if imports else ""}
# ...
Generate migration files
# Create migration files
alembic revision # Wrong command
alembic revision --autogenerate -m "<migraion_name>"
alembic revision --autogenerate -m "Create hero table"
Upgrade and downgrade migration files
alembic upgrade head
alembic downgrade head-1
alembic downgrade <commit>
History and info
alembic history
alembic show <commit>
Resource
- Database migrations matter! Get up and running with Alembic + sqlmodel: https://www.youtube.com/watch?v=gekC1ESLxPs