feat(backend): add automatic DB migrations

Add a lightweight migration runner with schema_migrations tracking, run pending migrations during backend startup before the scheduler, and keep a manual backend-migrate entrypoint.

The change also moves the existing lockout and task-thread-ID schema steps into shared migration modules, updates docs, and archives the OpenSpec change.
This commit is contained in:
2026-05-05 01:36:58 +08:00
parent e243dccfd7
commit 3ab845798d
21 changed files with 911 additions and 145 deletions
+9 -1
View File
@@ -90,6 +90,14 @@ git pull
docker compose up -d --build
```
后端启动时会自动执行待迁移数据库脚本,并在迁移完成后才启动调度器。如果迁移失败,backend 服务会启动失败并在日志中标出失败的迁移 ID。
需要手动执行迁移时:
```bash
docker compose exec backend uv run python main.py backend-migrate
```
不要使用 `docker compose down -v`,否则会删除 Compose 管理的卷。当前默认使用项目目录 bind mount,仍应避免误删 `data/``sessions/``logs/`
### 备份与恢复
@@ -116,7 +124,7 @@ git checkout <previous-tag-or-commit>
docker compose up -d --build
```
回滚时复用同一份 `.env``data/``sessions/``logs/`如果未来版本引入数据库迁移,按对应版本说明先确认迁移是否可逆
回滚时复用同一份 `.env``data/``sessions/``logs/`回滚到旧版本前,先确认当前版本已经执行的数据库迁移是否可被旧版本兼容读取
### Compose 故障排查
+8 -4
View File
@@ -190,13 +190,17 @@ export const tagApi = {
### 数据库迁移
```bash
# 修改模型后生成迁移脚本
# 手动创建脚本在 apps/backend/scripts/migrate_*.py
# 后端启动时会在调度器启动前自动执行待迁移项。
# 执行迁移
uv run python apps/backend/scripts/migrate_xxx.py
# 如需手动执行全部待迁移
uv run python main.py backend-migrate
# 或直接调用脚本模块
uv run python -m backend.scripts.run_migrations
```
新增迁移时,将迁移函数注册到 `backend.migrations.MIGRATIONS`,并保持迁移逻辑幂等。迁移只有成功完成后才会写入 `schema_migrations`
### 测试
#### 后端测试