adabf8e089
- Added a new API for managing data sources, including CRUD operations and connection validation. - Introduced UI components for data source settings, sync logs, and editor dialog, enhancing user experience in managing external data sources. - Updated localization files to support new data source features in multiple languages. - Implemented cron expression humanization for better scheduling visibility. - Enhanced knowledge base editor to include data source management options.
144 lines
4.5 KiB
Go
144 lines
4.5 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
|
"github.com/Tencent/WeKnora/internal/utils"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
var (
|
|
ErrTenantNotFound = errors.New("tenant not found")
|
|
ErrTenantHasKnowledgeBase = errors.New("tenant has associated knowledge bases")
|
|
)
|
|
|
|
// tenantRepository implements tenant repository interface
|
|
type tenantRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewTenantRepository creates a new tenant repository
|
|
func NewTenantRepository(db *gorm.DB) interfaces.TenantRepository {
|
|
return &tenantRepository{db: db}
|
|
}
|
|
|
|
// CreateTenant creates tenant
|
|
func (r *tenantRepository) CreateTenant(ctx context.Context, tenant *types.Tenant) error {
|
|
return r.db.WithContext(ctx).Create(tenant).Error
|
|
}
|
|
|
|
// GetTenantByID gets tenant by ID
|
|
func (r *tenantRepository) GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) {
|
|
var tenant types.Tenant
|
|
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&tenant).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, ErrTenantNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
return &tenant, nil
|
|
}
|
|
|
|
// ListTenants lists all tenants
|
|
func (r *tenantRepository) ListTenants(ctx context.Context) ([]*types.Tenant, error) {
|
|
var tenants []*types.Tenant
|
|
if err := r.db.WithContext(ctx).Order("created_at DESC").Find(&tenants).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return tenants, nil
|
|
}
|
|
|
|
// SearchTenants searches tenants with pagination and filters
|
|
func (r *tenantRepository) SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]*types.Tenant, int64, error) {
|
|
var tenants []*types.Tenant
|
|
var total int64
|
|
|
|
query := r.db.WithContext(ctx).Model(&types.Tenant{})
|
|
|
|
// Build search conditions
|
|
if tenantID > 0 && keyword != "" {
|
|
escaped := escapeLikeKeyword(keyword)
|
|
query = query.Where("id = ? OR name LIKE ? OR description LIKE ?", tenantID, "%"+escaped+"%", "%"+escaped+"%")
|
|
} else if tenantID > 0 {
|
|
query = query.Where("id = ?", tenantID)
|
|
} else if keyword != "" {
|
|
escaped := escapeLikeKeyword(keyword)
|
|
query = query.Where("name LIKE ? OR description LIKE ?", "%"+escaped+"%", "%"+escaped+"%")
|
|
}
|
|
|
|
// Count total
|
|
if err := query.Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
// Apply pagination
|
|
if page > 0 && pageSize > 0 {
|
|
offset := (page - 1) * pageSize
|
|
query = query.Offset(offset).Limit(pageSize)
|
|
}
|
|
|
|
// Order by created_at DESC
|
|
query = query.Order("created_at DESC")
|
|
|
|
// Execute query
|
|
if err := query.Find(&tenants).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
return tenants, total, nil
|
|
}
|
|
|
|
// UpdateTenant updates tenant.
|
|
// Handles api_key carefully because db.Updates() does not trigger the BeforeSave
|
|
// GORM hook. Without this guard, AfterFind-decrypted plaintext would silently
|
|
// overwrite the encrypted value in the database.
|
|
//
|
|
// Strategy:
|
|
// - enc:v1:… (pre-encrypted by CreateTenant / UpdateAPIKey): write as-is.
|
|
// - plaintext (decrypted by AfterFind): blank it so GORM skips the column.
|
|
// - SYSTEM_AES_KEY not set: write as-is (encryption disabled).
|
|
//
|
|
// The caller's in-memory struct is always restored after the write.
|
|
func (r *tenantRepository) UpdateTenant(ctx context.Context, tenant *types.Tenant) error {
|
|
origAPIKey := tenant.APIKey
|
|
if key := utils.GetAESKey(); key != nil && tenant.APIKey != "" &&
|
|
!strings.HasPrefix(tenant.APIKey, utils.EncPrefix) {
|
|
// Plaintext from AfterFind — do not write back; let the DB keep its
|
|
// existing encrypted value untouched.
|
|
tenant.APIKey = ""
|
|
}
|
|
err := r.db.WithContext(ctx).Model(&types.Tenant{}).Where("id = ?", tenant.ID).Updates(tenant).Error
|
|
tenant.APIKey = origAPIKey
|
|
return err
|
|
}
|
|
|
|
// DeleteTenant deletes tenant
|
|
func (r *tenantRepository) DeleteTenant(ctx context.Context, id uint64) error {
|
|
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.Tenant{}).Error
|
|
}
|
|
|
|
func (r *tenantRepository) AdjustStorageUsed(ctx context.Context, tenantID uint64, delta int64) error {
|
|
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
var tenant types.Tenant
|
|
// 使用悲观锁确保并发安全
|
|
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&tenant, tenantID).Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
tenant.StorageUsed += delta
|
|
// 保存更新并验证业务规则
|
|
if tenant.StorageUsed < 0 {
|
|
logger.Errorf(ctx, "tenant storage used is negative %d: %d", tenant.ID, tenant.StorageUsed)
|
|
tenant.StorageUsed = 0
|
|
}
|
|
|
|
return tx.Save(&tenant).Error
|
|
})
|
|
}
|