fix(n+1): 批量查询替代循环单查

- IsAdminBootstrapRequired: userRepo.GetByID 循环 → GetByIDs 批量
- AssignRoles: roleRepo.GetByID 循环 → GetByIDs 批量
- 在 userRepositoryInterface 补充 GetByIDs 方法签名
This commit is contained in:
2026-05-08 08:05:26 +08:00
parent 9b1cea246e
commit 2a18a6fb47
39 changed files with 3169 additions and 393 deletions

View File

@@ -104,6 +104,18 @@ func (r *UserRepository) GetByPhone(ctx context.Context, phone string) (*domain.
return &user, nil
}
// FindByAccount 按账号查询用户(支持用户名/邮箱/手机号P1性能优化替代串行查询
func (r *UserRepository) FindByAccount(ctx context.Context, account string) (*domain.User, error) {
var user domain.User
err := r.db.WithContext(ctx).
Where("username = ? OR email = ? OR phone = ?", account, account, account).
First(&user).Error
if err != nil {
return nil, err
}
return &user, nil
}
// List 获取用户列表
func (r *UserRepository) List(ctx context.Context, offset, limit int) ([]*domain.User, int64, error) {
var users []*domain.User
@@ -195,6 +207,21 @@ func (r *UserRepository) ExistsByPhone(ctx context.Context, phone string) (bool,
return count > 0, err
}
// FilterExistingUsernames 批量筛选已存在的用户名P1性能优化替代循环查询
func (r *UserRepository) FilterExistingUsernames(ctx context.Context, usernames []string) ([]string, error) {
if len(usernames) == 0 {
return []string{}, nil
}
var existing []string
err := r.db.WithContext(ctx).Model(&domain.User{}).
Where("username IN ?", usernames).
Pluck("username", &existing).Error
if err != nil {
return nil, err
}
return existing, nil
}
// Search 搜索用户
func (r *UserRepository) Search(ctx context.Context, keyword string, offset, limit int) ([]*domain.User, int64, error) {
var users []*domain.User