Skip to content

Commit

Permalink
feat: add a state db for account manager
Browse files Browse the repository at this point in the history
  • Loading branch information
moul committed Nov 2, 2018
1 parent c5b13e6 commit 03d4b63
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
49 changes: 49 additions & 0 deletions 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()
}
33 changes: 33 additions & 0 deletions 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)
})
}

0 comments on commit 03d4b63

Please sign in to comment.