From 8aa898376360db32001458726c28f5aef8896807 Mon Sep 17 00:00:00 2001 From: Thomas Rudin Date: Wed, 9 Jan 2019 09:56:36 +0100 Subject: [PATCH] working migration --- db/sqlite.go | 5 +++++ db/sqlite_test.go | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/db/sqlite.go b/db/sqlite.go index b7138cd..c7e98f0 100644 --- a/db/sqlite.go +++ b/db/sqlite.go @@ -4,6 +4,7 @@ import ( "database/sql" _ "github.com/mattn/go-sqlite3" "github.com/sirupsen/logrus" + "time" ) const migrateScript = ` @@ -46,10 +47,14 @@ func (db *Sqlite3Accessor) Migrate() error { if !hasMtime { log.Info("Migrating database") + start := time.Now() _, err = rwdb.Exec(migrateScript) if err != nil { return err } + t := time.Now() + elapsed := t.Sub(start) + log.WithFields(logrus.Fields{"elapsed":elapsed}).Info("Migration completed") } return nil diff --git a/db/sqlite_test.go b/db/sqlite_test.go index f22606c..931e14b 100644 --- a/db/sqlite_test.go +++ b/db/sqlite_test.go @@ -1,6 +1,8 @@ package db import ( + "os" + "io" "fmt" "testing" "io/ioutil" @@ -15,6 +17,8 @@ create table blocks ( ); ` +const testDatabase = "./testdata/map.sqlite" + func createEmptyDatabase(filename string){ db, err := sql.Open("sqlite3", filename) if err != nil { @@ -29,7 +33,31 @@ func createEmptyDatabase(filename string){ db.Close() } -func TestMigrate(t *testing.T){ +func copy(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + + out, err := os.Create(dst) + if err != nil { + return err + } + defer out.Close() + + _, err = io.Copy(out, in) + if err != nil { + return err + } + return out.Close() +} + +func createTestDatabase(filename string) error { + return copy(testDatabase, filename) +} + +func TestMigrateEmpty(t *testing.T){ tmpfile, err := ioutil.TempFile("", "example") if err != nil { panic(err) @@ -45,3 +73,20 @@ func TestMigrate(t *testing.T){ panic(err) } } + +func TestMigrate(t *testing.T){ + tmpfile, err := ioutil.TempFile("", "example") + if err != nil { + panic(err) + } + + createTestDatabase(tmpfile.Name()) + a, err := NewSqliteAccessor(tmpfile.Name()) + if err != nil { + panic(err) + } + err = a.Migrate() + if err != nil { + panic(err) + } +}