Alembic 是什么?
类比 Git,但管理的是数据库结构:
Git(代码版本控制) Alembic(数据库版本控制)
├── git commit ├── alembic revision
├── git log ├── alembic history
├── git checkout ├── alembic downgrade
└── git push └── alembic upgrade
工作原理
1. 您的数据库当前状态
├── 1 表
├── 2 表
└── 3 表
2. 创建迁移脚本(类似 git commit)
alembic revision -m "add xx table"
↓
生成文件:versions/abc123_add_xx.py
3. 迁移脚本内容
def upgrade():
"""执行这个函数 = 前进一个版本"""
op.create_table('xx', ...)
def downgrade():
"""执行这个函数 = 回退一个版本"""
op.drop_table('xx')
4. 应用迁移
alembic upgrade head
↓
在数据库中:
├── 执行 upgrade() 函数
├── 创建 xx 表
└── 记录到 alembic_version 表
在数据库中,alembic会自动创建一个表
-- Alembic 自动创建这个表
CREATE TABLE alembic_version (
version_num VARCHAR(32) NOT NULL,
PRIMARY KEY (version_num)
);
-- 内容示例
SELECT * FROM alembic_version;
-- 结果:
-- +-------------+
-- | version_num |
-- +-------------+
-- | abc123def | ← 当前数据库版本号
-- +-------------+
-- 作用:Alembic 通过这个表知道数据库当前的版本
使用步骤
- 安装
# Windows PowerShell 或 Linux Terminal
pip install alembic pymysql
- 初始化 Alembic
# 在项目根目录执行(D:\xx\xx\Datebase)
cd D:\xx\xx\Datebase
alembic init Database/migrations
这会创建:
Database/
└── migrations/
├── versions/(空目录,后续存放迁移脚本)
├── env.py(Alembic 环境配置)
├── script.py.mako(模板文件)
└── README
根目录/
└── alembic.ini(Alembic 配置文件)
- 配置数据库连接
编辑 alembic.ini 文件:
# 找到这一行(约第63行)
sqlalchemy.url = driver://user:pass@localhost/dbname
# 修改为您的 MySQL 配置
sqlalchemy.url = mysql+pymysql://root:your_password@localhost:3306/xx
^^^^^^^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^ ^^^^ ^^^^^^^^^^
驱动类型 用户 密码 主机 端口 数据库名
- 创建迁移脚本
# 创建一个新的迁移
alembic revision -m "add xx and xx_writes tables"
这会生成
Database/migrations/versions/abc123def456_add_xx_and_xx_writes_tables.py
^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
版本号(自动) 您的描述信息
-
编写升级脚本
在 upgrade() 函数中添加: -
执行迁移
# 查看待执行的迁移
alembic current # 显示当前版本
alembic history # 显示所有迁移历史
# 执行迁移(升级到最新版本)
alembic upgrade head
# 输出:
# INFO [alembic.runtime.migration] Context impl MySQLImpl.
# INFO [alembic.runtime.migration] Will assume non-transactional DDL.
# INFO [alembic.runtime.migration] Running upgrade -> abc123def456, add xx table
1270

被折叠的 条评论
为什么被折叠?



