perf(后端): 优化删除操作的数据库查询性能

- 新增 ExistsByID 方法用于账号存在性检查,避免加载完整对象
- 新增 GetOwnerID 方法用于 API Key 所有权验证,仅查询 user_id 字段
- 优化 AccountService.Delete 使用轻量级存在性检查
- 优化 ApiKeyService.Delete 使用轻量级权限验证
- 改进前端删除错误提示,显示后端返回的具体错误消息
- 添加详细的中文注释说明优化原因

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
yangjianbo
2025-12-29 14:06:38 +08:00
parent 89b1b744f2
commit e9c755f428
5 changed files with 62 additions and 10 deletions

View File

@@ -128,6 +128,19 @@ func (r *accountRepository) GetByID(ctx context.Context, id int64) (*service.Acc
return &accounts[0], nil
}
// ExistsByID 检查指定 ID 的账号是否存在。
// 相比 GetByID此方法性能更优因为
// - 使用 Exist() 方法生成 SELECT EXISTS 查询,只返回布尔值
// - 不加载完整的账号实体及其关联数据Groups、Proxy 等)
// - 适用于删除前的存在性检查等只需判断有无的场景
func (r *accountRepository) ExistsByID(ctx context.Context, id int64) (bool, error) {
exists, err := r.client.Account.Query().Where(dbaccount.IDEQ(id)).Exist(ctx)
if err != nil {
return false, err
}
return exists, nil
}
func (r *accountRepository) GetByCRSAccountID(ctx context.Context, crsAccountID string) (*service.Account, error) {
if crsAccountID == "" {
return nil, nil

View File

@@ -49,6 +49,25 @@ func (r *apiKeyRepository) GetByID(ctx context.Context, id int64) (*service.ApiK
return apiKeyEntityToService(m), nil
}
// GetOwnerID 根据 API Key ID 获取其所有者(用户)的 ID。
// 相比 GetByID此方法性能更优因为
// - 使用 Select() 只查询 user_id 字段,减少数据传输量
// - 不加载完整的 ApiKey 实体及其关联数据User、Group 等)
// - 适用于权限验证等只需用户 ID 的场景(如删除前的所有权检查)
func (r *apiKeyRepository) GetOwnerID(ctx context.Context, id int64) (int64, error) {
m, err := r.client.ApiKey.Query().
Where(apikey.IDEQ(id)).
Select(apikey.FieldUserID).
Only(ctx)
if err != nil {
if dbent.IsNotFound(err) {
return 0, service.ErrApiKeyNotFound
}
return 0, err
}
return m.UserID, nil
}
func (r *apiKeyRepository) GetByKey(ctx context.Context, key string) (*service.ApiKey, error) {
m, err := r.client.ApiKey.Query().
Where(apikey.KeyEQ(key)).