-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
82 lines (70 loc) · 1.45 KB
/
db.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package edb
import (
"fmt"
"time"
"go.etcd.io/bbolt"
)
type DB struct {
bdb *bbolt.DB
schema *Schema
logf func(format string, args ...any)
verbose bool
strict bool
tableStates []*tableState
}
type Options struct {
Logf func(format string, args ...any)
Verbose bool
IsTesting bool
}
func Open(path string, schema *Schema, opt Options) (*DB, error) {
bopt := &bbolt.Options{
Timeout: 10 * time.Second,
}
*bopt = *bbolt.DefaultOptions
if opt.IsTesting {
bopt.NoSync = true
bopt.NoFreelistSync = true
bopt.InitialMmapSize = 1024 * 1024
} else {
bopt.InitialMmapSize = 1024 * 1024 * 1024
bopt.FreelistType = bbolt.FreelistMapType
}
bdb, err := bbolt.Open(path, 0666, bopt)
if err != nil {
return nil, fmt.Errorf("kvdb: %w", err)
}
db := &DB{
bdb: bdb,
schema: schema,
logf: opt.Logf,
verbose: opt.Verbose,
tableStates: make([]*tableState, len(schema.tables)),
strict: opt.IsTesting,
}
db.Write(func(tx *Tx) {
now := time.Now()
for i, tbl := range schema.tables {
db.tableStates[i] = prepareTable(tx, tbl, now)
}
for _, mp := range schema.maps {
prepareMap(tx, mp)
}
for _, ts := range db.tableStates {
ts.migrate(tx)
}
for _, ts := range db.tableStates {
ts.save(tx)
}
})
return db, nil
}
func (db *DB) Bolt() *bbolt.DB {
return db.bdb
}
func (db *DB) Close() {
err := db.bdb.Close()
if err != nil {
panic(fmt.Errorf("kvdb: closing: %w", err))
}
}