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

@@ -16,6 +16,8 @@ var (
type AccountRepository interface {
Create(ctx context.Context, account *Account) error
GetByID(ctx context.Context, id int64) (*Account, error)
// ExistsByID 检查账号是否存在,仅返回布尔值,用于删除前的轻量级存在性检查
ExistsByID(ctx context.Context, id int64) (bool, error)
// GetByCRSAccountID finds an account previously synced from CRS.
// Returns (nil, nil) if not found.
GetByCRSAccountID(ctx context.Context, crsAccountID string) (*Account, error)
@@ -235,11 +237,17 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount
}
// Delete 删除账号
// 优化:使用 ExistsByID 替代 GetByID 进行存在性检查,
// 避免加载完整账号对象及其关联数据,提升删除操作的性能
func (s *AccountService) Delete(ctx context.Context, id int64) error {
// 检查账号是否存在
_, err := s.accountRepo.GetByID(ctx, id)
// 使用轻量级的存在性检查,而非加载完整账号对象
exists, err := s.accountRepo.ExistsByID(ctx, id)
if err != nil {
return fmt.Errorf("get account: %w", err)
return fmt.Errorf("check account: %w", err)
}
// 明确返回账号不存在错误,便于调用方区分错误类型
if !exists {
return ErrAccountNotFound
}
if err := s.accountRepo.Delete(ctx, id); err != nil {