migrations; game counter; next step by order game count

This commit is contained in:
Arnas Udovic 2024-01-27 13:29:23 +02:00
parent 7dc505f6f5
commit 34334c773a

38
db.go
View file

@ -6,6 +6,10 @@ import (
_ "github.com/mattn/go-sqlite3"
)
var migrations = []string{
"ALTER TABLE Games ADD count INT DEFAULT 0;",
}
func connectDB() (*sql.DB, error) {
db, err := sql.Open("sqlite3", "./game.db")
if err != nil {
@ -31,12 +35,37 @@ func checkPreinstall(db *sql.DB) error {
INSERT OR IGNORE INTO Stats (name, count) VALUES ('ai_won', 0);
INSERT OR IGNORE INTO Stats (name, count) VALUES ('draw', 0);
INSERT OR IGNORE INTO Stats (name, comment) VALUES ('last_ai_lost', NULL);
INSERT OR IGNORE INTO Stats (name, count) VALUES ('last_migration', 0);
`
_, err := db.Exec(sqlStmt)
if err != nil {
return err
}
err = runMigrations(db)
if err != nil {
return err
}
return nil
}
func runMigrations(db *sql.DB) error {
lastMigration, err := getStatsCounter(db, "last_migration")
if err != nil {
return err
}
for i := lastMigration; i < len(migrations); i++ {
sqlStmt := migrations[i]
_, err := db.Exec(sqlStmt)
if err != nil {
return err
}
db.Exec("UPDATE Stats SET count=count+1 WHERE name='last_migration';")
}
return nil
}
@ -80,6 +109,11 @@ func saveGameLog(db *sql.DB, game *Game) {
game.gameFlow,
game.isFirstWon(),
)
db.Exec(
"UPDATE Games SET count=count+1 WHERE game_flow=? AND first_won=?;",
game.gameFlow,
game.isFirstWon(),
)
if game.isAiWon() {
db.Exec("UPDATE Stats SET count=count+1 WHERE name='ai_won';")
@ -92,7 +126,9 @@ func saveGameLog(db *sql.DB, game *Game) {
}
func getWinnerNextStep(db *sql.DB, game *Game) string {
stmt, err := db.Prepare("SELECT game_flow FROM Games WHERE game_flow LIKE ? AND first_won = ?")
stmt, err := db.Prepare(
"SELECT game_flow FROM Games WHERE game_flow LIKE ? AND first_won = ? ORDER BY count DESC",
)
if err != nil {
return ""
}