-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.go
More file actions
149 lines (119 loc) · 2.37 KB
/
Copy pathdb.go
File metadata and controls
149 lines (119 loc) · 2.37 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package memdb
import (
"sync"
"github.com/tidwall/btree"
)
type dbKey string
type item struct {
key dbKey
value string
}
type dbItem struct {
key dbKey
current *item
pending *item
pendingDeleted bool
sync.RWMutex
}
func (i *item) Less(bitem btree.Item, ctx interface{}) bool {
i2 := bitem.(*item)
index, ok := ctx.(*Index)
if ok {
if index.sortFn(i.value, i2.value) {
return true
}
if index.sortFn(i2.value, i.value) {
return false
}
}
return i.key < i2.key
}
type Items struct {
mu sync.RWMutex
storage map[dbKey]*dbItem
}
func (it *Items) set(key dbKey, item *dbItem) {
it.mu.Lock()
it.storage[key] = item
it.mu.Unlock()
}
func (it *Items) get(key dbKey) *dbItem {
it.mu.RLock()
defer it.mu.RUnlock()
return it.storage[key]
}
func (it *Items) remove(key dbKey) {
it.mu.Lock()
delete(it.storage, key)
it.mu.Unlock()
}
func (it *Items) keys() []dbKey {
keys := make([]dbKey, 0)
it.mu.RLock()
for key := range it.storage {
keys = append(keys, key)
}
it.mu.RUnlock()
return keys
}
type Database struct {
writeTx sync.Mutex
items Items
indexes *Indexes
closed bool
persist bool
persistentStorage *fileStorage
}
func OpenDB(path string, persist bool) (*Database, error) {
db := &Database{
items: Items{storage: make(map[dbKey]*dbItem)},
indexes: newIndexer(),
}
if persist {
var err error
db.persist = true
db.persistentStorage, err = openFileStorage(path)
if err != nil {
return nil, err
}
records := db.persistentStorage.read()
for record := range records {
if record.err != nil {
return nil, err
}
if record.item.command == commandSET {
dbItem := &dbItem{key: record.item.key, current: &record.item.item}
db.items.set(dbItem.key, dbItem)
}
if record.item.command == commandDEL {
db.items.remove(record.item.key)
}
}
}
return db, nil
}
func (db *Database) Close() error {
if db.closed {
return nil
}
err := db.persistentStorage.close()
if err != nil {
return err
}
db.closed = true
db.items = Items{storage: make(map[dbKey]*dbItem)}
db.indexes = newIndexer()
return nil
}
func (db *Database) Begin(writable bool) *Transaction {
tx := &Transaction{
db: db,
}
if writable {
db.writeTx.Lock()
tx.writable = true
tx.pendingItems = make(map[dbKey]struct{})
tx.newIndexes = db.indexes.Copy()
}
return tx
}