From 34334c773a523e9183ef5c863574a615d1f3d1d4 Mon Sep 17 00:00:00 2001 From: Arnas Udovic Date: Sat, 27 Jan 2024 13:29:23 +0200 Subject: [PATCH] migrations; game counter; next step by order game count --- db.go | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/db.go b/db.go index c23178d..e61f9cf 100644 --- a/db.go +++ b/db.go @@ -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 "" }