This repository has been archived on 2022-06-29. You can view files and clone it, but cannot push or open issues or pull requests.
urtrator/database/database_object.go
pztrn ac938c16eb Initial commit, what works:
* Servers update
* Profile creation/edit/deletion
* Game launching
* Checks server version <> profile version.
2016-10-04 15:42:36 +05:00

77 lines
2.0 KiB
Go

// URTator - Urban Terror server browser and game launcher, written in
// Go.
//
// Copyright (c) 2016, Stanslav N. a.k.a pztrn (or p0z1tr0n)
// All rights reserved.
//
// Licensed under Terms and Conditions of GNU General Public License
// version 3 or any higher.
// ToDo: put full text of license here.
package database
import (
// stdlib
//"database/sql"
"fmt"
"path"
"strconv"
// local
"github.com/pztrn/urtrator/datamodels"
// Other
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
type Database struct {
// Pointer to initialized database connection.
Db *sqlx.DB
}
func (d *Database) Close() {
fmt.Println("Closing database...")
d.Db.Close()
}
func (d *Database) Initialize() {
fmt.Println("Initializing database...")
// Connect to database.
db_path := path.Join(cfg.TEMP["DATA"], "database.sqlite3")
fmt.Println("Database path: " + db_path)
db, err := sqlx.Connect("sqlite3", db_path)
if err != nil {
fmt.Println(err.Error())
}
d.Db = db
}
func (d *Database) Migrate() {
// Getting current database version.
dbver := 0
database := []datamodels.Database{}
d.Db.Select(&database, "SELECT * FROM database")
if len(database) > 0 {
fmt.Println("Current database version: " + database[0].Version)
dbver, _ = strconv.Atoi(database[0].Version)
} else {
fmt.Println("No database found, will create new one")
}
migrate_full(d, dbver)
}
func (d *Database) UpdateServers(data map[string]*datamodels.Server) {
fmt.Println("Updating servers information in database...")
// ToDo: real update :)
d.Db.MustExec("DELETE FROM servers")
tx := d.Db.MustBegin()
for _, srv := range data {
tx.NamedExec("INSERT INTO servers (ip, port, name, ping, players, maxplayers, gamemode, map, version) VALUES (:ip, :port, :name, :ping, :players, :maxplayers, :gamemode, :map, :version)", srv)
}
tx.Commit()
fmt.Println("Done")
}