refactor: 重构数据库逻辑
This commit is contained in:
@@ -2,9 +2,9 @@ package scoresaber
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lxtend.com/qqbot/sqlite3"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
@@ -13,10 +13,8 @@ const wsURL = "wss://scoresaber.com/ws"
|
||||
var ScoresManager = scoresManager{}
|
||||
|
||||
type scoresManager struct {
|
||||
recentScores []Command
|
||||
mu sync.Mutex
|
||||
conn *websocket.Conn
|
||||
retryTimes int
|
||||
conn *websocket.Conn
|
||||
retryTimes int
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -33,7 +31,6 @@ func (sm *scoresManager) connect() error {
|
||||
return err
|
||||
}
|
||||
sm.retryTimes = 0
|
||||
sm.recentScores = make([]Command, 0)
|
||||
go sm.receiveData()
|
||||
return nil
|
||||
}
|
||||
@@ -58,25 +55,24 @@ func (sm *scoresManager) receiveData() {
|
||||
continue
|
||||
}
|
||||
SSQuery.SaveRecord(cmd.CommandData)
|
||||
if cmd.CommandData.Score.LeaderboardPlayerInfo.Country != "CN" {
|
||||
continue
|
||||
}
|
||||
sm.mu.Lock()
|
||||
if len(sm.recentScores) >= 50 {
|
||||
sm.recentScores = sm.recentScores[1:]
|
||||
}
|
||||
sm.recentScores = append(sm.recentScores, cmd)
|
||||
sm.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (sm *scoresManager) GetRecentScores(count int) []Command {
|
||||
sm.mu.Lock()
|
||||
defer sm.mu.Unlock()
|
||||
if count > len(sm.recentScores) {
|
||||
count = len(sm.recentScores)
|
||||
func (sm *scoresManager) GetRecentScores(count int, predict string) []RecordDataLite {
|
||||
db := sqlite3.GetDB() // 假设 sqlite3.GetDB() 返回 *sqlx.DB
|
||||
scoresCopy := make([]RecordDataLite, 0, count)
|
||||
|
||||
query := "SELECT * FROM ssRecordData"
|
||||
if predict != "" {
|
||||
query += " " + predict
|
||||
}
|
||||
scoresCopy := make([]Command, count)
|
||||
copy(scoresCopy, sm.recentScores[len(sm.recentScores)-count:])
|
||||
query += " ORDER BY generated_time DESC LIMIT ?"
|
||||
|
||||
err := db.Select(&scoresCopy, query, count)
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return scoresCopy
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user