feat(repository): enhance repository methods with batch processing and transaction support
All checks were successful
Build Backend / build (push) Successful in 12m50s
Build Backend / build-docker (push) Successful in 2m57s

- Updated Like and Unlike methods in CommentRepository to use transactions for data consistency.
- Introduced IsLikedBatch method for batch checking if comments are liked, addressing N+1 query issues.
- Enhanced BatchDelete method in PostRepository to perform batch deletions within a single transaction, improving efficiency.
- Added BatchUpdateStatus method for posts to utilize a single SQL update for status changes, reducing database load.
- Implemented BatchUpdateSortOrder in StickerRepository using CASE WHEN for efficient sorting updates.
- Added IsFollowingBatch and IsBlockedBatch methods in UserRepository for batch checking follow and block relationships, optimizing performance.
This commit is contained in:
lafay
2026-03-26 01:50:54 +08:00
parent 56bd971e42
commit 7b41dfeb00
9 changed files with 386 additions and 109 deletions

View File

@@ -107,7 +107,7 @@ func (r *LoginLogRepository) DeleteOldLogs(ctx context.Context, beforeDate strin
return r.db.WithContext(ctx).Where("created_at < ?", beforeDate).Delete(&model.LoginLog{}).Error
}
// GetStatistics 获取登录日志统计
// GetStatistics 获取登录日志统计(使用单次 GROUP BY 查询,避免多次 COUNT
func (r *LoginLogRepository) GetStatistics(ctx context.Context, startTime, endTime string) (*LoginLogStatistics, error) {
stats := &LoginLogStatistics{}
@@ -119,20 +119,37 @@ func (r *LoginLogRepository) GetStatistics(ctx context.Context, startTime, endTi
query = query.Where("created_at <= ?", endTime)
}
if err := query.Count(&stats.TotalCount).Error; err != nil {
// 使用单次 GROUP BY 查询获取 result 计数
type resultCount struct {
Result string
Count int64
}
var results []resultCount
err := query.Select("result, count(*) as count").Group("result").Scan(&results).Error
if err != nil {
return nil, err
}
if err := query.Where("result = ?", string(model.LoginResultSuccess)).Count(&stats.SuccessCount).Error; err != nil {
return nil, err
// 汇总结果
for _, r := range results {
stats.TotalCount += r.Count
if r.Result == string(model.LoginResultSuccess) {
stats.SuccessCount = r.Count
} else if r.Result == string(model.LoginResultFail) {
stats.FailCount = r.Count
}
}
if err := query.Where("result = ?", string(model.LoginResultFail)).Count(&stats.FailCount).Error; err != nil {
return nil, err
}
if err := query.Where("event = ?", string(model.LoginEventLogin)).Count(&stats.LoginCount).Error; err != nil {
return nil, err
// 单独查询登录次数
if startTime != "" || endTime != "" {
loginQuery := r.db.WithContext(ctx).Model(&model.LoginLog{})
if startTime != "" {
loginQuery = loginQuery.Where("created_at >= ?", startTime)
}
if endTime != "" {
loginQuery = loginQuery.Where("created_at <= ?", endTime)
}
loginQuery.Where("event = ?", string(model.LoginEventLogin)).Count(&stats.LoginCount)
}
return stats, nil