feat(repository): enhance repository methods with batch processing and transaction support
- 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:
@@ -89,7 +89,7 @@ func (r *OperationLogRepository) DeleteOldLogs(ctx context.Context, beforeDate s
|
||||
return r.db.WithContext(ctx).Where("created_at < ?", beforeDate).Delete(&model.OperationLog{}).Error
|
||||
}
|
||||
|
||||
// GetStatistics 获取操作日志统计
|
||||
// GetStatistics 获取操作日志统计(使用单次 GROUP BY 查询,避免多次 COUNT)
|
||||
func (r *OperationLogRepository) GetStatistics(ctx context.Context, startTime, endTime string) (*OperationLogStatistics, error) {
|
||||
stats := &OperationLogStatistics{}
|
||||
|
||||
@@ -101,16 +101,25 @@ func (r *OperationLogRepository) GetStatistics(ctx context.Context, startTime, e
|
||||
query = query.Where("created_at <= ?", endTime)
|
||||
}
|
||||
|
||||
if err := query.Count(&stats.TotalCount).Error; err != nil {
|
||||
// 使用单次 GROUP BY 查询获取各状态计数
|
||||
type statusCount struct {
|
||||
Status string
|
||||
Count int64
|
||||
}
|
||||
var results []statusCount
|
||||
err := query.Select("status, count(*) as count").Group("status").Scan(&results).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := query.Where("status = ?", "success").Count(&stats.SuccessCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := query.Where("status = ?", "fail").Count(&stats.FailCount).Error; err != nil {
|
||||
return nil, err
|
||||
// 汇总结果
|
||||
for _, r := range results {
|
||||
stats.TotalCount += r.Count
|
||||
if r.Status == "success" {
|
||||
stats.SuccessCount = r.Count
|
||||
} else if r.Status == "fail" {
|
||||
stats.FailCount = r.Count
|
||||
}
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
|
||||
Reference in New Issue
Block a user