Added automatic database backups.

This commit is contained in:
Patrick Fairbank
2014-08-28 19:32:18 -07:00
parent 5920ea1488
commit 7e974fe36f
5 changed files with 57 additions and 0 deletions

View File

@@ -8,10 +8,16 @@ package main
import (
"bitbucket.org/liamstask/goose/lib/goose"
"database/sql"
"fmt"
"github.com/jmoiron/modl"
_ "github.com/mattn/go-sqlite3"
"io"
"os"
"strings"
"time"
)
const backupsDir = "db/backups"
const migrationsDir = "db/migrations"
type Database struct {
@@ -56,6 +62,30 @@ func (database *Database) Close() {
database.db.Close()
}
// Creates a copy of the current database and saves it to the backups directory.
func (database *Database) Backup() error {
err := os.MkdirAll(backupsDir, 0755)
if err != nil {
return err
}
filename := fmt.Sprintf("%s/%s-%s.db", backupsDir, strings.Replace(eventSettings.Name, " ", "_", -1),
time.Now().Format("20060102150405"))
src, err := os.Open(database.path)
if err != nil {
return err
}
defer src.Close()
dest, err := os.Create(filename)
if err != nil {
return err
}
defer dest.Close()
if _, err := io.Copy(dest, src); err != nil {
return err
}
return nil
}
// Sets up table-object associations.
func (database *Database) mapTables() {
dialect := new(modl.SqliteDialect)

View File

@@ -485,6 +485,12 @@ func CommitMatchScore(match *Match, matchResult *MatchResult) error {
}()
}
// Back up the database, but don't error out if it fails.
err = db.Backup()
if err != nil {
log.Println(err)
}
return nil
}

View File

@@ -218,6 +218,13 @@ func AllianceSelectionFinalizeHandler(w http.ResponseWriter, r *http.Request) {
}
}
// Back up the database.
err = db.Backup()
if err != nil {
handleWebErr(w, err)
return
}
http.Redirect(w, r, "/setup/alliance_selection", 302)
}

View File

@@ -131,6 +131,13 @@ func ScheduleSavePostHandler(w http.ResponseWriter, r *http.Request) {
}
}
// Back up the database.
err = db.Backup()
if err != nil {
handleWebErr(w, err)
return
}
http.Redirect(w, r, "/setup/schedule", 302)
}

View File

@@ -136,6 +136,13 @@ func RestoreDbHandler(w http.ResponseWriter, r *http.Request) {
}
tempDb.Close()
// Back up the current database.
err = db.Backup()
if err != nil {
handleWebErr(w, err)
return
}
// Replace the current database with the new one.
db.Close()
err = os.Rename(tempFilePath, eventDbPath)