diff --git a/core/manager/account/db.go b/core/manager/account/db.go new file mode 100644 index 0000000000..1a5118fae9 --- /dev/null +++ b/core/manager/account/db.go @@ -0,0 +1,49 @@ +package account + +import ( + "encoding/json" + + "github.com/jinzhu/gorm" +) + +type StateDB struct { + gorm *gorm.DB `gorm:"-"` + gorm.Model + + StartCounter int +} + +func OpenStateDB(path string) (*StateDB, error) { + // open db + db, err := gorm.Open("sqlite3", path) + if err != nil { + return nil, err + } + + // create tables and columns + if err := db.AutoMigrate(&StateDB{}).Error; err != nil { + return nil, err + } + + // preload last state + var state StateDB + if err := db.FirstOrInit(&state).Error; err != nil { + return nil, err + } + state.gorm = db + + return &state, nil +} + +func (state StateDB) String() string { + out, _ := json.Marshal(state) + return string(out) +} + +func (state *StateDB) Save() error { + return state.gorm.Save(state).Error +} + +func (state *StateDB) Close() { + state.gorm.Close() +} diff --git a/core/manager/account/db_test.go b/core/manager/account/db_test.go new file mode 100644 index 0000000000..6b95f64049 --- /dev/null +++ b/core/manager/account/db_test.go @@ -0,0 +1,33 @@ +package account + +import ( + "io/ioutil" + "os" + "testing" + + . "github.com/smartystreets/goconvey/convey" +) + +func TestStateDB(t *testing.T) { + Convey("Testing StateDB", t, func() { + tmpFile, err := ioutil.TempFile("", "sqlite") + So(err, ShouldBeNil) + defer os.Remove(tmpFile.Name()) + + state, err := OpenStateDB(tmpFile.Name()) + So(err, ShouldBeNil) + defer state.Close() + So(state.StartCounter, ShouldEqual, 0) + + state.StartCounter++ + So(state.Save(), ShouldBeNil) + So(state.StartCounter, ShouldEqual, 1) + + state.Close() + + state, err = OpenStateDB(tmpFile.Name()) + So(err, ShouldBeNil) + defer state.Close() + So(state.StartCounter, ShouldEqual, 1) + }) +}