dashboard-nanobot/design/database.md

3.1 KiB
Raw Permalink 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. 初始化与迁移策略

数据库初始化改为离线显式执行:

  1. scripts/sql/create-tables.sql 负责创建业务表和索引。
  2. scripts/sql/init-data.sql 负责初始化 sys_setting 和默认 skill_market_item 数据。
  3. scripts/init-full-db.sh 在完整部署场景下会按顺序执行 PostgreSQL 引导 SQL、建表 SQL、初始化数据 SQL。
  4. 后端启动时(backend/core/database.py)只校验必需表和核心 sys_setting 是否已经存在;若缺失则直接中止启动,不再做运行时迁移或结构修复。