dashboard-nanobot/design/database.md

2.9 KiB
Raw Blame History

Dashboard Nanobot 数据库设计文档

数据库默认使用 PostgreSQL推荐使用 psycopg3 驱动)。

1. ERD

erDiagram
    bot_instance ||--o{ bot_message : "messages"
    bot_instance ||--o{ bot_request_usage : "usage"
    bot_instance ||--o{ bot_activity_event : "events"
    bot_image ||--o{ bot_instance : "referenced by"

    bot_instance {
        string id PK
        string name
        boolean enabled
        string access_password
        string workspace_dir UK
        string docker_status
        string current_state
        string last_action
        string image_tag
        datetime created_at
        datetime updated_at
    }

    bot_message {
        int id PK
        string bot_id FK
        string role
        text text
        text media_json
        string feedback
        datetime feedback_at
        datetime created_at
    }

    bot_image {
        string tag PK
        string image_id
        string version
        string status
        string source_dir
        datetime created_at
    }

    bot_request_usage {
        int id PK
        string bot_id FK
        string request_id
        string channel
        string status
        string provider
        string model
        int input_tokens
        int output_tokens
        int total_tokens
        datetime started_at
        datetime completed_at
        datetime created_at
    }

    bot_activity_event {
        int id PK
        string bot_id FK
        string request_id
        string event_type
        string channel
        string detail
        text metadata_json
        datetime created_at
    }

    sys_setting {
        string key PK
        string name
        string category
        string description
        string value_type
        text value_json
        boolean is_public
        int sort_order
        datetime created_at
        datetime updated_at
    }

2. 设计原则

  • 数据库保留运行索引、历史消息、用量统计与运维事件。
  • Bot 核心配置渠道、资源配额、5 个 MD 文件)统一持久化在文件系统:
    • .nanobot/config.json
    • .nanobot/workspace/*.md
    • .nanobot/env.json

3. 表说明

3.1 bot_instance

存储 Bot 基础索引与运行态。

3.2 bot_message

Dashboard 渠道对话历史(用于会话回放与反馈)。

3.3 bot_image

基础镜像登记表。

3.4 bot_request_usage

模型调用用量详细记录。

3.5 bot_activity_event

运维事件记录(如容器启动/停止、指令提交、系统告警等)。

3.6 sys_setting

平台全局参数设置。

4. 初始化与迁移策略

服务启动时(backend/core/database.py

  1. 使用 PostgreSQL Advisory Lock 确保多节点部署时的单实例初始化。
  2. SQLModel.metadata.create_all(engine) 自动创建缺失表。
  3. 执行列对齐检查,确保旧表结构平滑升级。
  4. 自动对齐 PostgreSQL Sequences 以防 ID 冲突。