61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
package store
|
|
|
|
import (
|
|
"speedtest/internal/db"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// ResultStore 测速结果数据访问层
|
|
type ResultStore struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewResultStore creates a new ResultStore.
|
|
func NewResultStore(database *gorm.DB) *ResultStore {
|
|
return &ResultStore{db: database}
|
|
}
|
|
|
|
// Create 保存一次测速结果
|
|
func (s *ResultStore) Create(r *db.SpeedTestResult) error {
|
|
return s.db.Create(r).Error
|
|
}
|
|
|
|
// TopBy 按指定列排序取 [offset, offset+limit) 条(col 为白名单列名,asc 控制方向)
|
|
func (s *ResultStore) TopBy(col string, asc bool, limit, offset int) ([]db.SpeedTestResult, error) {
|
|
var results []db.SpeedTestResult
|
|
order := col + " DESC"
|
|
if asc {
|
|
order = col + " ASC"
|
|
}
|
|
err := s.db.Order(order).Limit(limit).Offset(offset).Find(&results).Error
|
|
return results, err
|
|
}
|
|
|
|
// GetByID 按 ID 查询单条记录
|
|
func (s *ResultStore) GetByID(id uint) (*db.SpeedTestResult, error) {
|
|
var r db.SpeedTestResult
|
|
if err := s.db.First(&r, id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &r, nil
|
|
}
|
|
|
|
// CountBetter 统计比指定值更优的记录数(用于计算记录的真实排名)
|
|
func (s *ResultStore) CountBetter(col string, asc bool, value float64) (int64, error) {
|
|
op := ">"
|
|
if asc {
|
|
op = "<"
|
|
}
|
|
var n int64
|
|
err := s.db.Model(&db.SpeedTestResult{}).Where(col+" "+op+" ?", value).Count(&n).Error
|
|
return n, err
|
|
}
|
|
|
|
// Count 返回测速总次数
|
|
func (s *ResultStore) Count() (int64, error) {
|
|
var total int64
|
|
err := s.db.Model(&db.SpeedTestResult{}).Count(&total).Error
|
|
return total, err
|
|
}
|