跳到主要内容

数据库与迁移

RadStudio 使用 SQLAlchemy 2.0 (async) 作为 ORM,Alembic 管理数据库迁移。

数据模型

模型定义在 apps/backend/app/models/ 目录:

apps/backend/app/models/
├── __init__.py
├── base.py # 基础模型类
├── user.py # 用户模型
├── project.py # 项目模型
├── dataset.py # 数据集模型
├── workflow.py # 工作流模型
├── task.py # 任务模型
├── node.py # 节点模型(多租户)
└── quota.py # 配额模型

模型示例

# apps/backend/app/models/project.py
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from app.models.base import Base

class Project(Base):
__tablename__ = "projects"

id = Column(Integer, primary_key=True)
name = Column(String(255), nullable=False)
description = Column(String(1000))
user_id = Column(Integer, ForeignKey("users.id"))
created_at = Column(DateTime, server_default="now()")

user = relationship("User", back_populates="projects")
datasets = relationship("Dataset", back_populates="project")

Alembic 迁移

创建迁移

cd apps/backend

# 自动生成迁移脚本
alembic revision --autogenerate -m "add_projects_table"

# 手动创建迁移脚本
alembic revision -m "manual_migration"

应用迁移

# 应用所有迁移
alembic upgrade head

# 回滚一个版本
alembic downgrade -1

# 查看当前版本
alembic current

# 查看迁移历史
alembic history

迁移最佳实践

  1. 总是检查自动生成的迁移 — Alembic 可能遗漏某些变更
  2. 添加数据迁移 — 需要迁移数据时使用 op.execute()
  3. 测试迁移 — 在测试数据库上验证迁移脚本
  4. 不要修改已提交的迁移 — 创建新的迁移脚本

连接配置

# apps/backend/app/core/config.py
class Settings(BaseSettings):
postgres_host: str = "postgres"
postgres_port: int = 5432
postgres_db: str = "radstudio"
postgres_user: str = "radstudio"
postgres_password: str = "change-me"

@property
def database_url(self) -> str:
return (
f"postgresql+asyncpg://{self.postgres_user}:{self.postgres_password}"
f"@{self.postgres_host}:{self.postgres_port}/{self.postgres_db}"
)

测试数据库

测试使用 SQLite(而非 PostgreSQL):

# conftest.py
TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"