ai_config_repository.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package repository
  2. import (
  3. "github.com/2930134478/AI-CS/backend/models"
  4. "gorm.io/gorm"
  5. )
  6. // AIConfigRepository 封装与 AI 配置相关的数据库操作。
  7. type AIConfigRepository struct {
  8. db *gorm.DB
  9. }
  10. // NewAIConfigRepository 创建 AI 配置仓库实例。
  11. func NewAIConfigRepository(db *gorm.DB) *AIConfigRepository {
  12. return &AIConfigRepository{db: db}
  13. }
  14. // Create 创建新的 AI 配置记录。
  15. func (r *AIConfigRepository) Create(config *models.AIConfig) error {
  16. return r.db.Create(config).Error
  17. }
  18. // GetByID 根据主键查询 AI 配置。
  19. func (r *AIConfigRepository) GetByID(id uint) (*models.AIConfig, error) {
  20. var config models.AIConfig
  21. if err := r.db.First(&config, id).Error; err != nil {
  22. return nil, err
  23. }
  24. return &config, nil
  25. }
  26. // GetActiveByUserID 查询指定用户的活跃 AI 配置(按模型类型筛选)。
  27. func (r *AIConfigRepository) GetActiveByUserID(userID uint, modelType string) (*models.AIConfig, error) {
  28. var config models.AIConfig
  29. query := r.db.Where("user_id = ? AND is_active = ?", userID, true)
  30. if modelType != "" {
  31. query = query.Where("model_type = ?", modelType)
  32. }
  33. if err := query.Order("created_at desc").First(&config).Error; err != nil {
  34. return nil, err
  35. }
  36. return &config, nil
  37. }
  38. // ListByUserID 查询指定用户的所有 AI 配置。
  39. func (r *AIConfigRepository) ListByUserID(userID uint) ([]models.AIConfig, error) {
  40. var configs []models.AIConfig
  41. if err := r.db.Where("user_id = ?", userID).Order("created_at desc").Find(&configs).Error; err != nil {
  42. return nil, err
  43. }
  44. return configs, nil
  45. }
  46. // UpdateFields 更新 AI 配置的指定字段。
  47. func (r *AIConfigRepository) UpdateFields(id uint, values map[string]interface{}) error {
  48. if len(values) == 0 {
  49. return nil
  50. }
  51. return r.db.Model(&models.AIConfig{}).Where("id = ?", id).Updates(values).Error
  52. }
  53. // Delete 删除 AI 配置。
  54. func (r *AIConfigRepository) Delete(id uint) error {
  55. return r.db.Delete(&models.AIConfig{}, id).Error
  56. }
  57. // ListPublic 查询所有开放的模型配置(供访客选择)。
  58. func (r *AIConfigRepository) ListPublic(modelType string) ([]models.AIConfig, error) {
  59. var configs []models.AIConfig
  60. query := r.db.Where("is_active = ? AND is_public = ?", true, true)
  61. if modelType != "" {
  62. query = query.Where("model_type = ?", modelType)
  63. }
  64. if err := query.Order("provider, model").Find(&configs).Error; err != nil {
  65. return nil, err
  66. }
  67. return configs, nil
  68. }