forked from elastos/Elastos.ELA.SPV
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
55 lines (43 loc) · 936 Bytes
/
state.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package sqlite
import (
"database/sql"
"sync"
)
const CreateStateDB = `CREATE TABLE IF NOT EXISTS State(
Key NOT NULL PRIMARY KEY,
Value BLOB NOT NULL
);`
const (
HeightKey = "Height"
)
// Ensure state implement State interface.
var _ State = (*state)(nil)
type state struct {
*sync.RWMutex
*sql.DB
}
func NewState(db *sql.DB, lock *sync.RWMutex) (*state, error) {
_, err := db.Exec(CreateStateDB)
if err != nil {
return nil, err
}
return &state{RWMutex: lock, DB: db}, nil
}
// get state height
func (s *state) GetHeight() uint32 {
s.RLock()
defer s.RUnlock()
row := s.QueryRow("SELECT Value FROM State WHERE Key=?", HeightKey)
var height uint32
err := row.Scan(&height)
if err != nil {
return 0
}
return height
}
// save state height
func (s *state) PutHeight(height uint32) {
s.Lock()
defer s.Unlock()
s.Exec("INSERT OR REPLACE INTO State(Key, Value) VALUES(?,?)", HeightKey, height)
}