Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add a state db for account manager
- Loading branch information
Showing
2 changed files
with
82 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
}) | ||
} |