refactor(store): DB 规约统一 —— 雪花字符串 id + created/updated/deleted_at 软删
所有数据库映射结构体收敛到统一基类,清理混乱。
- store/base.go:BaseModel{ID string(雪花,bwmarrin/snowflake) PK, CreatedAt, UpdatedAt,
DeletedAt gorm软删index} + BeforeCreate 生成 id + NewID()。
- 全模型嵌入 BaseModel:User/Task/LLMModel/KB/Doc/Agent(去掉各自 ID uint/CreatedAt);
Task 业务 id(task_xxx)挪到 TaskID 唯一列,主键统一雪花。
- 模型 id uint→string:admin :id 路由、SetActiveModel/DeleteModel/SaveModel、modelBody.ID。
- 一次性迁移 migrateLegacyIntIDs:检测旧整型 id(AutoMigrate 不改主键类型)→ 备份
sundynix_model 行(唯一不可再生的 API 密钥)→ 删旧表 → 按新规约重建 → 回灌模型(新雪花 id)。
其它表(User/Task/KB/Doc/Agent)为可重建测试数据,重置。
- Doc 预埋 Size/Preview/ObjectKey 字段,DocLink 表(为后续 B/C)。
验证:重启 gateway → 日志"回灌 2 条模型配置";PG sundynix_model.id=varchar、有
created_at/updated_at/deleted_at;DeepSeek/百炼 密钥保留(keylen 35);admin 列表返回
雪花 string id + 脱敏 key;健康五灯全绿。gateway build 通过。
注:mcp-go 的 sundynix_user_profile(Profile) 模型尚未套同规约,待跟进对齐。
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -5,7 +5,6 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -18,7 +17,7 @@ import (
|
||||
// 表 sundynix_model 由 Gateway 持有;Dispatcher 经 NATS 取激活配置。
|
||||
|
||||
type modelBody struct {
|
||||
ID uint `json:"id"`
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Provider string `json:"provider"`
|
||||
BaseURL string `json:"base_url"`
|
||||
@@ -58,7 +57,7 @@ func (h *Handler) SaveModel(c *gin.Context) {
|
||||
if kind == "" {
|
||||
kind = contract.ConfigKindChat
|
||||
}
|
||||
m := &store.LLMModel{ID: b.ID, Kind: kind, Provider: provider, BaseURL: b.BaseURL, APIKey: b.APIKey, Model: b.Model}
|
||||
m := &store.LLMModel{BaseModel: store.BaseModel{ID: b.ID}, Kind: kind, Provider: provider, BaseURL: b.BaseURL, APIKey: b.APIKey, Model: b.Model}
|
||||
if err := h.db.SaveModel(c.Request.Context(), m); err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -69,8 +68,8 @@ func (h *Handler) SaveModel(c *gin.Context) {
|
||||
|
||||
// SetActiveModel: POST /api/v1/admin/models/:id/active —— 设为激活并广播。
|
||||
func (h *Handler) SetActiveModel(c *gin.Context) {
|
||||
id, _ := strconv.Atoi(c.Param("id"))
|
||||
if err := h.db.SetActiveModel(c.Request.Context(), uint(id)); err != nil {
|
||||
id := c.Param("id")
|
||||
if err := h.db.SetActiveModel(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -80,8 +79,8 @@ func (h *Handler) SetActiveModel(c *gin.Context) {
|
||||
|
||||
// DeleteModel: DELETE /api/v1/admin/models/:id
|
||||
func (h *Handler) DeleteModel(c *gin.Context) {
|
||||
id, _ := strconv.Atoi(c.Param("id"))
|
||||
if err := h.db.DeleteModel(c.Request.Context(), uint(id)); err != nil {
|
||||
id := c.Param("id")
|
||||
if err := h.db.DeleteModel(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -98,7 +97,7 @@ func (h *Handler) TestModel(c *gin.Context) {
|
||||
}
|
||||
// 若传了已存的 id 但未带 key,用库里的真实 key。
|
||||
key := b.APIKey
|
||||
if key == "" && b.ID != 0 {
|
||||
if key == "" && b.ID != "" {
|
||||
if rows, _ := h.db.ListModels(c.Request.Context(), ""); rows != nil {
|
||||
for _, m := range rows {
|
||||
if m.ID == b.ID {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/bwmarrin/snowflake"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 雪花 ID 生成器(单节点;多实例部署应按机器分配 node id)。
|
||||
var sfNode *snowflake.Node
|
||||
|
||||
func init() {
|
||||
n, err := snowflake.NewNode(1)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
sfNode = n
|
||||
}
|
||||
|
||||
// NewID 生成字符串型雪花 ID(全库主键统一用它)。
|
||||
func NewID() string { return sfNode.Generate().String() }
|
||||
|
||||
// BaseModel 是所有数据库映射结构体的基础字段:
|
||||
// 字符串雪花主键 + 创建/更新时间 + GORM 软删除索引(deleted_at)。
|
||||
// 约定:每个模型都嵌入它,不再各自声明 ID/CreatedAt/UpdatedAt。
|
||||
type BaseModel struct {
|
||||
ID string `gorm:"primaryKey;size:24" json:"id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
|
||||
// BeforeCreate 为空 ID 的新记录分配雪花 ID(嵌入后各模型自动具备)。
|
||||
func (b *BaseModel) BeforeCreate(*gorm.DB) error {
|
||||
if b.ID == "" {
|
||||
b.ID = NewID()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -12,11 +12,10 @@ import (
|
||||
// 表名 sundynix_kb。(owner,name) 唯一 —— 同一用户下知识库名不重复。
|
||||
// 向量/全文/图谱实际以 "owner/name" 作分区键,保证只有 owner 能查到自己的库。
|
||||
type KB struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
Owner string `gorm:"size:64;uniqueIndex:idx_kb_owner_name"`
|
||||
Name string `gorm:"size:64;uniqueIndex:idx_kb_owner_name"`
|
||||
Kind string `gorm:"size:16"` // folder / project / case / general
|
||||
CreatedAt time.Time
|
||||
BaseModel
|
||||
Owner string `gorm:"size:64;uniqueIndex:idx_kb_owner_name"`
|
||||
Name string `gorm:"size:64;uniqueIndex:idx_kb_owner_name"`
|
||||
Kind string `gorm:"size:16"` // folder / project / case / general
|
||||
}
|
||||
|
||||
func (KB) TableName() string { return "sundynix_kb" }
|
||||
@@ -48,11 +47,10 @@ func (p *Postgres) EnsureKB(ctx context.Context, owner, name, kind string) error
|
||||
// Agent 是一份保存的 Agent 编排(React Flow 图 JSON,按 owner 隔离)。
|
||||
// 表名 sundynix_agent。(owner,name) 唯一 —— 同一用户下编排名不重复。
|
||||
type Agent struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
Owner string `gorm:"size:64;uniqueIndex:idx_agent_on"`
|
||||
Name string `gorm:"size:128;uniqueIndex:idx_agent_on"`
|
||||
Graph string `gorm:"type:text"` // {nodes,edges} 的 JSON(含布局)
|
||||
UpdatedAt time.Time
|
||||
BaseModel
|
||||
Owner string `gorm:"size:64;uniqueIndex:idx_agent_on"`
|
||||
Name string `gorm:"size:128;uniqueIndex:idx_agent_on"`
|
||||
Graph string `gorm:"type:text"` // {nodes,edges} 的 JSON(含布局)
|
||||
}
|
||||
|
||||
func (Agent) TableName() string { return "sundynix_agent" }
|
||||
@@ -75,7 +73,7 @@ func (p *Postgres) SaveAgent(ctx context.Context, owner, name, graph string) err
|
||||
return p.db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "owner"}, {Name: "name"}},
|
||||
DoUpdates: clause.Assignments(map[string]any{"graph": graph, "updated_at": time.Now()}),
|
||||
}).Create(&Agent{Owner: owner, Name: name, Graph: graph, UpdatedAt: time.Now()}).Error
|
||||
}).Create(&Agent{Owner: owner, Name: name, Graph: graph}).Error
|
||||
}
|
||||
|
||||
// DeleteAgent 删除某 owner 的一份编排。
|
||||
@@ -89,16 +87,30 @@ func (p *Postgres) DeleteAgent(ctx context.Context, owner, name string) error {
|
||||
// Doc 是入库的一份原始文档/笔记(供 Obsidian 式"文库"浏览:列表 + Markdown 阅读 + 双链)。
|
||||
// 表名 sundynix_doc。(owner,kb,name) 唯一;按 owner 隔离。
|
||||
type Doc struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
BaseModel
|
||||
Owner string `gorm:"size:64;uniqueIndex:idx_doc_okn"`
|
||||
KB string `gorm:"size:64;uniqueIndex:idx_doc_okn"`
|
||||
Name string `gorm:"size:160;uniqueIndex:idx_doc_okn"`
|
||||
Content string `gorm:"type:text"`
|
||||
CreatedAt time.Time
|
||||
Size int // 原文字数(rune)
|
||||
Preview string `gorm:"size:600"` // 前若干字预览(列表/反链用,不拉全文)
|
||||
Content string `gorm:"type:text"` // 小文档内联正文;大文档转 MinIO 后置空
|
||||
ObjectKey string `gorm:"size:160"` // 大文档在 MinIO 的对象键(空=内联 Content)
|
||||
}
|
||||
|
||||
func (Doc) TableName() string { return "sundynix_doc" }
|
||||
|
||||
// DocLink 是文档间 [[双链]] 的索引(owner+kb 内 from→to),供反链/笔记关系图按 SQL 查询,
|
||||
// 避免在前端扫全部正文。入库/编辑时按 from 文档重建其出链。
|
||||
type DocLink struct {
|
||||
BaseModel
|
||||
Owner string `gorm:"size:64;index:idx_link_okf"`
|
||||
KB string `gorm:"size:64;index:idx_link_okf"`
|
||||
FromName string `gorm:"size:160;index:idx_link_okf"`
|
||||
ToName string `gorm:"size:160;index"`
|
||||
}
|
||||
|
||||
func (DocLink) TableName() string { return "sundynix_doc_link" }
|
||||
|
||||
// SaveDoc 写入/更新一份文档(owner+kb+name 唯一,重名覆盖内容)。
|
||||
func (p *Postgres) SaveDoc(ctx context.Context, owner, kb, name, content string) error {
|
||||
if p.db == nil {
|
||||
@@ -123,7 +135,7 @@ func (p *Postgres) ListVault(ctx context.Context, owner, kb string) ([]Doc, erro
|
||||
// LLMModel 是一个模型后端配置(控制面:管理员在此登记可用模型)。
|
||||
// 表名 sundynix_model(遵守前缀约定)。每个 kind 同一时刻仅一条 Active=true。
|
||||
type LLMModel struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
BaseModel
|
||||
Kind string `gorm:"size:16;index"` // chat / embedding
|
||||
Provider string `gorm:"size:32"` // openai-compatible / vllm
|
||||
BaseURL string `gorm:"size:255"` // 如 https://api.deepseek.com
|
||||
@@ -148,22 +160,25 @@ func (p *Postgres) ListModels(ctx context.Context, kind string) ([]LLMModel, err
|
||||
return rows, err
|
||||
}
|
||||
|
||||
// SaveModel 新增或更新一条模型配置(ID==0 新增)。
|
||||
// SaveModel 新增或更新一条模型配置(ID 空则新增,BeforeCreate 生成雪花 ID)。
|
||||
func (p *Postgres) SaveModel(ctx context.Context, m *LLMModel) error {
|
||||
if p.db == nil {
|
||||
return errStoreDisabled
|
||||
}
|
||||
if m.ID == "" {
|
||||
return p.db.WithContext(ctx).Create(m).Error
|
||||
}
|
||||
return p.db.WithContext(ctx).Save(m).Error
|
||||
}
|
||||
|
||||
// SetActiveModel 把指定模型设为激活(同 kind 内其余取消),事务保证每 kind 唯一激活。
|
||||
func (p *Postgres) SetActiveModel(ctx context.Context, id uint) error {
|
||||
func (p *Postgres) SetActiveModel(ctx context.Context, id string) error {
|
||||
if p.db == nil {
|
||||
return errStoreDisabled
|
||||
}
|
||||
return p.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var m LLMModel
|
||||
if err := tx.First(&m, id).Error; err != nil {
|
||||
if err := tx.First(&m, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&LLMModel{}).Where("kind = ? AND active = ?", m.Kind, true).Update("active", false).Error; err != nil {
|
||||
@@ -187,9 +202,9 @@ func (p *Postgres) GetActiveModel(ctx context.Context, kind string) (*LLMModel,
|
||||
}
|
||||
|
||||
// DeleteModel 删除一条模型配置。
|
||||
func (p *Postgres) DeleteModel(ctx context.Context, id uint) error {
|
||||
func (p *Postgres) DeleteModel(ctx context.Context, id string) error {
|
||||
if p.db == nil {
|
||||
return errStoreDisabled
|
||||
}
|
||||
return p.db.WithContext(ctx).Delete(&LLMModel{}, id).Error
|
||||
return p.db.WithContext(ctx).Delete(&LLMModel{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
package store
|
||||
|
||||
import "time"
|
||||
|
||||
// 数据库映射模型。表名经 GORM NamingStrategy 统一加 sundynix_ 前缀 + 单数:
|
||||
// User → sundynix_user,Task → sundynix_task。
|
||||
// 约定:均嵌入 BaseModel(雪花字符串 id + created_at/updated_at + 软删 deleted_at);
|
||||
// 建表/改表一律走 AutoMigrate,不手写 DDL。
|
||||
|
||||
// User 是平台用户(Users)。
|
||||
type User struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
Email string `gorm:"uniqueIndex;size:255"`
|
||||
CreatedAt time.Time
|
||||
BaseModel
|
||||
Email string `gorm:"uniqueIndex;size:255"`
|
||||
}
|
||||
|
||||
// Task 是一次提交的 Agent 编排任务(DSL)。
|
||||
// 业务 id(task_xxx,用于 NATS subject/stream)单列 TaskID,主键统一雪花。
|
||||
type Task struct {
|
||||
ID string `gorm:"primaryKey;size:64"` // task_xxx
|
||||
Graph string `gorm:"type:jsonb"` // React Flow 导出的 DSL 原文
|
||||
Status string `gorm:"size:32"` // submitted / done / failed
|
||||
CreatedAt time.Time
|
||||
BaseModel
|
||||
TaskID string `gorm:"uniqueIndex;size:64"` // task_xxx
|
||||
Graph string `gorm:"type:jsonb"` // React Flow 导出的 DSL 原文
|
||||
Status string `gorm:"size:32"` // submitted / done / failed
|
||||
}
|
||||
|
||||
@@ -34,16 +34,43 @@ func OpenPostgres(dsn string) *Postgres {
|
||||
log.Printf("[store] postgres 不可用,降级运行(不持久化): %v", err)
|
||||
return &Postgres{}
|
||||
}
|
||||
if err := db.AutoMigrate(&User{}, &Task{}, &LLMModel{}, &KB{}, &Doc{}, &Agent{}); err != nil {
|
||||
// 一次性迁移:旧表用整型自增 id,与新雪花字符串 id 不兼容(AutoMigrate 不改主键类型)。
|
||||
// 备份模型密钥(唯一不可再生的数据) → 重建全部表 → 回灌模型。其余为可重建的测试数据。
|
||||
migrateLegacyIntIDs(db)
|
||||
|
||||
if err := db.AutoMigrate(&User{}, &Task{}, &LLMModel{}, &KB{}, &Doc{}, &Agent{}, &DocLink{}); err != nil {
|
||||
log.Printf("[store] postgres AutoMigrate 失败,降级运行: %v", err)
|
||||
return &Postgres{}
|
||||
}
|
||||
// 回填:kind 列新增前的旧模型行默认归为 chat(幂等)。
|
||||
db.Model(&LLMModel{}).Where("kind = '' OR kind IS NULL").Update("kind", "chat")
|
||||
log.Println("[store] postgres connected, migrated sundynix_user / sundynix_task")
|
||||
log.Println("[store] postgres connected & migrated (雪花 id + 软删 规约)")
|
||||
return &Postgres{db: db}
|
||||
}
|
||||
|
||||
// migrateLegacyIntIDs 检测到旧整型 id 表则备份模型密钥、删旧表(AutoMigrate 随后按新规约重建)。
|
||||
func migrateLegacyIntIDs(db *gorm.DB) {
|
||||
var dt string
|
||||
db.Raw(`SELECT data_type FROM information_schema.columns WHERE table_name='sundynix_model' AND column_name='id'`).Scan(&dt)
|
||||
if dt != "bigint" && dt != "integer" {
|
||||
return // 全新库或已是新规约
|
||||
}
|
||||
log.Println("[store] 检测到旧整型 id 表,执行雪花 id 迁移(保模型密钥,重置其它测试表)")
|
||||
var saved []map[string]any
|
||||
db.Table("sundynix_model").Find(&saved)
|
||||
for _, t := range []string{"sundynix_doc_link", "sundynix_doc", "sundynix_agent", "sundynix_kb", "sundynix_model", "sundynix_task", "sundynix_user"} {
|
||||
db.Exec("DROP TABLE IF EXISTS " + t + " CASCADE")
|
||||
}
|
||||
_ = db.AutoMigrate(&LLMModel{}) // 先建模型表以回灌
|
||||
for _, r := range saved {
|
||||
s := func(k string) string { v, _ := r[k].(string); return v }
|
||||
b, _ := r["active"].(bool)
|
||||
_ = db.Create(&LLMModel{
|
||||
Kind: s("kind"), Provider: s("provider"), BaseURL: s("base_url"),
|
||||
APIKey: s("api_key"), Model: s("model"), Active: b,
|
||||
}).Error
|
||||
}
|
||||
log.Printf("[store] 已回灌 %d 条模型配置(新雪花 id)", len(saved))
|
||||
}
|
||||
|
||||
// Enabled 报告是否处于真实持久化模式。
|
||||
func (p *Postgres) Enabled() bool { return p.db != nil }
|
||||
|
||||
@@ -52,7 +79,7 @@ func (p *Postgres) SaveTask(ctx context.Context, id, graph string) error {
|
||||
if p.db == nil {
|
||||
return nil
|
||||
}
|
||||
return p.db.WithContext(ctx).Create(&Task{ID: id, Graph: graph, Status: "submitted"}).Error
|
||||
return p.db.WithContext(ctx).Create(&Task{TaskID: id, Graph: graph, Status: "submitted"}).Error
|
||||
}
|
||||
|
||||
// CountTasks 返回已提交任务数(降级模式返回 0)。
|
||||
|
||||
Reference in New Issue
Block a user