79 lines
2.0 KiB
Markdown
79 lines
2.0 KiB
Markdown
# 数据库迁移
|
||
|
||
本目录包含数据库迁移相关的脚本和配置。
|
||
|
||
## 目录结构
|
||
|
||
- `alembic.ini`: Alembic 配置文件
|
||
- `env.py`: Alembic 环境配置
|
||
- `script.py.mako`: 迁移脚本模板
|
||
- `versions/`: 迁移脚本目录
|
||
|
||
## 使用方法
|
||
|
||
### 安装依赖
|
||
|
||
```bash
|
||
pip install alembic
|
||
```
|
||
|
||
### 生成迁移脚本
|
||
|
||
使用通用迁移脚本生成工具生成迁移脚本:
|
||
|
||
```bash
|
||
python scripts/generate_migration.py --table 表名 --field 字段名 --type 字段类型 [--nullable] [--default 默认值] [--comment 注释] [--unique] [--index]
|
||
```
|
||
|
||
参数说明:
|
||
|
||
- `--table`: 表名,必填
|
||
- `--field`: 字段名,必填
|
||
- `--type`: 字段类型,如 String(36), Integer, Boolean 等,必填
|
||
- `--nullable`: 是否可为空,默认为 False
|
||
- `--default`: 默认值
|
||
- `--comment`: 注释
|
||
- `--unique`: 是否唯一,默认为 False
|
||
- `--index`: 是否创建索引,默认为 False
|
||
|
||
示例:
|
||
|
||
```bash
|
||
# 添加 task_id 字段到 tasks 表
|
||
python scripts/generate_migration.py --table tasks --field task_id --type String(36) --comment "任务UUID,用于外部引用" --unique --index
|
||
|
||
# 添加 is_active 字段到 users 表
|
||
python scripts/generate_migration.py --table users --field is_active --type Boolean --default "true" --comment "是否激活" --index
|
||
```
|
||
|
||
### 执行迁移
|
||
|
||
使用迁移执行脚本执行迁移:
|
||
|
||
```bash
|
||
python scripts/run_migration.py [--revision 版本号] [--downgrade]
|
||
```
|
||
|
||
参数说明:
|
||
|
||
- `--revision`: 版本号,为空表示升级到最新版本
|
||
- `--downgrade`: 是否降级,默认为 False
|
||
|
||
示例:
|
||
|
||
```bash
|
||
# 升级到最新版本
|
||
python scripts/run_migration.py
|
||
|
||
# 升级到指定版本
|
||
python scripts/run_migration.py --revision 001
|
||
|
||
# 降级到指定版本
|
||
python scripts/run_migration.py --revision 001 --downgrade
|
||
```
|
||
|
||
## 注意事项
|
||
|
||
1. 迁移脚本会自动为已有记录生成默认值,但可能需要根据实际情况修改。
|
||
2. 执行迁移前,请确保已备份数据库。
|
||
3. 降级操作可能会导致数据丢失,请谨慎使用。 |