-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.go
67 lines (54 loc) · 1.11 KB
/
storage.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
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"log"
"os"
"sync"
"time"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
const BatchSize = 2000
var state struct {
Db *gorm.DB
DbMutex sync.Mutex
}
func init() {
//openDatabase("keys.db")
}
func openDatabase(path string) {
d := sqlite.Open(path)
db, err := gorm.Open(d, &gorm.Config{
Logger: logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags),
logger.Config{
SlowThreshold: time.Second,
IgnoreRecordNotFoundError: true,
},
),
})
if err != nil {
panic(err)
}
state.Db = db
if db.Migrator().HasTable(Key{}) {
db.Migrator().AutoMigrate(Key{})
return
}
if err = db.Migrator().CreateTable(Key{}); err != nil {
panic(err)
}
}
type Keys struct{}
func (Keys) Save(keys []Key) error {
state.DbMutex.Lock()
defer state.DbMutex.Unlock()
return state.Db.CreateInBatches(keys, BatchSize).Error
}
func (Keys) Scan(offset, limit int) ([]Key, error) {
state.DbMutex.Lock()
defer state.DbMutex.Unlock()
var result []Key
err := state.Db.Model(Key{}).Order("id").Offset(offset).Limit(limit).Find(&result).Error
return result, err
}