- 使用 GORM clause.OnConflict 替代事务包装 - Record 和 BatchUpdate 方法改用 upsert 模式 - 修复 UsageStats 的 GORM struct tag,确保 AutoMigrate 创建正确的 UNIQUE 约束 - 更新 usage-statistics spec 以反映 upsert 操作 MySQL 并发测试验证:10 并发调用 → request_count = 10
51 lines
1.8 KiB
Go
51 lines
1.8 KiB
Go
package config
|
||
|
||
import (
|
||
"time"
|
||
)
|
||
|
||
// Provider 供应商模型
|
||
type Provider struct {
|
||
ID string `gorm:"primaryKey" json:"id"`
|
||
Name string `gorm:"not null" json:"name"`
|
||
APIKey string `gorm:"not null" json:"api_key"`
|
||
BaseURL string `gorm:"not null" json:"base_url"`
|
||
Protocol string `gorm:"column:protocol;default:'openai'" json:"protocol"`
|
||
Enabled bool `gorm:"default:true" json:"enabled"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
UpdatedAt time.Time `json:"updated_at"`
|
||
Models []Model `gorm:"foreignKey:ProviderID;constraint:OnDelete:CASCADE" json:"models,omitempty"`
|
||
}
|
||
|
||
// Model 模型配置(id 为 UUID 自动生成,UNIQUE(provider_id, model_name))
|
||
type Model struct {
|
||
ID string `gorm:"primaryKey" json:"id"`
|
||
ProviderID string `gorm:"not null;index;uniqueIndex:idx_provider_model" json:"provider_id"`
|
||
ModelName string `gorm:"not null;index;uniqueIndex:idx_provider_model" json:"model_name"`
|
||
Enabled bool `gorm:"default:true" json:"enabled"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
}
|
||
|
||
// UsageStats 用量统计
|
||
type UsageStats struct {
|
||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||
ProviderID string `gorm:"not null;index;uniqueIndex:idx_provider_model_date" json:"provider_id"`
|
||
ModelName string `gorm:"not null;index;uniqueIndex:idx_provider_model_date" json:"model_name"`
|
||
RequestCount int `gorm:"default:0" json:"request_count"`
|
||
Date time.Time `gorm:"type:date;not null;uniqueIndex:idx_provider_model_date" json:"date"`
|
||
}
|
||
|
||
// TableName 指定表名
|
||
func (Provider) TableName() string {
|
||
return "providers"
|
||
}
|
||
|
||
func (Model) TableName() string {
|
||
return "models"
|
||
}
|
||
|
||
func (UsageStats) TableName() string {
|
||
return "usage_stats"
|
||
}
|
||
|