Alembic 是一个 Pythonic 的迁移工具,用于 SQLAlchemy 数据库应用。本教程将带你了解 Alembic 的基本用法。

安装 Alembic

首先,确保你已经安装了 SQLAlchemy。然后,使用以下命令安装 Alembic:

pip install alembic

创建一个新项目

在你的项目目录下,创建一个名为 migrations 的文件夹,并在其中创建一个名为 env.py 的文件。

from alembic import context
from sqlalchemy import create_engine
from myapp.models import Base

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
context.configure(
    # ...other options...
    connection=create_engine('sqlite:///myapp.db')
)

# this runs the Alembic autogenerate script
# which will generate the upgrade files for us, then
# we will copy them into the migrations folder
context.run_script()

# finally, connect to the database and create all tables
engine = create_engine('sqlite:///myapp.db')
Base.metadata.create_all(engine)

迁移数据库

使用以下命令创建一个迁移:

alembic revision -m "create users table"

这将在 migrations/versions 目录下创建一个新的文件,其中包含创建用户表的 SQL 语句。

应用迁移

要应用迁移到数据库,使用以下命令:

alembic upgrade head

这会将所有未应用的迁移应用到数据库中。

查看迁移历史

要查看迁移历史,使用以下命令:

alembic history

更多关于 Alembic 的信息,请访问我们的官方文档


SQLAlchemy

Alembic